Skip to content

Instantly share code, notes, and snippets.

@rbarbey
Last active November 29, 2020 08:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbarbey/ea676f47653e20d05b24 to your computer and use it in GitHub Desktop.
Save rbarbey/ea676f47653e20d05b24 to your computer and use it in GitHub Desktop.
Bootstrapping Cobra Commands From a Config File
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