-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcli.go
127 lines (110 loc) · 2.34 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package ghg
import (
"context"
"fmt"
"io"
"log"
"os"
"path/filepath"
"github.com/Songmu/gitconfig"
"github.com/jessevdk/go-flags"
)
const (
exitCodeOK = iota
exitCodeParseFlagErr
exitCodeErr
)
type ghOpts struct {
Get getCommand `description:"get stuffs" command:"get" subcommands-optional:"true"`
Bin binCommand `description:"display bin dir" command:"bin" subcommands-optional:"true"`
Ver verCommand `description:"display version" command:"version" subcommands-optional:"true"`
}
type getCommand struct {
targets []string
Upgrade bool `short:"u" description:"overwrite the executable even if exists"`
}
func (g *getCommand) Execute(args []string) error {
gHome, err := ghgHome()
if err != nil {
return err
}
ctx := context.TODO()
ghcli := getOctCli(ctx, getToken())
for _, target := range args {
gh := &ghg{
ghgHome: gHome,
target: target,
client: ghcli,
upgrade: g.Upgrade,
}
err := gh.get(ctx)
if err != nil {
return err
}
}
log.Printf("done!")
return nil
}
// EnvHome is key of enviroment variable represents ghg home
const EnvHome = "GHG_HOME"
func ghgHome() (string, error) {
ghome := os.Getenv(EnvHome)
if ghome != "" {
return ghome, nil
}
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, ".ghg"), nil
}
func ghgBin() (string, error) {
home, err := ghgHome()
if err != nil {
return "", err
}
return filepath.Join(home, "bin"), nil
}
type binCommand struct{}
func (b *binCommand) Execute(args []string) error {
bin, err := ghgBin()
if err != nil {
return err
}
fmt.Println(bin)
return nil
}
type verCommand struct{}
func (b *verCommand) Execute(args []string) error {
fmt.Printf("ghg version: %s (rev: %s)\n", version, revision)
return nil
}
// CLI is struct for command line tool
type CLI struct {
OutStream, ErrStream io.Writer
}
// Run the ghg
func (cli *CLI) Run(argv []string) int {
log.SetOutput(cli.ErrStream)
log.SetFlags(0)
err := parseArgs(argv)
if err != nil {
if ferr, ok := err.(*flags.Error); ok {
if ferr.Type == flags.ErrHelp {
return exitCodeOK
}
return exitCodeParseFlagErr
}
return exitCodeErr
}
return exitCodeOK
}
func getToken() string {
token, _ := gitconfig.GitHubToken("")
return token
}
func parseArgs(args []string) error {
opts := &ghOpts{}
_, err := flags.ParseArgs(opts, args)
return err
}