-
Notifications
You must be signed in to change notification settings - Fork 0
/
flags.go
105 lines (84 loc) · 2.5 KB
/
flags.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
package main
import (
"errors"
"flag"
"strings"
"github.com/gravitational/trace"
"github.com/mailgun/log"
"io/ioutil"
)
const (
// defaultAuthFilePath is used in the flags list
defaultAuthFilePath = "./userlist"
)
var (
// ErrBadFlag is returned whenever the user has improperly run the program.
ErrBadFlag = errors.New("command was run improperly, check --help")
)
// NOTE: flags can be defined anywhere, they're defined as a block here
// to see the command-line UX as a whole.
var (
// flagAuth is path to textfile of authorized users.
flagAuthFile = flag.String("auth",
defaultAuthFilePath,
"What file contains a list of authorized users")
// flagSlackToken is a slack token.
flagSlackToken = flag.String("slack_token",
"",
"Specify the slack token")
// github_token is a github token.
flagGitHubToken = flag.String("github_token",
"",
"Specify the github oauth token")
)
type config struct {
slackToken string
gitHubToken string
authFile string
authedUsers []string
}
func init() {
flag.Parse()
}
// flagHelper calls populateFlags with the flags above. These functions are
// seperate to allow unit testing the logic in populateFlags.
func flagHelper() (config, error) {
c, err := populateFlags(*flagSlackToken, *flagGitHubToken, *flagAuthFile)
if err != nil {
return c, err
}
err = c.loadAuthedUsers()
return c, err
}
// populateFlags checks flag validity and initializes a "config" struct.
func populateFlags(slackToken, gitHubToken, authFile string) (config, error) {
c := config{}
// NOTE: It's more efficient (in the long run) to copy this structure by value
// TODO: Implement an errors structure that contains an []error.
// It must implement the "Error" interface.
// It will have a receiver function .contains(err) to check if the error contains.
var err error
if len(slackToken) == 0 {
log.Errorf("You must specify a Slack token with --slack_token")
err = ErrBadFlag
}
c.slackToken = slackToken
c.gitHubToken = gitHubToken
c.authFile = authFile
if err != nil {
flag.PrintDefaults()
return c, trace.Wrap(err)
}
return c, trace.Wrap(err)
}
// loadAuthedUsers maps a newline deliminated list of users to a string slice.
func (c *config) loadAuthedUsers() error {
authFileContents, err := ioutil.ReadFile(c.authFile)
if err != nil {
return trace.Wrap(err)
}
authedUsers := strings.Split(string(authFileContents), "\n")
// NOTE: The last slice element after strings.Split is empty, so truncate
c.authedUsers = authedUsers[:len(authedUsers)-1]
return nil
}