generated from gopherdojo/template
-
Notifications
You must be signed in to change notification settings - Fork 181
/
Copy pathcli.go
91 lines (78 loc) · 2.13 KB
/
cli.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
package imgconv
import (
"flag"
"fmt"
"io"
"os"
)
// CLI is the command line interface
type CLI struct {
OutStream, ErrStream io.Writer
}
// validateType validates the type of the image
func validateType(t string) error {
switch t {
case "jpg", "jpeg", "png", "gif":
return nil
default:
return fmt.Errorf("invalid type: %s", t)
}
}
// Run parses the command line arguments and runs the imgConv
func (cli *CLI) Run() int {
config := &Config{}
fs := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
fs.StringVar(&config.InputType, "input-type", "jpg", "input type[jpg|jpeg|png|gif]")
fs.StringVar(&config.OutputType, "output-type", "png", "output type[jpg|jpeg|png|gif]")
fs.SetOutput(cli.ErrStream)
fs.Usage = func() {
fmt.Fprintf(cli.ErrStream, "Usage: %s [options] DIRECTORY\n", "imgconv")
fs.PrintDefaults()
}
if err := fs.Parse(os.Args[1:]); err != nil {
fmt.Fprintf(cli.ErrStream, "Error parsing arguments: %s\n", err)
return 1
}
if err := validateType(config.InputType); err != nil {
fmt.Fprintf(cli.ErrStream, "invalid input type: %s\n", err)
return 1
}
if err := validateType(config.OutputType); err != nil {
fmt.Fprintf(cli.ErrStream, "invalid output type: %s\n", err)
return 1
}
if config.InputType == config.OutputType {
fmt.Fprintf(cli.ErrStream, "input type and output type must be different\n")
return 1
}
if fs.Arg(0) == "" {
fmt.Fprintf(cli.ErrStream, "directory is required\n")
return 1
}
config.Directory = fs.Arg(0)
dec, err := NewDecoder(config.InputType)
if err != nil {
fmt.Fprintf(cli.ErrStream, "failed to create decoder: %s\n", err)
return 1
}
enc, err := NewEncoder(config.OutputType)
if err != nil {
fmt.Fprintf(cli.ErrStream, "failed to create encoder: %s\n", err)
return 1
}
imgConv := &ImgConv{
Decoder: dec,
Encoder: enc,
TargetDir: config.Directory,
}
convertedFiles, err := imgConv.Run()
if err != nil {
fmt.Fprintf(cli.ErrStream, "failed to convert images: %s\n", err)
return 1
}
fmt.Fprintf(cli.OutStream, "converted %d files\n", len(convertedFiles))
for _, f := range convertedFiles {
fmt.Fprintf(cli.OutStream, "%s\n", f)
}
return 0
}