-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
99 lines (81 loc) · 2.55 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
package main
import (
"errors"
"fmt"
"log/slog"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/crissyfield/powerhouse/cmd"
)
// Version will be set during build.
var Version = "(unknown)"
// CmdRoot defines the CLI root command.
var CmdRoot = &cobra.Command{
Use: "powerhouse",
Long: "...",
Args: cobra.NoArgs,
Version: Version,
CompletionOptions: cobra.CompletionOptions{DisableDefaultCmd: true},
PersistentPreRunE: setup,
}
// Initialize CLI options.
func init() {
// Logging
CmdRoot.PersistentFlags().StringP("log-level", "l", "info", "verbosity of logging output")
CmdRoot.PersistentFlags().BoolP("log-as-json", "j", false, "change logging format to JSON")
// Subcommands
CmdRoot.AddCommand(cmd.CmdList)
CmdRoot.AddCommand(cmd.CmdMeasure)
}
// setup will set up configuration management and logging.
//
// Configuration options can be set via the command line, via a configuration file (in the current folder, at
// "/etc/powerhouse/config.yaml" or at "~/.config/powerhouse/config.yaml"), and via environment variables
// (all uppercase and prefixed with "POWERHOUSE_").
func setup(cmd *cobra.Command, _ []string) error {
// Connect all options to Viper
err := viper.BindPFlags(cmd.Flags())
if err != nil {
return fmt.Errorf("bind command line flags: %w", err)
}
// Environment variables
viper.SetEnvPrefix("POWERHOUSE")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
viper.AutomaticEnv()
// Configuration file
viper.SetConfigName("config")
viper.AddConfigPath("/etc/powerhouse")
viper.AddConfigPath(os.Getenv("HOME") + "/.config/powerhouse")
viper.AddConfigPath(".")
// Configuration file
if err := viper.ReadInConfig(); err != nil {
// Don't fail if config not found
if !errors.As(err, &viper.ConfigFileNotFoundError{}) {
return fmt.Errorf("read config file: %w", err)
}
}
// Logging
var level slog.Level
err = level.UnmarshalText([]byte(viper.GetString("log-level")))
if err != nil {
return fmt.Errorf("parse log level: %w", err)
}
var handler slog.Handler
if viper.GetBool("log-as-json") {
// Use JSON handler
handler = slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: level})
} else {
// Use text handler
handler = slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: level})
}
slog.SetDefault(slog.New(handler))
return nil
}
// main is the main entry point of the command.
func main() {
if err := CmdRoot.Execute(); err != nil {
slog.Error("Unable to execute command", slog.Any("error", err))
}
}