Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds ability to use custom add command template #84

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,3 +177,13 @@ Copyright © 2020 Steve Francia <spf@spf13.com>
This file is part of CLI application foo.
*/
```

### Custom "add" Templates

In some cases advanced Cobra users may have extended their implementations of
their command line application past the defaults. In these cases, the default
`cobra-cli add` template may no longer apply to their repository. Support has
been added to create custom template files for new commands on a per-project
basis by adding a `.cobra_template.tpl` file to the root directory of their
command line application. An example template can be found in the
[cmd/add_test.go](https://www.github.com/spf13/cobra-cli/blob/main/cmd/add_test.go) file.
60 changes: 60 additions & 0 deletions cmd/add_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,38 @@ import (
"github.com/spf13/viper"
)

var customFileTemplate = []byte(`/*
{{ .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 = &myStruct.Command{
Use: "{{ .CmdName }}",
Short: "A brief description of your command",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("{{ .CmdName }} called")
},
CustomParam: "This is a custom parameter to extend the default cobra functionality",
}

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

// All commands must indepenently define this flag by default
testCmd.PersistentFlags().String("foo", "", "A help for foo")

// Thank you for contributing a new command.
}
`)

func TestGoldenAddCmd(t *testing.T) {
viper.Set("useViper", true)
viper.Set("license", "apache")
Expand All @@ -29,6 +61,34 @@ func TestGoldenAddCmd(t *testing.T) {
}
}

func TestGoldenCustomAddCmd(t *testing.T) {
viper.Set("useViper", true)
viper.Set("license", "apache")
command := &Command{
CmdName: "test",
CmdParent: parentName,
Project: getProject(),
}
defer os.RemoveAll(command.AbsolutePath)

assertNoErr(t, command.Project.Create())

templateFile := fmt.Sprintf("%s/.cobra_template.tpl", command.AbsolutePath)
err := os.WriteFile(templateFile, customFileTemplate, 0644)
if err != nil {
t.Fatal(err)
}

assertNoErr(t, command.Create())

generatedFile := fmt.Sprintf("%s/cmd/%s.go", command.AbsolutePath, command.CmdName)
goldenFile := fmt.Sprintf("testdata/%s.go.golden", command.CmdName)
err = compareFiles(generatedFile, goldenFile)
if err != nil {
t.Fatal(err)
}
}

func TestValidateCmdName(t *testing.T) {
testCases := []struct {
input string
Expand Down
2 changes: 1 addition & 1 deletion cmd/testdata/main.go.golden
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>
Copyright © 2023 NAME HERE <EMAIL ADDRESS>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down
2 changes: 1 addition & 1 deletion cmd/testdata/root.go.golden
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>
Copyright © 2023 NAME HERE <EMAIL ADDRESS>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down
45 changes: 45 additions & 0 deletions cmd/testdata/test-custom.go.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd

import (
"fmt"

"github.com/spf13/cobra"
)

// testCmd represents the test command
var testCmd = &myStruct.Command{
Use: "test",
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("test called")
},
CustomParam: "This is a custom parameter to extend the default cobra functionality",
}

func init() {
rootCmd.AddCommand(testCmd)

// All commands must indepenently define this flag by default
testCmd.PersistentFlags().String("foo", "", "A help for foo")
}
2 changes: 1 addition & 1 deletion cmd/testdata/test.go.golden
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>
Copyright © 2023 NAME HERE <EMAIL ADDRESS>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down
35 changes: 33 additions & 2 deletions tpl/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@

package tpl

import (
"errors"
"fmt"
"io/fs"
"os"
)

func MainTemplate() []byte {
return []byte(`/*
{{ .Copyright }}
Expand Down Expand Up @@ -118,8 +125,7 @@ func initConfig() {
`)
}

func AddCommandTemplate() []byte {
return []byte(`/*
var defaultCommandTemplate = []byte(`/*
{{ .Project.Copyright }}
{{ if .Legal.Header }}{{ .Legal.Header }}{{ end }}
*/
Expand Down Expand Up @@ -160,4 +166,29 @@ func init() {
// {{ .CmdName }}Cmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
`)

func AddCommandTemplate() []byte {
wd, err := os.Getwd()
if err != nil {
fmt.Println("Could not get current working directory.", "Error:", err)
return defaultCommandTemplate
}

filename := ".cobra_template.tpl"

tpl, err := os.ReadFile(fmt.Sprintf("%s/%s", wd, filename))
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return defaultCommandTemplate
}
fmt.Println("Could not read .cobra_template.tpl", "Error:", err)
return defaultCommandTemplate
}

if len(tpl) < 1 {
fmt.Println("Template file is empty. Using default template.")
return defaultCommandTemplate
}

return tpl
}