Skip to content

Commit

Permalink
cmd: Validate cmd names
Browse files Browse the repository at this point in the history
  • Loading branch information
n10v committed May 1, 2017
1 parent e427add commit 4a72870
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 3 deletions.
50 changes: 47 additions & 3 deletions cobra/cmd/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@ import (
"fmt"
"os"
"path/filepath"
"unicode"

"github.com/spf13/cobra"
"github.com/spf13/viper"
)

func init() {
addCmd.Flags().StringVarP(&parentName, "parent", "p", "RootCmd", "name of parent command for this command")
RootCmd.AddCommand(addCmd)
}

Expand Down Expand Up @@ -50,12 +52,54 @@ Example: cobra add server -> resulting in a new cmd/server.go`,
er(err)
}
project := NewProjectFromPath(wd)
createCmdFile(project, args[0])
cmdName := validateCmdName(args[0])
createCmdFile(project, cmdName)
},
}

func init() {
addCmd.Flags().StringVarP(&parentName, "parent", "p", "RootCmd", "name of parent command for this command")
// validateCmdName returns source without any dashes and underscore.
// If there will be dash or underscore, next letter will be uppered.
func validateCmdName(source string) string {
i := 0
l := len(source)
// The output is initialized on demand, then first dash or underscore
// occurs.
var output string

for i < l {
if source[i] == '-' || source[i] == '_' {
if output == "" {
output = source[:i]
}

// If next character is dash or underscore,
// just skip the current character.
if source[i+1] == '-' || source[i+1] == '_' {
i++
continue
}

// If the current character is dash or underscore,
// upper next letter and add to output.
output += string(unicode.ToUpper(rune(source[i+1])))
// We know, what source[i] is dash or underscore and source[i+1] is
// uppered character, so make i = i+2.
i += 2
continue
}

// If the current character isn't dash or underscore,
// just add it.
if output != "" {
output += string(source[i])
}
i++
}

if output == "" {
return source // source is initially valid name.
}
return output
}

func createCmdFile(project *Project, cmdName string) {
Expand Down
25 changes: 25 additions & 0 deletions cobra/cmd/add_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package cmd

import "testing"

func TestValidateCmdName(t *testing.T) {
testCases := []struct {
input string
expected string
}{
{"cmdName", "cmdName"},
{"cmd_name", "cmdName"},
{"cmd-name", "cmdName"},
{"cmd______Name", "cmdName"},
{"cmd------Name", "cmdName"},
{"cmd______name", "cmdName"},
{"cmd------name", "cmdName"},
}

for _, testCase := range testCases {
got := validateCmdName(testCase.input)
if testCase.expected != got {
t.Errorf("Expected %q, got %q", testCase.expected, got)
}
}
}

0 comments on commit 4a72870

Please sign in to comment.