-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.go
93 lines (83 loc) · 2.29 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
package main
import (
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"github.com/keybase/go-keychain"
"github.com/shiimaxx/alfred-gitlab-workflow/workflow"
)
// Exit codes are int values that represent an exit code for a particular error.
const (
ExitCodeOK int = 0
ExitCodeError int = 1 + iota
)
// CLI is the command line object
type CLI struct {
// outStream and errStream are the stdout and stderr
// to write message from the CLI.
outStream, errStream io.Writer
}
// Run invokes the CLI with the given arguments.
func (c *CLI) Run(args []string) int {
var refresh bool
flags := flag.NewFlagSet("alfred-gitlab-workflow", flag.ContinueOnError)
flags.SetOutput(c.outStream)
flags.BoolVar(&refresh, "refresh", false, "force fetch projects")
if err := flags.Parse(args[1:]); err != nil {
return ExitCodeError
}
urlFlags := flag.NewFlagSet("set-url", flag.ContinueOnError)
tokenFlags := flag.NewFlagSet("set-token", flag.ContinueOnError)
if len(args) > 1 {
switch args[1] {
case "set-url":
urlFlags.Parse(args[2:])
case "set-token":
tokenFlags.Parse(args[2:])
}
if urlFlags.Parsed() {
f, err := os.OpenFile("./endpoint_url", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0664)
if err != nil {
fmt.Fprint(c.errStream, err)
return ExitCodeError
}
url := urlFlags.Args()[0]
if _, err := f.Write([]byte(url)); err != nil {
fmt.Fprint(c.errStream, err)
return ExitCodeError
}
if err := f.Close(); err != nil {
fmt.Fprint(c.errStream, err)
return ExitCodeError
}
return ExitCodeOK
}
if tokenFlags.Parsed() {
item := keychain.NewGenericPassword("alfred-gitlab-workflow", "", "", []byte(tokenFlags.Args()[0]), "")
item.SetAccessible(keychain.AccessibleWhenUnlocked)
if err := keychain.AddItem(item); err != nil {
fmt.Fprint(c.errStream, err)
return ExitCodeError
}
return ExitCodeOK
}
}
var url string
if _, err := os.Stat("endpoint_url"); !os.IsNotExist(err) {
d, err := ioutil.ReadFile("endpoint_url")
if err != nil {
fmt.Fprint(c.errStream, err)
return ExitCodeError
}
url = string(d)
}
b, err := keychain.GetGenericPassword("alfred-gitlab-workflow", "", "", "")
if err != nil {
fmt.Fprint(c.errStream, err)
return ExitCodeError
}
fmt.Fprint(c.outStream, workflow.Run(url, string(b), refresh))
return ExitCodeOK
}