cmd: remove global state in main.go

* refactoring
* Now supporting default config locations
This commit is contained in:
Christian Schwarz
2017-09-17 18:20:05 +02:00
parent 4ac7e78e2b
commit 9cd83399d3
9 changed files with 148 additions and 77 deletions

View File

@ -12,6 +12,7 @@ import (
"github.com/kr/pretty"
"github.com/spf13/cobra"
"github.com/zrepl/zrepl/zfs"
"log"
)
var testCmd = &cobra.Command{
@ -19,6 +20,11 @@ var testCmd = &cobra.Command{
Short: "test configuration",
}
var testCmdGlobal struct {
log Logger
conf *Config
}
var testConfigSyntaxCmd = &cobra.Command{
Use: "config",
Short: "parse config file and dump parsed datastructure",
@ -45,6 +51,7 @@ var testPrunePolicyCmd = &cobra.Command{
}
func init() {
cobra.OnInitialize(testCmdGlobalInit)
RootCmd.AddCommand(testCmd)
testCmd.AddCommand(testConfigSyntaxCmd)
testCmd.AddCommand(testDatasetMapFilter)
@ -55,15 +62,33 @@ func init() {
testCmd.AddCommand(testPrunePolicyCmd)
}
func testCmdGlobalInit() {
testCmdGlobal.log = log.New(os.Stdout, "", 0)
ctx := context.WithValue(context.Background(), contextKeyLog, testCmdGlobal.log)
var err error
if testCmdGlobal.conf, err = ParseConfig(ctx, rootArgs.configFile); err != nil {
testCmdGlobal.log.Printf("error parsing config file: %s", err)
os.Exit(1)
}
}
func doTestConfig(cmd *cobra.Command, args []string) {
log, conf := testCmdGlobal.log, testCmdGlobal.conf
log.Printf("config ok")
log.Printf("%# v", pretty.Formatter(conf))
return
}
func doTestDatasetMapFilter(cmd *cobra.Command, args []string) {
log, conf := testCmdGlobal.log, testCmdGlobal.conf
if len(args) != 2 {
log.Printf("specify job name as first postitional argument, test input as second")
log.Printf(cmd.UsageString())
@ -120,6 +145,8 @@ func doTestDatasetMapFilter(cmd *cobra.Command, args []string) {
func doTestPrunePolicy(cmd *cobra.Command, args []string) {
log, conf := testCmdGlobal.log, testCmdGlobal.conf
if cmd.Flags().NArg() != 1 {
log.Printf("specify job name as first positional argument")
log.Printf(cmd.UsageString())