-
Notifications
You must be signed in to change notification settings - Fork 1
/
root.go
62 lines (49 loc) · 1.44 KB
/
root.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
package cli
import (
"fmt"
"github.com/joho/godotenv"
"github.com/roadrunner-server/errors"
"github.com/rumorsflow/rumors/internal/cli/serve"
"github.com/spf13/cobra"
"os"
"path/filepath"
)
const envDotenv string = "DOTENV_PATH"
func NewCommand(args []string, version string) *cobra.Command {
var cfgFile string
var dotenv string
cmd := &cobra.Command{
Use: filepath.Base(args[0]),
Short: "Rumors CLI",
SilenceErrors: true,
SilenceUsage: true,
Version: version,
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
cmd.Version = version
// cfgFile could be defined by user or default `config.yaml`
// this check added just to be safe
if cfgFile == "" {
return errors.Str("no configuration file provided")
}
// try to get the absolute path to the configuration
if absPath, err := filepath.Abs(cfgFile); err == nil {
cfgFile = absPath // switch config path to the absolute
}
if v, ok := os.LookupEnv(envDotenv); ok { // read path to the dotenv file from environment variable
dotenv = v
}
if dotenv != "" {
if err := godotenv.Load(dotenv); err != nil {
return err
}
}
return nil
},
}
f := cmd.PersistentFlags()
f.StringVarP(&cfgFile, "config", "c", "config.yaml", "config file")
f.StringVar(&dotenv, "dotenv", "", fmt.Sprintf("dotenv file [$%s]", envDotenv))
_ = f.Parse(args[1:])
cmd.AddCommand(serve.NewCommand(cfgFile))
return cmd
}