Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions cmd/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@ import (
)

var (
packageName string
parentName string
packageName string
parentName string
dirName string
addCopyrightLine bool

addCmd = &cobra.Command{
Use: "add [command name]",
Expand Down Expand Up @@ -54,6 +56,9 @@ Example: cobra-cli add server -> resulting in a new cmd/server.go`,
}

wd, err := os.Getwd()
if dirName != "" {
wd += "/" + dirName
}
cobra.CheckErr(err)

commandName := validateCmdName(args[0])
Expand All @@ -63,9 +68,12 @@ Example: cobra-cli add server -> resulting in a new cmd/server.go`,
Project: &Project{
AbsolutePath: wd,
Legal: getLicense(),
Copyright: copyrightLine(),
LocalVars: localVars,
},
}
if addCopyrightLine {
command.Copyright = copyrightLine()
}

cobra.CheckErr(command.Create())

Expand All @@ -77,6 +85,8 @@ Example: cobra-cli add server -> resulting in a new cmd/server.go`,
func init() {
addCmd.Flags().StringVarP(&packageName, "package", "t", "", "target package name (e.g. github.com/spf13/hugo)")
addCmd.Flags().StringVarP(&parentName, "parent", "p", "rootCmd", "variable name of parent command for this command")
addCmd.Flags().StringVarP(&dirName, "dir", "d", "", "relative path to the command's main package")
addCmd.Flags().BoolVarP(&addCopyrightLine, "copyright", "c", true, "add copyright line to generated command file")
cobra.CheckErr(addCmd.Flags().MarkDeprecated("package", "this operation has been removed."))
}

Expand Down
6 changes: 4 additions & 2 deletions cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,21 +69,23 @@ func initializeProject(args []string) (string, error) {
return "", err
}

modName := getModImportPath()

if len(args) > 0 {
if args[0] != "." {
wd = fmt.Sprintf("%s/%s", wd, args[0])
modName = fmt.Sprintf("%s/%s", modName, args[0])
}
}

modName := getModImportPath()

project := &Project{
AbsolutePath: wd,
PkgName: modName,
Legal: getLicense(),
Copyright: copyrightLine(),
Viper: viper.GetBool("useViper"),
AppName: path.Base(modName),
LocalVars: localVars,
}

if err := project.Create(); err != nil {
Expand Down
37 changes: 32 additions & 5 deletions cmd/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cmd
import (
"fmt"
"os"
"strings"
"text/template"

"github.com/spf13/cobra"
Expand All @@ -18,6 +19,7 @@ type Project struct {
Legal License
Viper bool
AppName string
LocalVars bool
}

type Command struct {
Expand All @@ -30,7 +32,7 @@ func (p *Project) Create() error {
// check if AbsolutePath exists
if _, err := os.Stat(p.AbsolutePath); os.IsNotExist(err) {
// create directory
if err := os.Mkdir(p.AbsolutePath, 0754); err != nil {
if err := os.MkdirAll(p.AbsolutePath, 0754); err != nil {
return err
}
}
Expand All @@ -50,15 +52,19 @@ func (p *Project) Create() error {

// create cmd/root.go
if _, err = os.Stat(fmt.Sprintf("%s/cmd", p.AbsolutePath)); os.IsNotExist(err) {
cobra.CheckErr(os.Mkdir(fmt.Sprintf("%s/cmd", p.AbsolutePath), 0751))
cobra.CheckErr(os.MkdirAll(fmt.Sprintf("%s/cmd", p.AbsolutePath), 0751))
}
rootFile, err := os.Create(fmt.Sprintf("%s/cmd/root.go", p.AbsolutePath))
if err != nil {
return err
}
defer rootFile.Close()

rootTemplate := template.Must(template.New("root").Parse(string(tpl.RootTemplate())))
tmpl := tpl.RootTemplateGlobal()
if p.LocalVars {
tmpl = tpl.RootTemplateLocal()
}
rootTemplate := template.Must(template.New("root").Parse(string(tmpl)))
err = rootTemplate.Execute(rootFile, p)
if err != nil {
return err
Expand All @@ -83,13 +89,34 @@ func (p *Project) createLicenseFile() error {
}

func (c *Command) Create() error {
cmdFile, err := os.Create(fmt.Sprintf("%s/cmd/%s.go", c.AbsolutePath, c.CmdName))
filename := c.CmdName
if c.CmdParent != "rootCmd" {
filename = fmt.Sprintf("%s_%s", strings.TrimSuffix(c.CmdParent, "Cmd"), c.CmdName)
}
cmdFile, err := os.Create(fmt.Sprintf("%s/cmd/%s.go", c.AbsolutePath, filename))
if err != nil {
return err
}
defer cmdFile.Close()

commandTemplate := template.Must(template.New("sub").Parse(string(tpl.AddCommandTemplate())))
funcMap := template.FuncMap{
// The name "title" is what the function will be called in the template text.
"typeName": func(cmd string, parent string) string {
name := strings.Title(cmd)
if parent != "rootCmd" {
name = strings.Title(strings.TrimSuffix(parent, "Cmd")) + name
}
name += "Cmd"
return name
},
"title": strings.Title,
}

tmpl := tpl.AddCommandTemplateGlobal()
if c.LocalVars {
tmpl = tpl.AddCommandTemplateLocal()
}
commandTemplate := template.Must(template.New("sub").Funcs(funcMap).Parse(string(tmpl)))
err = commandTemplate.Execute(cmdFile, c)
if err != nil {
return err
Expand Down
2 changes: 2 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ var (
// Used for flags.
cfgFile string
userLicense string
localVars bool

rootCmd = &cobra.Command{
Use: "cobra-cli",
Expand All @@ -48,6 +49,7 @@ func init() {
rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
rootCmd.PersistentFlags().Bool("viper", false, "use Viper for configuration")
rootCmd.PersistentFlags().BoolVarP(&localVars, "local", "L", false, "project uses local-scoped variables")
cobra.CheckErr(viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")))
cobra.CheckErr(viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")))
viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/spf13/cobra-cli

go 1.15
go 1.16

require (
github.com/spf13/cobra v1.6.1
Expand Down
40 changes: 40 additions & 0 deletions tpl/add-command.global.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
{{ .Project.Copyright }}
{{ if .Legal.Header }}{{ .Legal.Header }}{{ end }}
*/
package cmd

import (
"fmt"

"github.com/spf13/cobra"
)

// {{ .CmdName }}Cmd represents the {{ .CmdName }} command
var {{ .CmdName }}Cmd = &cobra.Command{
Use: "{{ .CmdName }}",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("{{ .CmdName }} called")
},
}

func init() {
{{ .CmdParent }}.AddCommand({{ .CmdName }}Cmd)

// Here you will define your flags and configuration settings.

// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// {{ .CmdName }}Cmd.PersistentFlags().String("foo", "", "A help for foo")

// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// {{ .CmdName }}Cmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
55 changes: 55 additions & 0 deletions tpl/add-command.local.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
{{ if or ( ne .Project.Copyright "" ) .Legal.Header }}
/*
{{ .Project.Copyright }}
{{ if .Legal.Header }}{{ .Legal.Header }}{{ end }}
*/
{{ end }}package cmd

import (
"fmt"

"github.com/spf13/cobra"
)

// {{ typeName .CmdName .CmdParent }} represents the {{ .CmdName }} command
type {{ typeName .CmdName .CmdParent }} struct {
cmd *cobra.Command
}

func (c *{{ typeName .CmdName .CmdParent }}) RunE(_ *cobra.Command, args []string) error {
//Command execution goes here

fmt.Printf("running %s", c.cmd.Use)

return nil
}

func Add{{ typeName .CmdName .CmdParent }}({{.CmdParent}} *cobra.Command) {
{{.CmdName}} := {{ typeName .CmdName .CmdParent }}{
cmd: &cobra.Command{
Use: "{{ .CmdName }}",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
},
}
// Here you will define your flags and configuration settings.

// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// {{.CmdName}}.cmd.PersistentFlags().String("foo", "", "A help for foo")

// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// {{.CmdName}}.cmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
{{.CmdParent}}.AddCommand({{.CmdName}}.cmd)
{{.CmdName}}.cmd.RunE = {{.CmdName}}.RunE

// Add child commands here
// Add{{title .CmdName}}ChildCmd({{.CmdName}}.cmd)
}

Loading