-
Notifications
You must be signed in to change notification settings - Fork 90
/
do_init.go
65 lines (57 loc) · 1.45 KB
/
do_init.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
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"github.com/mackerelio/mackerel-agent/config"
)
func doInitialize(fs *flag.FlagSet, argv []string) error {
var (
conffile = fs.String("conf", config.DefaultConfig.Conffile, "Config file path")
apikey = fs.String("apikey", "", "API key from mackerel.io web site (Required)")
)
err := fs.Parse(argv)
if err != nil {
return err
}
if *apikey == "" {
// Setting apikey via environment variable should be supported or not?
return fmt.Errorf("-apikey option is required")
}
// make the config file directory if not exist
root := filepath.Dir(*conffile)
if _, err := os.Stat(root); err != nil {
if !os.IsNotExist(err) {
return err
}
err := os.MkdirAll(root, 0755)
if err != nil {
return err
}
}
_, err = os.Stat(*conffile)
confExists := err == nil
if confExists {
conf, err := config.LoadConfig(*conffile)
if err != nil {
return fmt.Errorf("failed to load the config file: %s", err)
}
if conf.Apikey != "" {
return apikeyAlreadySetError(*conffile)
}
}
contents := []byte(fmt.Sprintf("apikey = %q\n", *apikey))
if confExists {
cBytes, err := os.ReadFile(*conffile)
if err != nil {
return err
}
contents = append(contents, cBytes...)
}
return os.WriteFile(*conffile, contents, 0644)
}
type apikeyAlreadySetError string
func (a apikeyAlreadySetError) Error() string {
return fmt.Sprintf("apikey already set in %q. Skip initializing", string(a))
}