Last active
November 29, 2020 08:52
-
-
Save rbarbey/ea676f47653e20d05b24 to your computer and use it in GitHub Desktop.
Bootstrapping Cobra Commands From a Config File
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package cmd | |
import ( | |
"log" | |
"github.com/spf13/cobra" | |
"github.com/spf13/viper" | |
) | |
// Task tries to be similar to os.exec.Cmd | |
type Task struct { | |
Name string | |
Desc string | |
Path string | |
Args []string | |
} | |
type Config map[string]Task | |
var RootCmd = &cobra.Command{ | |
Use: "tool", | |
Short: "Tool which bootstraps commands", | |
} | |
func Execute() { | |
// intentionally left blank | |
} | |
func init() { | |
cobra.OnInitialize(initConfig) | |
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "path to config file") | |
err := RootCmd.Execute() | |
if err != nil { | |
// error handling | |
} | |
} | |
func initConfig() { | |
// omission: init viper, read config | |
// iterate over parsed structures and create cobra.Commands | |
tasks := Config{} | |
err = viper.UnmarshalKey("tasks", &tasks) | |
if err != nil { | |
log.Fatalf("Could not unmarshal config: %+v", err) | |
} | |
log.Printf("Read tasks from config: %+v", tasks) | |
for _, task := range tasks { | |
log.Printf("Task found: %+v", task) | |
var command = &cobra.Command{ | |
Use: task.Name, | |
Short: task.Desc, | |
Run: func(cmd *cobra.Command, args []string) { | |
log.Printf("Executing %v", task.Name) | |
}, | |
} | |
RootCmd.AddCommand(command) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment