-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
107 lines (82 loc) · 2.27 KB
/
main.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
package main
import (
"os"
"reflect"
"strings"
commands "github.com/kekaadrenalin/dockhook/pkg/command"
argsType "github.com/kekaadrenalin/dockhook/pkg/types"
log "github.com/sirupsen/logrus"
"github.com/alexflint/go-arg"
)
func main() {
args, subcommand := parseArgs()
validateEnvVars()
if subcommand != nil {
switch subcommand.(type) {
case *argsType.HealthcheckCmd:
if err := commands.Healthcheck(args.Addr, args.Base); err != nil {
log.Fatal(err)
}
case *argsType.CreateUserCmd:
newUser, err := commands.CreateUser(args)
if err != nil {
log.Fatalf("Could not create new user: %s", err)
}
log.Infof("User %s successfully saved", newUser.Username)
log.Infof("Password hash: %s", newUser.Password)
case *argsType.CreateWebhookCmd:
webhook, err := commands.CreateWebhook(args)
if err != nil {
log.Fatalf("Could not create new webhook: %s", err)
}
log.Infoln("Webhook successfully saved", webhook)
log.Infof("UUID: %s", webhook.UUID)
}
os.Exit(0)
}
commands.Default(args)
}
func parseArgs() (argsType.Args, interface{}) {
var args argsType.Args
parser := arg.MustParse(&args)
configureLogger(args.Level)
args.Filter = make(map[string][]string)
for _, filter := range args.FilterStrings {
pos := strings.Index(filter, "=")
if pos == -1 {
parser.Fail("each filter should be of the form key=value")
}
key := filter[:pos]
val := filter[pos+1:]
args.Filter[key] = append(args.Filter[key], val)
}
return args, parser.Subcommand()
}
func configureLogger(level string) {
if l, err := log.ParseLevel(level); err == nil {
log.SetLevel(l)
} else {
panic(any(err))
}
log.SetFormatter(&log.TextFormatter{
DisableLevelTruncation: true,
})
}
func validateEnvVars() {
argsType := reflect.TypeOf(argsType.Args{})
expectedEnvs := make(map[string]bool)
for i := 0; i < argsType.NumField(); i++ {
field := argsType.Field(i)
for _, tag := range strings.Split(field.Tag.Get("arg"), ",") {
if strings.HasPrefix(tag, "env:") {
expectedEnvs[strings.TrimPrefix(tag, "env:")] = true
}
}
}
for _, env := range os.Environ() {
actual := strings.Split(env, "=")[0]
if strings.HasPrefix(actual, "DOCKHOOK_") && !expectedEnvs[actual] {
log.Warnf("Unexpected environment variable %s", actual)
}
}
}