From 99ff9334bda26384b5ef4a4aaa4d444d29bdde73 Mon Sep 17 00:00:00 2001 From: Albert Nigmatzianov Date: Sun, 28 May 2017 12:42:06 +0200 Subject: [PATCH] cmd: Add possibility to specify the target package Fix #455 --- cobra/cmd/add.go | 17 ++++++++++++----- cobra/cmd/root.go | 5 ++--- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/cobra/cmd/add.go b/cobra/cmd/add.go index 8897f8f..45f00bb 100644 --- a/cobra/cmd/add.go +++ b/cobra/cmd/add.go @@ -23,10 +23,11 @@ import ( ) func init() { + addCmd.Flags().StringVarP(&packageName, "package", "t", "", "target package name (e.g. github.com/spf13/hugo)") addCmd.Flags().StringVarP(&parentName, "parent", "p", "RootCmd", "name of parent command for this command") } -var parentName string +var packageName, parentName string var addCmd = &cobra.Command{ Use: "add [command name]", @@ -45,11 +46,17 @@ Example: cobra add server -> resulting in a new cmd/server.go`, if len(args) < 1 { er("add needs a name for the command") } - wd, err := os.Getwd() - if err != nil { - er(err) + + var project *Project + if packageName != "" { + project = NewProject(packageName) + } else { + wd, err := os.Getwd() + if err != nil { + er(err) + } + project = NewProjectFromPath(wd) } - project := NewProjectFromPath(wd) cmdName := validateCmdName(args[0]) cmdPath := filepath.Join(project.CmdPath(), cmdName+".go") diff --git a/cobra/cmd/root.go b/cobra/cmd/root.go index 716a59a..1c5e690 100644 --- a/cobra/cmd/root.go +++ b/cobra/cmd/root.go @@ -44,16 +44,15 @@ func init() { rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution") - rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project (can provide `license` in config)") + rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project") rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration") viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) viper.SetDefault("author", "NAME HERE ") viper.SetDefault("license", "apache") - rootCmd.AddCommand(initCmd) rootCmd.AddCommand(addCmd) - + rootCmd.AddCommand(initCmd) } func initViper() {