-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
83 lines (69 loc) · 1.76 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
package main
import (
"fmt"
"os"
"github.com/go-zoox/cli"
"github.com/go-zoox/fs"
"github.com/go-zoox/fs/type/yaml"
"github.com/go-zoox/gztinypng/tinypng"
)
var configDir = fs.JoinHomeDir(".config/go-zoox")
var tinypngConfigPath = fs.JoinPath(configDir, "gztinypng.yml")
func main() {
app := cli.NewSingleProgram(&cli.SingleProgramConfig{
Name: "gztinypng",
Usage: "TinyPNG cli, easy way to compress images",
Version: Version,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "input",
Usage: "input image file",
Aliases: []string{"i"},
Required: true,
},
&cli.StringFlag{
Name: "output",
Usage: "output image file",
Aliases: []string{"o"},
Required: true,
},
&cli.StringFlag{
Name: "api-key",
Usage: "tinypng api key",
},
},
})
app.Command(func(ctx *cli.Context) (err error) {
cfg := tinypng.Config{}
if !fs.IsExist(configDir) {
if err := fs.Mkdirp(configDir); err != nil {
return fmt.Errorf("failed to create config directory: %v", err)
}
}
if fs.IsExist(tinypngConfigPath) {
if err := yaml.Read(tinypngConfigPath, &cfg); err != nil {
return fmt.Errorf("failed to read config file: %v", err)
}
}
if ctx.String("api-key") != "" {
cfg.ApiKey = ctx.String("api-key")
}
input := ctx.String("input")
output := ctx.String("output")
cfg.InputFile, err = fs.Open(input)
if err != nil {
return fmt.Errorf("failed to open input image: %v", err)
}
defer cfg.InputFile.Close()
cfg.OutputFile, err = os.Create(output)
if err != nil {
return fmt.Errorf("failed to open output image: %v", err)
}
defer cfg.OutputFile.Close()
if cfg.ApiKey == "" {
return fmt.Errorf("api key is required")
}
return tinypng.TinyPNG(&cfg)
})
app.Run()
}