-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
111 lines (93 loc) · 2.23 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"image"
"image/color"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"os"
ctools "github.com/gookit/color"
_ "golang.org/x/image/bmp"
_ "golang.org/x/image/tiff"
_ "golang.org/x/image/webp"
"golang.org/x/term"
"github.com/tomasruud/dog/ansi"
)
func main() {
flag := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
bg := flag.String("bg", "light", "Background color, availble values: [white, gray, black]")
colors := flag.String("color", "auto", "Color level, available values: [auto, 16, 256, rgb]")
flag.Usage = func() {
fmt.Fprintln(flag.Output(), "Dump out graphics (dog) 🐶")
fmt.Fprintln(flag.Output(), "A friendly, cat-like image previewer for your terminal.")
fmt.Fprintln(flag.Output(), "")
fmt.Fprintln(flag.Output(), "Syntax: dog [OPTIONS] [FILE]")
fmt.Fprintln(flag.Output(), "")
fmt.Fprintln(flag.Output(), "Available options:")
flag.PrintDefaults()
}
flag.Parse(os.Args[1:])
var in io.Reader
if term.IsTerminal(int(os.Stdin.Fd())) {
if flag.NArg() < 1 {
flag.Usage()
os.Exit(1)
}
raw, err := os.ReadFile(flag.Arg(0))
if err != nil {
exit("Unable to read file", err)
}
in = bytes.NewBuffer(raw)
} else {
raw, err := io.ReadAll(os.Stdin)
if err != nil {
exit("Unable to read pipe", err)
}
in = bytes.NewBuffer(raw)
}
w, h, err := term.GetSize(int(os.Stdout.Fd()))
if err != nil {
exit("Unable to determine terminal dimensions", err)
}
img, _, err := image.Decode(in)
if err != nil {
exit("Unable to decode image data", err)
}
matte := color.White
switch *bg {
case "black":
matte = color.Black
case "gray":
matte = color.Gray16{0xAAAA}
}
level := ctools.TermColorLevel()
switch *colors {
case "16":
level = ctools.Level16
case "256":
level = ctools.Level256
case "rgb":
level = ctools.LevelRgb
}
if level == ctools.LevelNo {
exit("Unable to determine color level", errors.New("level was none"))
}
enc := ansi.Encoder{
MaxW: w,
MaxH: h,
Matte: matte,
ColorLevel: level,
}
if err := enc.Encode(os.Stdout, img); err != nil {
exit("Unable to encode image data", err)
}
}
func exit(msg string, err error) {
fmt.Fprintf(os.Stderr, "%s: %v\n", msg, err)
os.Exit(1)
}