-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcli.go
80 lines (66 loc) · 2 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
package main
import (
"flag"
"fmt"
"io"
"github.com/hidapple/isbn-gen/isbn"
"github.com/olekukonko/tablewriter"
)
const (
exitCodeOK int = iota
exitCodeErr
)
// CLI represents command line interface.
type CLI struct {
outStream, errStream io.Writer
}
// Run parses command line and execute it with given flags.
func (cli *CLI) Run(args []string) int {
var (
idGrp string
code string
version bool
list bool
)
flags := flag.NewFlagSet(Name, flag.ContinueOnError)
flags.SetOutput(cli.errStream)
// Bind flag params
flags.BoolVar(&version, "version", false, "Print version information and quit")
flags.BoolVar(&version, "v", false, "Print version information and quit")
flags.BoolVar(&list, "list", false, "Print supported registration group identifier list")
flags.BoolVar(&list, "l", false, "Print supported registration group identifier list")
flags.StringVar(&idGrp, "id", "jp", "Registration group identifier of ISBN")
flags.StringVar(&idGrp, "id-group", "jp", "Registration group identifier of ISBN")
flags.StringVar(&code, "code", "", "The code part pregix of ISBN")
flags.StringVar(&code, "c", "", "The code part pregix of ISBN")
// Parse commandline flag
if err := flags.Parse(args[1:]); err != nil {
return exitCodeErr
}
// Show version
if version {
fmt.Fprintf(cli.outStream, "%s version %s (rev: %s)\n", Name, Version, Revision)
return exitCodeOK
}
// Show supported registration group list
if list {
cli.printSupportedGroups()
return exitCodeOK
}
// Generate ISBN
isbn, err := isbn.NewISBN(idGrp, code)
if err != nil {
fmt.Fprintf(cli.errStream, "%v\n", err.Error())
return exitCodeErr
}
fmt.Fprintln(cli.outStream, isbn.Number())
return exitCodeOK
}
func (cli *CLI) printSupportedGroups() {
table := tablewriter.NewWriter(cli.outStream)
table.SetHeader([]string{"identifying group", "abbreviation", "prefix", "identifier"})
for _, v := range isbn.Identifiers {
table.Append([]string{v.GroupName, v.Abbreviation, v.Prefix, v.Identifier})
}
table.Render()
}