Repository: spf13/cobra
Pull request #425 (2017-04-27 08:57:24)

Make initHelpFlag public
Useful for solving #424

/cc @spf13 @eparis @bep 


Patch:
diff --git a/.travis.yml b/.travis.yml
index 42d1f57..cb2bf0d 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -2,12 +2,8 @@ language: go
 
 matrix:
   include:
-    - go: 1.4.3
-      env: NOVET=true # No bundled vet.
-    - go: 1.5.4
-    - go: 1.6.4
     - go: 1.7.5
-    - go: 1.8
+    - go: 1.8.1
     - go: tip
   allow_failures:
     - go: tip
diff --git a/README.md b/README.md
index 202c48e..77b6e28 100644
--- a/README.md
+++ b/README.md
@@ -48,7 +48,7 @@ Cobra provides:
 * Automatically generated bash autocomplete for your application
 * Automatically generated man pages for your application
 * Command aliases so you can change things without breaking them
-* The flexibilty to define your own help, usage, etc.
+* The flexibility to define your own help, usage, etc.
 * Optional tight integration with [viper](http://github.com/spf13/viper) for 12-factor apps
 
 Cobra has an exceptionally clean interface and simple design without needless
@@ -79,11 +79,11 @@ A few good real world examples may better illustrate this point.
 
 In the following example, 'server' is a command, and 'port' is a flag:
 
-    > hugo server --port=1313
+    hugo server --port=1313
 
 In this command we are telling Git to clone the url bare.
 
-    > git clone URL --bare
+    git clone URL --bare
 
 ## Commands
 
@@ -130,7 +130,7 @@ Using Cobra is easy. First, use `go get` to install the latest version
 of the library. This command will install the `cobra` generator executible
 along with the library:
 
-    > go get -v github.com/spf13/cobra/cobra
+    go get -v github.com/spf13/cobra/cobra
 
 Next, include Cobra in your application:
 
@@ -180,7 +180,7 @@ commands you want. It's the easiest way to incorporate Cobra into your applicati
 
 In order to use the cobra command, compile it using the following command:
 
-    > go get github.com/spf13/cobra/cobra
+    go get github.com/spf13/cobra/cobra
 
 This will create the cobra executable under your `$GOPATH/bin` directory.
 
@@ -215,6 +215,10 @@ cobra add config
 cobra add create -p 'configCmd'
 ```
 
+*Note: Use camelCase (not snake_case/snake-case) for command names.
+Otherwise, you will become unexpected errors.
+For example, `cobra add add-user` is incorrect, but `cobra add addUser` is valid.*
+
 Once you have run these three commands you would have an app structure that would look like:
 
 ```
diff --git a/cobra/cmd/add.go b/cobra/cmd/add.go
index b89d4c4..20c6538 100644
--- a/cobra/cmd/add.go
+++ b/cobra/cmd/add.go
@@ -15,20 +15,20 @@ package cmd
 
 import (
 	"fmt"
+	"os"
 	"path/filepath"
-	"strings"
+	"unicode"
 
 	"github.com/spf13/cobra"
 	"github.com/spf13/viper"
 )
 
 func init() {
-	RootCmd.AddCommand(addCmd)
+	addCmd.Flags().StringVarP(&parentName, "parent", "p", "RootCmd", "name of parent command for this command")
 }
 
-var pName string
+var parentName string
 
-// initialize Command
 var addCmd = &cobra.Command{
 	Use:     "add [command name]",
 	Aliases: []string{"command"},
@@ -40,35 +40,82 @@ and register it to its parent (default RootCmd).
 If you want your command to be public, pass in the command name
 with an initial uppercase letter.
 
-Example: cobra add server  -> resulting in a new cmd/server.go
-  `,
+Example: cobra add server -> resulting in a new cmd/server.go`,
 
 	Run: func(cmd *cobra.Command, args []string) {
-		if len(args) != 1 {
+		if len(args) < 1 {
 			er("add needs a name for the command")
 		}
-		guessProjectPath()
-		createCmdFile(args[0])
+		wd, err := os.Getwd()
+		if err != nil {
+			er(err)
+		}
+		project := NewProjectFromPath(wd)
+
+		cmdName := validateCmdName(args[0])
+		cmdPath := filepath.Join(project.CmdPath(), cmdName+".go")
+		createCmdFile(project.License(), cmdPath, cmdName)
+
+		fmt.Fprintln(cmd.OutOrStdout(), cmdName, "created at", cmdPath)
 	},
 }
 
-func init() {
-	addCmd.Flags().StringVarP(&pName, "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.
+// It supports only ASCII (1-byte character) strings.
+// https://github.com/spf13/cobra/issues/269
+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 it's last rune and it's dash or underscore,
+			// don't add it output and break the loop.
+			if i == l-1 {
+				break
+			}
+
+			// 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
+		}
 
-func parentName() string {
-	if !strings.HasSuffix(strings.ToLower(pName), "cmd") {
-		return pName + "Cmd"
+		// If the current character isn't dash or underscore,
+		// just add it.
+		if output != "" {
+			output += string(source[i])
+		}
+		i++
 	}
 
-	return pName
+	if output == "" {
+		return source // source is initially valid name.
+	}
+	return output
 }
 
-func createCmdFile(cmdName string) {
-	lic := getLicense()
-
-	template := `{{ comment .copyright }}
-{{ comment .license }}
+func createCmdFile(license License, path, cmdName string) {
+	template := `{{comment .copyright}}
+{{comment .license}}
 
 package cmd
 
@@ -79,8 +126,8 @@ import (
 )
 
 // {{.cmdName}}Cmd represents the {{.cmdName}} command
-var {{ .cmdName }}Cmd = &cobra.Command{
-	Use:   "{{ .cmdName }}",
+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:
@@ -89,13 +136,12 @@ 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) {
-		// TODO: Work your own magic here
-		fmt.Println("{{ .cmdName }} called")
+		fmt.Println("{{.cmdName}} called")
 	},
 }
 
 func init() {
-	{{ .parentName }}.AddCommand({{ .cmdName }}Cmd)
+	{{.parentName}}.AddCommand({{.cmdName}}Cmd)
 
 	// Here you will define your flags and configuration settings.
 
@@ -106,23 +152,22 @@ func init() {
 	// 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")
-
 }
 `
 
-	var data map[string]interface{}
-	data = make(map[string]interface{})
-
+	data := make(map[string]interface{})
 	data["copyright"] = copyrightLine()
-	data["license"] = lic.Header
-	data["appName"] = projectName()
+	data["license"] = license.Header
 	data["viper"] = viper.GetBool("useViper")
-	data["parentName"] = parentName()
+	data["parentName"] = parentName
 	data["cmdName"] = cmdName
 
-	err := writeTemplateToFile(filepath.Join(ProjectPath(), guessCmdDir()), cmdName+".go", template, data)
+	cmdScript, err := executeTemplate(template, data)
+	if err != nil {
+		er(err)
+	}
+	err = writeStringToFile(path, cmdScript)
 	if err != nil {
 		er(err)
 	}
-	fmt.Println(cmdName, "created at", filepath.Join(ProjectPath(), guessCmdDir(), cmdName+".go"))
 }
diff --git a/cobra/cmd/helpers.go b/cobra/cmd/helpers.go
index 6989bd7..fc9dd85 100644
--- a/cobra/cmd/helpers.go
+++ b/cobra/cmd/helpers.go
@@ -23,289 +23,123 @@ import (
 	"text/template"
 )
 
-// var BaseDir = ""
-// var AppName = ""
-// var CommandDir = ""
+var projectPath string
 
-var funcMap template.FuncMap
-var projectPath = ""
-var inputPath = ""
-var projectBase = ""
-
-// for testing only
-var testWd = ""
-
-var cmdDirs = []string{"cmd", "cmds", "command", "commands"}
+var cmdDirs = [...]string{"cmd", "cmds", "command", "commands"}
+var srcPaths []string
 
 func init() {
-	funcMap = template.FuncMap{
-		"comment": commentifyString,
+	// Initialize goPaths and srcPaths
+	envGoPath := os.Getenv("GOPATH")
+	if envGoPath == "" {
+		er("$GOPATH is not set")
 	}
-}
-
-func er(msg interface{}) {
-	fmt.Println("Error:", msg)
-	os.Exit(-1)
-}
-
-// Check if a file or directory exists.
-func exists(path string) (bool, error) {
-	_, err := os.Stat(path)
-	if err == nil {
-		return true, nil
-	}
-	if os.IsNotExist(err) {
-		return false, nil
-	}
-	return false, err
-}
 
-func ProjectPath() string {
-	if projectPath == "" {
-		guessProjectPath()
+	goPaths := filepath.SplitList(envGoPath)
+	srcPaths = make([]string, 0, len(goPaths))
+	for _, goPath := range goPaths {
+		srcPaths = append(srcPaths, filepath.Join(goPath, "src"))
 	}
-
-	return projectPath
-}
-
-// wrapper of the os package so we can test better
-func getWd() (string, error) {
-	if testWd == "" {
-		return os.Getwd()
-	}
-	return testWd, nil
-}
-
-func guessCmdDir() string {
-	guessProjectPath()
-	if b, _ := isEmpty(projectPath); b {
-		return "cmd"
-	}
-
-	files, _ := filepath.Glob(projectPath + string(os.PathSeparator) + "c*")
-	for _, f := range files {
-		for _, c := range cmdDirs {
-			if f == c {
-				return c
-			}
-		}
-	}
-
-	return "cmd"
 }
 
-func guessImportPath() string {
-	guessProjectPath()
-
-	if !strings.HasPrefix(projectPath, getSrcPath()) {
-		er("Cobra only supports project within $GOPATH")
-	}
-
-	return filepath.ToSlash(filepath.Clean(strings.TrimPrefix(projectPath, getSrcPath())))
-}
-
-func getSrcPath() string {
-	return filepath.Join(os.Getenv("GOPATH"), "src") + string(os.PathSeparator)
-}
-
-func projectName() string {
-	return filepath.Base(ProjectPath())
-}
-
-func guessProjectPath() {
-	// if no path is provided... assume CWD.
-	if inputPath == "" {
-		x, err := getWd()
-		if err != nil {
-			er(err)
-		}
-
-		// inspect CWD
-		base := filepath.Base(x)
-
-		// if we are in the cmd directory.. back up
-		for _, c := range cmdDirs {
-			if base == c {
-				projectPath = filepath.Dir(x)
-				return
-			}
-		}
-
-		if projectPath == "" {
-			projectPath = filepath.Clean(x)
-			return
-		}
-	}
-
-	srcPath := getSrcPath()
-	// if provided, inspect for logical locations
-	if strings.ContainsRune(inputPath, os.PathSeparator) {
-		if filepath.IsAbs(inputPath) || filepath.HasPrefix(inputPath, string(os.PathSeparator)) {
-			// if Absolute, use it
-			projectPath = filepath.Clean(inputPath)
-			return
-		}
-		// If not absolute but contains slashes,
-		// assuming it means create it from $GOPATH
-		count := strings.Count(inputPath, string(os.PathSeparator))
-
-		switch count {
-		// If only one directory deep, assume "github.com"
-		case 1:
-			projectPath = filepath.Join(srcPath, "github.com", inputPath)
-			return
-		case 2:
-			projectPath = filepath.Join(srcPath, inputPath)
-			return
-		default:
-			er("Unknown directory")
-		}
-	} else {
-		// hardest case.. just a word.
-		if projectBase == "" {
-			x, err := getWd()
-			if err == nil {
-				projectPath = filepath.Join(x, inputPath)
-				return
-			}
-			er(err)
-		} else {
-			projectPath = filepath.Join(srcPath, projectBase, inputPath)
-			return
-		}
-	}
+func er(msg interface{}) {
+	fmt.Println("Error:", msg)
+	os.Exit(1)
 }
 
 // isEmpty checks if a given path is empty.
-func isEmpty(path string) (bool, error) {
-	if b, _ := exists(path); !b {
-		return false, fmt.Errorf("%q path does not exist", path)
-	}
+func isEmpty(path string) bool {
 	fi, err := os.Stat(path)
 	if err != nil {
-		return false, err
+		er(err)
 	}
 	if fi.IsDir() {
 		f, err := os.Open(path)
-		// FIX: Resource leak - f.close() should be called here by defer or is missed
-		// if the err != nil branch is taken.
-		defer f.Close()
 		if err != nil {
-			return false, err
+			er(err)
 		}
-		list, _ := f.Readdir(-1)
-		// f.Close() - see bug fix above
-		return len(list) == 0, nil
-	}
-	return fi.Size() == 0, nil
-}
-
-// isDir checks if a given path is a directory.
-func isDir(path string) (bool, error) {
-	fi, err := os.Stat(path)
-	if err != nil {
-		return false, err
+		defer f.Close()
+		dirs, err := f.Readdirnames(1)
+		if err != nil && err != io.EOF {
+			er(err)
+		}
+		return len(dirs) == 0
 	}
-	return fi.IsDir(), nil
+	return fi.Size() == 0
 }
 
-// dirExists checks if a path exists and is a directory.
-func dirExists(path string) (bool, error) {
-	fi, err := os.Stat(path)
-	if err == nil && fi.IsDir() {
-		return true, nil
-	}
-	if os.IsNotExist(err) {
-		return false, nil
+// exists checks if a file or directory exists.
+func exists(path string) bool {
+	if path == "" {
+		return false
 	}
-	return false, err
-}
-
-func writeTemplateToFile(path string, file string, template string, data interface{}) error {
-	filename := filepath.Join(path, file)
-
-	r, err := templateToReader(template, data)
-
-	if err != nil {
-		return err
+	_, err := os.Stat(path)
+	if err == nil {
+		return true
 	}
-
-	err = safeWriteToDisk(filename, r)
-
-	if err != nil {
-		return err
+	if !os.IsNotExist(err) {
+		er(err)
 	}
-	return nil
+	return false
 }
 
-func writeStringToFile(path, file, text string) error {
-	filename := filepath.Join(path, file)
-
-	r := strings.NewReader(text)
-	err := safeWriteToDisk(filename, r)
+var tmpl = template.New("").Funcs(template.FuncMap{"comment": commentifyString})
 
+func executeTemplate(tmplStr string, data interface{}) (string, error) {
+	var err error
+	tmpl, err = tmpl.Parse(tmplStr)
 	if err != nil {
-		return err
+		return "", err
 	}
-	return nil
-}
 
-func templateToReader(tpl string, data interface{}) (io.Reader, error) {
-	tmpl := template.New("")
-	tmpl.Funcs(funcMap)
-	tmpl, err := tmpl.Parse(tpl)
-
-	if err != nil {
-		return nil, err
-	}
 	buf := new(bytes.Buffer)
 	err = tmpl.Execute(buf, data)
-
-	return buf, err
+	return buf.String(), err
 }
 
-// Same as WriteToDisk but checks to see if file/directory already exists.
-func safeWriteToDisk(inpath string, r io.Reader) (err error) {
-	dir, _ := filepath.Split(inpath)
-	ospath := filepath.FromSlash(dir)
+func writeStringToFile(path string, s string) error {
+	return writeToFile(path, strings.NewReader(s))
+}
 
-	if ospath != "" {
-		err = os.MkdirAll(ospath, 0777) // rwx, rw, r
-		if err != nil {
-			return
-		}
+// writeToFile writes r to file with path only
+// if file/directory on given path doesn't exist.
+// If file/directory exists on given path, then
+// it terminates app and prints an appropriate error.
+func writeToFile(path string, r io.Reader) error {
+	if exists(path) {
+		return fmt.Errorf("%v already exists", path)
 	}
 
-	ex, err := exists(inpath)
-	if err != nil {
-		return
-	}
-	if ex {
-		return fmt.Errorf("%v already exists", inpath)
+	dir := filepath.Dir(path)
+	if dir != "" {
+		if err := os.MkdirAll(dir, 0777); err != nil {
+			return err
+		}
 	}
 
-	file, err := os.Create(inpath)
+	file, err := os.Create(path)
 	if err != nil {
-		return
+		return err
 	}
 	defer file.Close()
 
 	_, err = io.Copy(file, r)
-	return
+	return err
 }
 
+// commentfyString comments every line of in.
 func commentifyString(in string) string {
 	var newlines []string
 	lines := strings.Split(in, "\n")
-	for _, x := range lines {
-		if !strings.HasPrefix(x, "//") {
-			if x != "" {
-				newlines = append(newlines, "// "+x)
-			} else {
+	for _, line := range lines {
+		if strings.HasPrefix(line, "//") {
+			newlines = append(newlines, line)
+		} else {
+			if line == "" {
 				newlines = append(newlines, "//")
+			} else {
+				newlines = append(newlines, "// "+line)
 			}
-		} else {
-			newlines = append(newlines, x)
 		}
 	}
 	return strings.Join(newlines, "\n")
diff --git a/cobra/cmd/init.go b/cobra/cmd/init.go
index b77c986..788bdb5 100644
--- a/cobra/cmd/init.go
+++ b/cobra/cmd/init.go
@@ -14,20 +14,15 @@
 package cmd
 
 import (
-	"bytes"
 	"fmt"
 	"os"
-	"strings"
+	"path"
+	"path/filepath"
 
 	"github.com/spf13/cobra"
 	"github.com/spf13/viper"
 )
 
-func init() {
-	RootCmd.AddCommand(initCmd)
-}
-
-// initialize Command
 var initCmd = &cobra.Command{
 	Use:     "init [name]",
 	Aliases: []string{"initialize", "initialise", "create"},
@@ -45,79 +40,75 @@ and the appropriate structure for a Cobra-based CLI application.
 Init will not use an existing directory with contents.`,
 
 	Run: func(cmd *cobra.Command, args []string) {
-		switch len(args) {
-		case 0:
-			inputPath = ""
-
-		case 1:
-			inputPath = args[0]
+		wd, err := os.Getwd()
+		if err != nil {
+			er(err)
+		}
 
-		default:
-			er("init doesn't support more than 1 parameter")
+		var project *Project
+		if len(args) == 0 {
+			project = NewProjectFromPath(wd)
+		} else if len(args) == 1 {
+			arg := args[0]
+			if arg[0] == '.' {
+				arg = filepath.Join(wd, arg)
+			}
+			if filepath.IsAbs(arg) {
+				project = NewProjectFromPath(arg)
+			} else {
+				project = NewProject(arg)
+			}
+		} else {
+			er("please enter the name")
 		}
-		guessProjectPath()
-		initializePath(projectPath)
+
+		initializeProject(project)
+
+		fmt.Fprintln(cmd.OutOrStdout(), `Your Cobra application is ready at
+`+project.AbsPath()+`.
+
+Give it a try by going there and running `+"`go run main.go`."+`
+Add commands to it by running `+"`cobra add [cmdname]`.")
 	},
 }
 
-func initializePath(path string) {
-	b, err := exists(path)
-	if err != nil {
-		er(err)
-	}
-
-	if !b { // If path doesn't yet exist, create it
-		err := os.MkdirAll(path, os.ModePerm)
+func initializeProject(project *Project) {
+	if !exists(project.AbsPath()) { // If path doesn't yet exist, create it
+		err := os.MkdirAll(project.AbsPath(), os.ModePerm)
 		if err != nil {
 			er(err)
 		}
-	} else { // If path exists and is not empty don't use it
-		empty, err := exists(path)
-		if err != nil {
-			er(err)
-		}
-		if !empty {
-			er("Cobra will not create a new project in a non empty directory")
-		}
+	} else if !isEmpty(project.AbsPath()) { // If path exists and is not empty don't use it
+		er("Cobra will not create a new project in a non empty directory: " + project.AbsPath())
 	}
-	// We have a directory and it's empty.. Time to initialize it.
 
-	createLicenseFile()
-	createMainFile()
-	createRootCmdFile()
+	// We have a directory and it's empty. Time to initialize it.
+	createLicenseFile(project.License(), project.AbsPath())
+	createMainFile(project)
+	createRootCmdFile(project)
 }
 
-func createLicenseFile() {
-	lic := getLicense()
-
-	// Don't bother writing a LICENSE file if there is no text.
-	if lic.Text != "" {
-		data := make(map[string]interface{})
-
-		// Try to remove the email address, if any
-		data["copyright"] = strings.Split(copyrightLine(), " <")[0]
-
-		data["appName"] = projectName()
+func createLicenseFile(license License, path string) {
+	data := make(map[string]interface{})
+	data["copyright"] = copyrightLine()
 
-		// Generate license template from text and data.
-		r, _ := templateToReader(lic.Text, data)
-		buf := new(bytes.Buffer)
-		buf.ReadFrom(r)
+	// Generate license template from text and data.
+	text, err := executeTemplate(license.Text, data)
+	if err != nil {
+		er(err)
+	}
 
-		err := writeTemplateToFile(ProjectPath(), "LICENSE", buf.String(), data)
-		_ = err
-		// if err != nil {
-		// 	er(err)
-		// }
+	// Write license text to LICENSE file.
+	err = writeStringToFile(filepath.Join(path, "LICENSE"), text)
+	if err != nil {
+		er(err)
 	}
 }
 
-func createMainFile() {
-	lic := getLicense()
+func createMainFile(project *Project) {
+	mainTemplate := `{{ comment .copyright }}
+{{if .license}}{{ comment .license }}{{end}}
 
-	template := `{{ comment .copyright }}
-{{if .license}}{{ comment .license }}
-{{end}}
 package main
 
 import "{{ .importpath }}"
@@ -127,46 +118,41 @@ func main() {
 }
 `
 	data := make(map[string]interface{})
-
 	data["copyright"] = copyrightLine()
-	data["appName"] = projectName()
-
-	// Generate license template from header and data.
-	r, _ := templateToReader(lic.Header, data)
-	buf := new(bytes.Buffer)
-	buf.ReadFrom(r)
-	data["license"] = buf.String()
+	data["license"] = project.License().Header
+	data["importpath"] = path.Join(project.Name(), filepath.Base(project.CmdPath()))
 
-	data["importpath"] = guessImportPath() + "/" + guessCmdDir()
+	mainScript, err := executeTemplate(mainTemplate, data)
+	if err != nil {
+		er(err)
+	}
 
-	err := writeTemplateToFile(ProjectPath(), "main.go", template, data)
-	_ = err
-	// if err != nil {
-	// 	er(err)
-	// }
+	err = writeStringToFile(filepath.Join(project.AbsPath(), "main.go"), mainScript)
+	if err != nil {
+		er(err)
+	}
 }
 
-func createRootCmdFile() {
-	lic := getLicense()
+func createRootCmdFile(project *Project) {
+	template := `{{comment .copyright}}
+{{if .license}}{{comment .license}}{{end}}
 
-	template := `{{ comment .copyright }}
-{{if .license}}{{ comment .license }}
-{{end}}
 package cmd
 
 import (
 	"fmt"
 	"os"
 
+	homedir "github.com/mitchellh/go-homedir"
 	"github.com/spf13/cobra"
-{{ if .viper }}	"github.com/spf13/viper"
-{{ end }})
-{{if .viper}}
-var cfgFile string
-{{ end }}
+{{if .viper}}	"github.com/spf13/viper"{{end}}
+)
+
+{{if .viper}}var cfgFile string{{end}}
+
 // RootCmd represents the base command when called without any subcommands
 var RootCmd = &cobra.Command{
-	Use:   "{{ .appName }}",
+	Use:   "{{.appName}}",
 	Short: "A brief description of your application",
 	Long: ` + "`" + `A longer description that spans multiple lines and likely contains
 examples and usage of using your application. For example:
@@ -174,9 +160,9 @@ examples and usage of using your application. 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.` + "`" + `,
-// Uncomment the following line if your bare application
-// has an action associated with it:
-//	Run: func(cmd *cobra.Command, args []string) { },
+	// Uncomment the following line if your bare application
+	// has an action associated with it:
+	//	Run: func(cmd *cobra.Command, args []string) { },
 }
 
 // Execute adds all child commands to the root command sets flags appropriately.
@@ -184,62 +170,65 @@ to quickly create a Cobra application.` + "`" + `,
 func Execute() {
 	if err := RootCmd.Execute(); err != nil {
 		fmt.Println(err)
-		os.Exit(-1)
+		os.Exit(1)
 	}
 }
 
 func init() {
-{{ if .viper }}	cobra.OnInitialize(initConfig)
-
-{{ end }}	// Here you will define your flags and configuration settings.
-	// Cobra supports Persistent Flags, which, if defined here,
-	// will be global for your application.
-{{ if .viper }}
-	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)")
-{{ else }}
-	// RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)")
-{{ end }}	// Cobra also supports local flags, which will only run
+{{if .viper}}	cobra.OnInitialize(initConfig){{end}}
+
+	// Here you will define your flags and configuration settings.
+	// Cobra supports persistent flags, which, if defined here,
+	// will be global for your application.{{ if .viper }}
+	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)"){{ else }}
+	// RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)"){{ end }}
+
+	// Cobra also supports local flags, which will only run
 	// when this action is called directly.
 	RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
-}
-{{ if .viper }}
+}{{ if .viper }}
+
 // initConfig reads in config file and ENV variables if set.
 func initConfig() {
-	if cfgFile != "" { // enable ability to specify config file via flag
+	if cfgFile != "" {
+		// Use config file from the flag.
 		viper.SetConfigFile(cfgFile)
+	} else {
+		// Find home directory.
+		home, err := homedir.Dir()
+		if err != nil {
+			fmt.Println(home)
+			os.Exit(1)
+		}
+
+		// Search config in home directory with name ".cobra" (without extension).
+		viper.AddConfigPath(home)
+		viper.SetConfigName(".cobra")
 	}
 
-	viper.SetConfigName(".{{ .appName }}") // name of config file (without extension)
-	viper.AddConfigPath(os.Getenv("HOME")) // adding home directory as first search path
-	viper.AutomaticEnv()                   // read in environment variables that match
+	viper.AutomaticEnv() // read in environment variables that match
 
 	// If a config file is found, read it in.
 	if err := viper.ReadInConfig(); err == nil {
 		fmt.Println("Using config file:", viper.ConfigFileUsed())
 	}
-}
-{{ end }}`
+}{{ end }}
+`
 
 	data := make(map[string]interface{})
-
 	data["copyright"] = copyrightLine()
-	data["appName"] = projectName()
-
-	// Generate license template from header and data.
-	r, _ := templateToReader(lic.Header, data)
-	buf := new(bytes.Buffer)
-	buf.ReadFrom(r)
-	data["license"] = buf.String()
-
 	data["viper"] = viper.GetBool("useViper")
+	data["license"] = project.License().Header
+	data["appName"] = path.Base(project.Name())
+
+	rootCmdScript, err := executeTemplate(template, data)
+	if err != nil {
+		er(err)
+	}
 
-	err := writeTemplateToFile(ProjectPath()+string(os.PathSeparator)+guessCmdDir(), "root.go", template, data)
+	err = writeStringToFile(filepath.Join(project.CmdPath(), "root.go"), rootCmdScript)
 	if err != nil {
 		er(err)
 	}
 
-	fmt.Println("Your Cobra application is ready at")
-	fmt.Println(ProjectPath())
-	fmt.Println("Give it a try by going there and running `go run main.go`")
-	fmt.Println("Add commands to it by running `cobra add [cmdname]`")
 }
diff --git a/cobra/cmd/license_agpl.go b/cobra/cmd/license_agpl.go
index 10308cc..4ea036e 100644
--- a/cobra/cmd/license_agpl.go
+++ b/cobra/cmd/license_agpl.go
@@ -4,21 +4,20 @@ func initAgpl() {
 	Licenses["agpl"] = License{
 		Name:            "GNU Affero General Public License",
 		PossibleMatches: []string{"agpl", "affero gpl", "gnu agpl"},
-		Header: `
-This file is part of {{ .appName }}.
+		Header: `{{.copyright}}
 
-{{ .appName }} is free software: you can redistribute it and/or modify
+This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
-{{ .appName }} is distributed in the hope that it will be useful,
+This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.
 
 You should have received a copy of the GNU Affero General Public License
-along with {{ .appName }}. If not, see <http://www.gnu.org/licenses/>.`,
+along with this program. If not, see <http://www.gnu.org/licenses/>.`,
 		Text: `                    GNU AFFERO GENERAL PUBLIC LICENSE
                        Version 3, 19 November 2007
 
@@ -679,6 +678,7 @@ specific requirements.
   You should also get your employer (if you work as a programmer) or school,
 if any, to sign a "copyright disclaimer" for the program, if necessary.
 For more information on this, and how to apply and follow the GNU AGPL, see
-<http://www.gnu.org/licenses/>.`,
+<http://www.gnu.org/licenses/>.
+`,
 	}
 }
diff --git a/cobra/cmd/license_apache_2.go b/cobra/cmd/license_apache_2.go
index 878e1d9..3f33086 100644
--- a/cobra/cmd/license_apache_2.go
+++ b/cobra/cmd/license_apache_2.go
@@ -19,18 +19,17 @@ func initApache2() {
 	Licenses["apache"] = License{
 		Name:            "Apache 2.0",
 		PossibleMatches: []string{"apache", "apache20", "apache 2.0", "apache2.0", "apache-2.0"},
-		Header: `
-// 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.`,
+		Header: `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.`,
 		Text: `
                                  Apache License
                            Version 2.0, January 2004
diff --git a/cobra/cmd/license_gpl_2.go b/cobra/cmd/license_gpl_2.go
index 1105e35..054b470 100644
--- a/cobra/cmd/license_gpl_2.go
+++ b/cobra/cmd/license_gpl_2.go
@@ -19,20 +19,20 @@ func initGpl2() {
 	Licenses["gpl2"] = License{
 		Name:            "GNU General Public License 2.0",
 		PossibleMatches: []string{"gpl2", "gnu gpl2", "gplv2"},
-		Header: `{{ .copyright }}
+		Header: `{{.copyright}}
 
- {{ .appName }} is free software; you can redistribute it and/or
+ This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  as published by the Free Software Foundation; either version 2
  of the License, or (at your option) any later version.
 
- {{ .appName }} is distributed in the hope that it will be useful,
+ This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
 
  You should have received a copy of the GNU Lesser General Public License
- along with {{ .appName }}. If not, see <http://www.gnu.org/licenses/>.`,
+ along with this program. If not, see <http://www.gnu.org/licenses/>.`,
 		Text: `                    GNU GENERAL PUBLIC LICENSE
                        Version 2, June 1991
 
@@ -313,6 +313,65 @@ PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGES.
 
                      END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type 'show c' for details.
+
+The hypothetical commands 'show w' and 'show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than 'show w' and 'show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  'Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
 `,
 	}
 }
diff --git a/cobra/cmd/license_gpl_3.go b/cobra/cmd/license_gpl_3.go
index 009df9f..d1ef656 100644
--- a/cobra/cmd/license_gpl_3.go
+++ b/cobra/cmd/license_gpl_3.go
@@ -19,21 +19,20 @@ func initGpl3() {
 	Licenses["gpl3"] = License{
 		Name:            "GNU General Public License 3.0",
 		PossibleMatches: []string{"gpl3", "gplv3", "gpl", "gnu gpl3", "gnu gpl"},
-		Header: `
-This file is part of {{ .appName }}.
+		Header: `{{.copyright}}
 
-{{ .appName }} is free software: you can redistribute it and/or modify
+This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
-{{ .appName }} is distributed in the hope that it will be useful,
+This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
-along with {{ .appName }}. If not, see <http://www.gnu.org/licenses/>.`,
+along with this program. If not, see <http://www.gnu.org/licenses/>.`,
 		Text: `                    GNU GENERAL PUBLIC LICENSE
                        Version 3, 29 June 2007
 
@@ -655,6 +654,59 @@ Program, unless a warranty or assumption of liability accompanies a
 copy of the Program in return for a fee.
 
                      END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type 'show c' for details.
+
+The hypothetical commands 'show w' and 'show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
 `,
 	}
 }
diff --git a/cobra/cmd/license_lgpl.go b/cobra/cmd/license_lgpl.go
index 24f18f8..75fd043 100644
--- a/cobra/cmd/license_lgpl.go
+++ b/cobra/cmd/license_lgpl.go
@@ -4,21 +4,20 @@ func initLgpl() {
 	Licenses["lgpl"] = License{
 		Name:            "GNU Lesser General Public License",
 		PossibleMatches: []string{"lgpl", "lesser gpl", "gnu lgpl"},
-		Header: `
-This file is part of {{ .appName }}.
+		Header: `{{.copyright}}
 
-{{ .appName }} is free software: you can redistribute it and/or modify
+This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Lesser General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
-{{ .appName }} is distributed in the hope that it will be useful,
+This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Lesser General Public License for more details.
 
 You should have received a copy of the GNU Lesser General Public License
-along with {{ .appName }}. If not, see <http://www.gnu.org/licenses/>.`,
+along with this program. If not, see <http://www.gnu.org/licenses/>.`,
 		Text: `                   GNU LESSER GENERAL PUBLIC LICENSE
                        Version 3, 29 June 2007
 
diff --git a/cobra/cmd/licenses.go b/cobra/cmd/licenses.go
index 13ffbf7..d73e6fb 100644
--- a/cobra/cmd/licenses.go
+++ b/cobra/cmd/licenses.go
@@ -22,11 +22,11 @@ import (
 	"github.com/spf13/viper"
 )
 
-//Licenses contains all possible licenses a user can chose from
-var Licenses map[string]License
+// Licenses contains all possible licenses a user can choose from.
+var Licenses = make(map[string]License)
 
-//License represents a software license agreement, containing the Name of
-// the license, its possible matches (on the command line as given to cobra)
+// License represents a software license agreement, containing the Name of
+// the license, its possible matches (on the command line as given to cobra),
 // the header to be used with each file on the file's creating, and the text
 // of the license
 type License struct {
@@ -37,14 +37,9 @@ type License struct {
 }
 
 func init() {
-	Licenses = make(map[string]License)
-
 	// Allows a user to not use a license.
 	Licenses["none"] = License{"None", []string{"none", "false"}, "", ""}
 
-	// Allows a user to use config for a custom license.
-	Licenses["custom"] = License{"Custom", []string{}, "", ""}
-
 	initApache2()
 	initMit()
 	initBsdClause3()
@@ -53,49 +48,31 @@ func init() {
 	initGpl3()
 	initLgpl()
 	initAgpl()
-
-	// Licenses["apache20"] = License{
-	// 	Name:            "Apache 2.0",
-	// 	PossibleMatches: []string{"apache", "apache20", ""},
-	//   Header: `
-	//   `,
-	// 	Text: `
-	//   `,
-	// }
 }
 
+// getLicense returns license specified by user in flag or in config.
+// If user didn't specify the license, it returns Apache License 2.0.
+//
+// TODO: Inspect project for existing license
 func getLicense() License {
-	l := whichLicense()
-	if l != "" {
-		if x, ok := Licenses[l]; ok {
-			return x
-		}
-	}
-
-	return Licenses["apache"]
-}
-
-func whichLicense() string {
-	// if explicitly flagged, use that
+	// If explicitly flagged, use that.
 	if userLicense != "" {
-		return matchLicense(userLicense)
+		return findLicense(userLicense)
 	}
 
-	// if already present in the project, use that
-	// TODO: Inspect project for existing license
-
-	// default to viper's setting
-
+	// If user wants to have custom license, use that.
 	if viper.IsSet("license.header") || viper.IsSet("license.text") {
-		if custom, ok := Licenses["custom"]; ok {
-			custom.Header = viper.GetString("license.header")
-			custom.Text = viper.GetString("license.text")
-			Licenses["custom"] = custom
-			return "custom"
-		}
+		return License{Header: viper.GetString("license.header"),
+			Text: "license.text"}
+	}
+
+	// If user wants to have built-in license, use that.
+	if viper.IsSet("license") {
+		return findLicense(viper.GetString("license"))
 	}
 
-	return matchLicense(viper.GetString("license"))
+	// If user didn't set any license, use Apache 2.0 by default.
+	return Licenses["apache"]
 }
 
 func copyrightLine() string {
@@ -105,14 +82,33 @@ func copyrightLine() string {
 	return "Copyright © " + year + " " + author
 }
 
-// given a license name (in), try to match the license indicated
-func matchLicense(in string) string {
+// findLicense looks for License object of built-in licenses.
+// If it didn't find license, then the app will be terminated and
+// error will be printed.
+func findLicense(name string) License {
+	found := matchLicense(name)
+	if found == "" {
+		er("unknown license: " + name)
+	}
+	return Licenses[found]
+}
+
+// matchLicense compares the given a license name
+// to PossibleMatches of all built-in licenses.
+// It returns blank string, if name is blank string or it didn't find
+// then appropriate match to name.
+func matchLicense(name string) string {
+	if name == "" {
+		return ""
+	}
+
 	for key, lic := range Licenses {
 		for _, match := range lic.PossibleMatches {
-			if strings.EqualFold(in, match) {
+			if strings.EqualFold(name, match) {
 				return key
 			}
 		}
 	}
+
 	return ""
 }
diff --git a/cobra/cmd/project.go b/cobra/cmd/project.go
new file mode 100644
index 0000000..a3e6d91
--- /dev/null
+++ b/cobra/cmd/project.go
@@ -0,0 +1,182 @@
+package cmd
+
+import (
+	"os"
+	"path/filepath"
+	"strings"
+)
+
+// Project contains name, license and paths to projects.
+type Project struct {
+	absPath string
+	cmdPath string
+	srcPath string
+	license License
+	name    string
+}
+
+// NewProject returns Project with specified project name.
+// If projectName is blank string, it returns nil.
+func NewProject(projectName string) *Project {
+	if projectName == "" {
+		return nil
+	}
+
+	p := new(Project)
+	p.name = projectName
+
+	// 1. Find already created protect.
+	p.absPath = findPackage(projectName)
+
+	// 2. If there are no created project with this path, and user is in GOPATH,
+	// then use GOPATH/src/projectName.
+	if p.absPath == "" {
+		wd, err := os.Getwd()
+		if err != nil {
+			er(err)
+		}
+		for _, srcPath := range srcPaths {
+			goPath := filepath.Dir(srcPath)
+			if filepath.HasPrefix(wd, goPath) {
+				p.absPath = filepath.Join(srcPath, projectName)
+				break
+			}
+		}
+	}
+
+	// 3. If user is not in GOPATH, then use (first GOPATH)/src/projectName.
+	if p.absPath == "" {
+		p.absPath = filepath.Join(srcPaths[0], projectName)
+	}
+
+	return p
+}
+
+// findPackage returns full path to existing go package in GOPATHs.
+// findPackage returns "", if it can't find path.
+// If packageName is "", findPackage returns "".
+func findPackage(packageName string) string {
+	if packageName == "" {
+		return ""
+	}
+
+	for _, srcPath := range srcPaths {
+		packagePath := filepath.Join(srcPath, packageName)
+		if exists(packagePath) {
+			return packagePath
+		}
+	}
+
+	return ""
+}
+
+// NewProjectFromPath returns Project with specified absolute path to
+// package.
+// If absPath is blank string or if absPath is not actually absolute,
+// it returns nil.
+func NewProjectFromPath(absPath string) *Project {
+	if absPath == "" || !filepath.IsAbs(absPath) {
+		return nil
+	}
+
+	p := new(Project)
+	p.absPath = absPath
+	p.absPath = strings.TrimSuffix(p.absPath, findCmdDir(p.absPath))
+	p.name = filepath.ToSlash(trimSrcPath(p.absPath, p.SrcPath()))
+	return p
+}
+
+// trimSrcPath trims at the beginning of absPath the srcPath.
+func trimSrcPath(absPath, srcPath string) string {
+	relPath, err := filepath.Rel(srcPath, absPath)
+	if err != nil {
+		er("Cobra supports project only within $GOPATH")
+	}
+	return relPath
+}
+
+// License returns the License object of project.
+func (p *Project) License() License {
+	if p.license.Text == "" && p.license.Name != "None" {
+		p.license = getLicense()
+	}
+
+	return p.license
+}
+
+// Name returns the name of project, e.g. "github.com/spf13/cobra"
+func (p Project) Name() string {
+	return p.name
+}
+
+// CmdPath returns absolute path to directory, where all commands are located.
+//
+// CmdPath returns blank string, only if p.AbsPath() is a blank string.
+func (p *Project) CmdPath() string {
+	if p.absPath == "" {
+		return ""
+	}
+	if p.cmdPath == "" {
+		p.cmdPath = filepath.Join(p.absPath, findCmdDir(p.absPath))
+	}
+	return p.cmdPath
+}
+
+// findCmdDir checks if base of absPath is cmd dir and returns it or
+// looks for existing cmd dir in absPath.
+// If the cmd dir doesn't exist, empty, or cannot be found,
+// it returns "cmd".
+func findCmdDir(absPath string) string {
+	if !exists(absPath) || isEmpty(absPath) {
+		return "cmd"
+	}
+
+	if isCmdDir(absPath) {
+		return filepath.Base(absPath)
+	}
+
+	files, _ := filepath.Glob(filepath.Join(absPath, "c*"))
+	for _, file := range files {
+		if isCmdDir(file) {
+			return filepath.Base(file)
+		}
+	}
+
+	return "cmd"
+}
+
+// isCmdDir checks if base of name is one of cmdDir.
+func isCmdDir(name string) bool {
+	name = filepath.Base(name)
+	for _, cmdDir := range cmdDirs {
+		if name == cmdDir {
+			return true
+		}
+	}
+	return false
+}
+
+// AbsPath returns absolute path of project.
+func (p Project) AbsPath() string {
+	return p.absPath
+}
+
+// SrcPath returns absolute path to $GOPATH/src where project is located.
+func (p *Project) SrcPath() string {
+	if p.srcPath != "" {
+		return p.srcPath
+	}
+	if p.absPath == "" {
+		p.srcPath = srcPaths[0]
+		return p.srcPath
+	}
+
+	for _, srcPath := range srcPaths {
+		if strings.HasPrefix(p.absPath, srcPath) {
+			p.srcPath = srcPath
+			break
+		}
+	}
+
+	return p.srcPath
+}
diff --git a/cobra/cmd/root.go b/cobra/cmd/root.go
index 32386ac..967eecc 100644
--- a/cobra/cmd/root.go
+++ b/cobra/cmd/root.go
@@ -17,14 +17,13 @@ import (
 	"fmt"
 	"os"
 
+	homedir "github.com/mitchellh/go-homedir"
 	"github.com/spf13/cobra"
 	"github.com/spf13/viper"
 )
 
-var cfgFile string
-var userLicense string
+var cfgFile, projectBase, userLicense string // are used for flags
 
-// RootCmd represents the base command when called without any subcommands
 var RootCmd = &cobra.Command{
 	Use:   "cobra",
 	Short: "A generator for Cobra based Applications",
@@ -33,16 +32,16 @@ This application is a tool to generate the needed files
 to quickly create a Cobra application.`,
 }
 
-//Execute adds all child commands to the root command sets flags appropriately.
 func Execute() {
 	if err := RootCmd.Execute(); err != nil {
 		fmt.Println(err)
-		os.Exit(-1)
+		os.Exit(1)
 	}
 }
 
 func init() {
-	cobra.OnInitialize(initConfig)
+	initViper()
+
 	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
 	RootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory, e.g. github.com/spf13/")
 	RootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution")
@@ -53,19 +52,31 @@ func init() {
 	viper.BindPFlag("useViper", RootCmd.PersistentFlags().Lookup("viper"))
 	viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
 	viper.SetDefault("license", "apache")
+
+	RootCmd.AddCommand(initCmd)
+	RootCmd.AddCommand(addCmd)
+
 }
 
-// Read in config file and ENV variables if set.
-func initConfig() {
-	if cfgFile != "" { // enable ability to specify config file via flag
+func initViper() {
+	if cfgFile != "" {
+		// Use config file from the flag.
 		viper.SetConfigFile(cfgFile)
+	} else {
+		// Find home directory.
+		home, err := homedir.Dir()
+		if err != nil {
+			fmt.Println(home)
+			os.Exit(1)
+		}
+
+		// Search config in home directory with name ".cobra" (without extension).
+		viper.AddConfigPath(home)
+		viper.SetConfigName(".cobra")
 	}
 
-	viper.SetConfigName(".cobra")          // name of config file (without extension)
-	viper.AddConfigPath(os.Getenv("HOME")) // adding home directory as first search path
-	viper.AutomaticEnv()                   // read in environment variables that match
+	viper.AutomaticEnv()
 
-	// If a config file is found, read it in.
 	if err := viper.ReadInConfig(); err == nil {
 		fmt.Println("Using config file:", viper.ConfigFileUsed())
 	}
diff --git a/command.go b/command.go
index 79956f3..ebc9ab2 100644
--- a/command.go
+++ b/command.go
@@ -11,8 +11,8 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-//Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces.
-//In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code.
+// Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces.
+// In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code.
 package cobra
 
 import (
@@ -114,6 +114,9 @@ type Command struct {
 	// is commands slice are sorted or not
 	commandsAreSorted bool
 
+	// flagErrorBuf contains all error messages from pflag.
+	flagErrorBuf *bytes.Buffer
+
 	args          []string             // actual args parsed from flags
 	output        io.Writer            // out writer if set in SetOutput(w)
 	usageFunc     func(*Command) error // Usage can be defined by application
@@ -366,8 +369,8 @@ func (c *Command) HelpTemplate() string {
 {{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
 }
 
-func hasNoOptDefVal(name string, f *flag.FlagSet) bool {
-	flag := f.Lookup(name)
+func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {
+	flag := fs.Lookup(name)
 	if flag == nil {
 		return false
 	}
@@ -375,14 +378,15 @@ func hasNoOptDefVal(name string, f *flag.FlagSet) bool {
 }
 
 func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {
-	result := false
-	fs.VisitAll(func(flag *flag.Flag) {
-		if flag.Shorthand == name && flag.NoOptDefVal != "" {
-			result = true
-			return
-		}
-	})
-	return result
+	if len(name) == 0 {
+		return false
+	}
+
+	flag := fs.ShorthandLookup(name[:1])
+	if flag == nil {
+		return false
+	}
+	return flag.NoOptDefVal != ""
 }
 
 func stripFlags(args []string, c *Command) []string {
@@ -567,18 +571,19 @@ func (c *Command) execute(a []string) (err error) {
 
 	// initialize help flag as the last point possible to allow for user
 	// overriding
-	c.initHelpFlag()
+	c.InitDefaultHelpFlag()
 
 	err = c.ParseFlags(a)
 	if err != nil {
 		return c.FlagErrorFunc()(c, err)
 	}
-	// If help is called, regardless of other flags, return we want help
+
+	// If help is called, regardless of other flags, return we want help.
 	// Also say we need help if the command isn't runnable.
 	helpVal, err := c.Flags().GetBool("help")
 	if err != nil {
 		// should be impossible to get here as we always declare a help
-		// flag in initHelpFlag()
+		// flag in InitDefaultHelpFlag()
 		c.Println("\"help\" flag declared as non-bool. Please correct your code")
 		return err
 	}
@@ -718,7 +723,9 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
 	return cmd, nil
 }
 
-func (c *Command) initHelpFlag() {
+// InitDefaultHelpFlag adds default help flag to c.
+// It is called automatically by executing the c or by calling help and usage.
+func (c *Command) InitDefaultHelpFlag() {
 	c.mergePersistentFlags()
 	if c.Flags().Lookup("help") == nil {
 		usage := "help for "
@@ -751,7 +758,7 @@ func (c *Command) initHelpCmd() {
 					c.Printf("Unknown help topic %#q\n", args)
 					c.Root().Usage()
 				} else {
-					cmd.initHelpFlag() // make possible 'help' flag to be shown
+					cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
 					cmd.Help()
 				}
 			},
@@ -915,6 +922,7 @@ func (c *Command) DebugFlags() {
 				}
 			})
 		}
+		c.Println(x.flagErrorBuf)
 		if x.HasSubCommands() {
 			for _, y := range x.commands {
 				debugflags(y)
@@ -1055,7 +1063,10 @@ func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) f
 func (c *Command) Flags() *flag.FlagSet {
 	if c.flags == nil {
 		c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
-		c.flags.SetOutput(c.OutOrStderr())
+		if c.flagErrorBuf == nil {
+			c.flagErrorBuf = new(bytes.Buffer)
+		}
+		c.flags.SetOutput(c.flagErrorBuf)
 	}
 
 	return c.flags
@@ -1080,7 +1091,10 @@ func (c *Command) LocalFlags() *flag.FlagSet {
 
 	if c.lflags == nil {
 		c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
-		c.lflags.SetOutput(c.OutOrStderr())
+		if c.flagErrorBuf == nil {
+			c.flagErrorBuf = new(bytes.Buffer)
+		}
+		c.lflags.SetOutput(c.flagErrorBuf)
 	}
 	c.lflags.SortFlags = c.Flags().SortFlags
 
@@ -1100,6 +1114,10 @@ func (c *Command) InheritedFlags() *flag.FlagSet {
 
 	if c.iflags == nil {
 		c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
+		if c.flagErrorBuf == nil {
+			c.flagErrorBuf = new(bytes.Buffer)
+		}
+		c.iflags.SetOutput(c.flagErrorBuf)
 	}
 
 	local := c.LocalFlags()
@@ -1120,17 +1138,22 @@ func (c *Command) NonInheritedFlags() *flag.FlagSet {
 func (c *Command) PersistentFlags() *flag.FlagSet {
 	if c.pflags == nil {
 		c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
-		c.pflags.SetOutput(c.OutOrStderr())
+		if c.flagErrorBuf == nil {
+			c.flagErrorBuf = new(bytes.Buffer)
+		}
+		c.pflags.SetOutput(c.flagErrorBuf)
 	}
 	return c.pflags
 }
 
 // ResetFlags is used in testing.
 func (c *Command) ResetFlags() {
+	c.flagErrorBuf = new(bytes.Buffer)
+	c.flagErrorBuf.Reset()
 	c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
-	c.flags.SetOutput(c.OutOrStderr())
+	c.flags.SetOutput(c.flagErrorBuf)
 	c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
-	c.pflags.SetOutput(c.OutOrStderr())
+	c.pflags.SetOutput(c.flagErrorBuf)
 }
 
 // HasFlags checks if the command contains any flags (local plus persistent from the entire structure).
@@ -1229,7 +1252,7 @@ func (c *Command) mergePersistentFlags() {
 func (c *Command) updateParentsPflags() {
 	if c.parentsPflags == nil {
 		c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
-		c.parentsPflags.SetOutput(c.OutOrStderr())
+		c.parentsPflags.SetOutput(c.flagErrorBuf)
 		c.parentsPflags.SortFlags = false
 	}
 


Test patch:
diff --git a/cobra/cmd/add_test.go b/cobra/cmd/add_test.go
new file mode 100644
index 0000000..dacbe83
--- /dev/null
+++ b/cobra/cmd/add_test.go
@@ -0,0 +1,100 @@
+package cmd
+
+import (
+	"errors"
+	"io/ioutil"
+	"os"
+	"path/filepath"
+	"testing"
+)
+
+// TestGoldenAddCmd initializes the project "github.com/spf13/testproject"
+// in GOPATH, adds "test" command
+// and compares the content of all files in cmd directory of testproject
+// with appropriate golden files.
+// Use -update to update existing golden files.
+func TestGoldenAddCmd(t *testing.T) {
+	projectName := "github.com/spf13/testproject"
+	project := NewProject(projectName)
+
+	// Initialize the project at first.
+	initializeProject(project)
+	defer os.RemoveAll(project.AbsPath())
+
+	// Then add the "test" command.
+	cmdName := "test"
+	cmdPath := filepath.Join(project.CmdPath(), cmdName+".go")
+	createCmdFile(project.License(), cmdPath, cmdName)
+
+	expectedFiles := []string{".", "root.go", "test.go"}
+	gotFiles := []string{}
+
+	// Check project file hierarchy and compare the content of every single file
+	// with appropriate golden file.
+	err := filepath.Walk(project.CmdPath(), func(path string, info os.FileInfo, err error) error {
+		if err != nil {
+			return err
+		}
+
+		// Make path relative to project.CmdPath().
+		// E.g. path = "/home/user/go/src/github.com/spf13/testproject/cmd/root.go"
+		// then it returns just "root.go".
+		relPath, err := filepath.Rel(project.CmdPath(), path)
+		if err != nil {
+			return err
+		}
+		relPath = filepath.ToSlash(relPath)
+		gotFiles = append(gotFiles, relPath)
+		goldenPath := filepath.Join("testdata", filepath.Base(path)+".golden")
+
+		switch relPath {
+		// Know directories.
+		case ".":
+			return nil
+		// Known files.
+		case "root.go", "test.go":
+			if *update {
+				got, err := ioutil.ReadFile(path)
+				if err != nil {
+					return err
+				}
+				ioutil.WriteFile(goldenPath, got, 0644)
+			}
+			return compareFiles(path, goldenPath)
+		}
+		// Unknown file.
+		return errors.New("unknown file: " + path)
+	})
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	// Check if some files lack.
+	if err := checkLackFiles(expectedFiles, gotFiles); err != nil {
+		t.Fatal(err)
+	}
+}
+
+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"},
+		{"cmdName-----", "cmdName"},
+		{"cmdname-", "cmdname"},
+	}
+
+	for _, testCase := range testCases {
+		got := validateCmdName(testCase.input)
+		if testCase.expected != got {
+			t.Errorf("Expected %q, got %q", testCase.expected, got)
+		}
+	}
+}
diff --git a/cobra/cmd/golden_test.go b/cobra/cmd/golden_test.go
new file mode 100644
index 0000000..0ac7e89
--- /dev/null
+++ b/cobra/cmd/golden_test.go
@@ -0,0 +1,77 @@
+package cmd
+
+import (
+	"bytes"
+	"errors"
+	"flag"
+	"fmt"
+	"io/ioutil"
+	"os/exec"
+)
+
+var update = flag.Bool("update", false, "update .golden files")
+
+func init() {
+	// Mute commands.
+	addCmd.SetOutput(new(bytes.Buffer))
+	initCmd.SetOutput(new(bytes.Buffer))
+}
+
+// compareFiles compares the content of files with pathA and pathB.
+// If contents are equal, it returns nil.
+// If not, it returns which files are not equal
+// and diff (if system has diff command) between these files.
+func compareFiles(pathA, pathB string) error {
+	contentA, err := ioutil.ReadFile(pathA)
+	if err != nil {
+		return err
+	}
+	contentB, err := ioutil.ReadFile(pathB)
+	if err != nil {
+		return err
+	}
+	if !bytes.Equal(contentA, contentB) {
+		output := new(bytes.Buffer)
+		output.WriteString(fmt.Sprintf("%q and %q are not equal!\n\n", pathA, pathB))
+
+		diffPath, err := exec.LookPath("diff")
+		if err != nil {
+			// Don't execute diff if it can't be found.
+			return nil
+		}
+		diffCmd := exec.Command(diffPath, pathA, pathB)
+		diffCmd.Stdout = output
+		diffCmd.Stderr = output
+
+		output.WriteString("$ diff " + pathA + " " + pathB + "\n")
+		if err := diffCmd.Run(); err != nil {
+			output.WriteString("\n" + err.Error())
+		}
+		return errors.New(output.String())
+	}
+	return nil
+}
+
+// checkLackFiles checks if all elements of expected are in got.
+func checkLackFiles(expected, got []string) error {
+	lacks := make([]string, 0, len(expected))
+	for _, ev := range expected {
+		if !stringInStringSlice(ev, got) {
+			lacks = append(lacks, ev)
+		}
+	}
+	if len(lacks) > 0 {
+		return fmt.Errorf("Lack %v file(s): %v", len(lacks), lacks)
+	}
+	return nil
+}
+
+// stringInStringSlice checks if s is an element of slice.
+func stringInStringSlice(s string, slice []string) bool {
+	for _, v := range slice {
+		if s == v {
+			return true
+		}
+	}
+	return false
+}
diff --git a/cobra/cmd/helpers_test.go b/cobra/cmd/helpers_test.go
deleted file mode 100644
index bce9471..0000000
--- a/cobra/cmd/helpers_test.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package cmd
-
-import (
-	"path/filepath"
-	"testing"
-)
-
-func checkGuess(t *testing.T, wd, input, expected string) {
-	testWd = wd
-	inputPath = input
-	guessProjectPath()
-
-	if projectPath != expected {
-		t.Errorf("Unexpected Project Path. \n Got: %q\nExpected: %q\n", projectPath, expected)
-	}
-
-	reset()
-}
-
-func reset() {
-	testWd = ""
-	inputPath = ""
-	projectPath = ""
-}
-
-func TestProjectPath(t *testing.T) {
-	checkGuess(t, "", filepath.Join("github.com", "spf13", "hugo"), filepath.Join(getSrcPath(), "github.com", "spf13", "hugo"))
-	checkGuess(t, "", filepath.Join("spf13", "hugo"), filepath.Join(getSrcPath(), "github.com", "spf13", "hugo"))
-	checkGuess(t, "", filepath.Join("/", "bar", "foo"), filepath.Join("/", "bar", "foo"))
-	checkGuess(t, "/bar/foo", "baz", filepath.Join("/", "bar", "foo", "baz"))
-	checkGuess(t, "/bar/foo/cmd", "", filepath.Join("/", "bar", "foo"))
-	checkGuess(t, "/bar/foo/command", "", filepath.Join("/", "bar", "foo"))
-	checkGuess(t, "/bar/foo/commands", "", filepath.Join("/", "bar", "foo"))
-	checkGuess(t, "github.com/spf13/hugo/../hugo", "", filepath.Join("github.com", "spf13", "hugo"))
-}
diff --git a/cobra/cmd/init_test.go b/cobra/cmd/init_test.go
new file mode 100644
index 0000000..f97be30
--- /dev/null
+++ b/cobra/cmd/init_test.go
@@ -0,0 +1,72 @@
+package cmd
+
+import (
+	"errors"
+	"io/ioutil"
+	"os"
+	"path/filepath"
+	"testing"
+)
+
+// TestGoldenInitCmd initializes the project "github.com/spf13/testproject"
+// in GOPATH and compares the content of files in initialized project with
+// appropriate golden files ("testdata/*.golden").
+// Use -update to update existing golden files.
+func TestGoldenInitCmd(t *testing.T) {
+	projectName := "github.com/spf13/testproject"
+	project := NewProject(projectName)
+	defer os.RemoveAll(project.AbsPath())
+
+	os.Args = []string{"cobra", "init", projectName}
+	if err := RootCmd.Execute(); err != nil {
+		t.Fatal("Error by execution:", err)
+	}
+
+	expectedFiles := []string{".", "cmd", "LICENSE", "main.go", "cmd/root.go"}
+	gotFiles := []string{}
+
+	// Check project file hierarchy and compare the content of every single file
+	// with appropriate golden file.
+	err := filepath.Walk(project.AbsPath(), func(path string, info os.FileInfo, err error) error {
+		if err != nil {
+			return err
+		}
+
+		// Make path relative to project.AbsPath().
+		// E.g. path = "/home/user/go/src/github.com/spf13/testproject/cmd/root.go"
+		// then it returns just "cmd/root.go".
+		relPath, err := filepath.Rel(project.AbsPath(), path)
+		if err != nil {
+			return err
+		}
+		relPath = filepath.ToSlash(relPath)
+		gotFiles = append(gotFiles, relPath)
+		goldenPath := filepath.Join("testdata", filepath.Base(path)+".golden")
+
+		switch relPath {
+		// Know directories.
+		case ".", "cmd":
+			return nil
+		// Known files.
+		case "LICENSE", "main.go", "cmd/root.go":
+			if *update {
+				got, err := ioutil.ReadFile(path)
+				if err != nil {
+					return err
+				}
+				ioutil.WriteFile(goldenPath, got, 0644)
+			}
+			return compareFiles(path, goldenPath)
+		}
+		// Unknown file.
+		return errors.New("unknown file: " + path)
+	})
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	// Check if some files lack.
+	if err := checkLackFiles(expectedFiles, gotFiles); err != nil {
+		t.Fatal(err)
+	}
+}
diff --git a/cobra/cmd/project_test.go b/cobra/cmd/project_test.go
new file mode 100644
index 0000000..2774094
--- /dev/null
+++ b/cobra/cmd/project_test.go
@@ -0,0 +1,25 @@
+package cmd
+
+import (
+	"path/filepath"
+	"testing"
+)
+
+func TestFindExistingPackage(t *testing.T) {
+	path := findPackage("github.com/spf13/cobra")
+	if path == "" {
+		t.Fatal("findPackage didn't find the existing package")
+	}
+	if !hasGoPathPrefix(path) {
+		t.Fatalf("%q is not in GOPATH, but must be", path)
+	}
+}
+
+func hasGoPathPrefix(path string) bool {
+	for _, srcPath := range srcPaths {
+		if filepath.HasPrefix(path, srcPath) {
+			return true
+		}
+	}
+	return false
+}
diff --git a/cobra/cmd/testdata/LICENSE.golden b/cobra/cmd/testdata/LICENSE.golden
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/cobra/cmd/testdata/LICENSE.golden
@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   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.
diff --git a/cobra/cmd/testdata/main.go.golden b/cobra/cmd/testdata/main.go.golden
new file mode 100644
index 0000000..69ecbd4
--- /dev/null
+++ b/cobra/cmd/testdata/main.go.golden
@@ -0,0 +1,20 @@
+// Copyright © 2017 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 main
+
+import "github.com/spf13/testproject/cmd"
+
+func main() {
+	cmd.Execute()
+}
diff --git a/cobra/cmd/testdata/root.go.golden b/cobra/cmd/testdata/root.go.golden
new file mode 100644
index 0000000..a8f4ff1
--- /dev/null
+++ b/cobra/cmd/testdata/root.go.golden
@@ -0,0 +1,88 @@
+// Copyright © 2017 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"
+	"os"
+
+	homedir "github.com/mitchellh/go-homedir"
+	"github.com/spf13/cobra"
+	"github.com/spf13/viper"
+)
+
+var cfgFile string
+
+// RootCmd represents the base command when called without any subcommands
+var RootCmd = &cobra.Command{
+	Use:   "testproject",
+	Short: "A brief description of your application",
+	Long: `A longer description that spans multiple lines and likely contains
+examples and usage of using your application. 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.`,
+	// Uncomment the following line if your bare application
+	// has an action associated with it:
+	//	Run: func(cmd *cobra.Command, args []string) { },
+}
+
+// Execute adds all child commands to the root command sets flags appropriately.
+// This is called by main.main(). It only needs to happen once to the rootCmd.
+func Execute() {
+	if err := RootCmd.Execute(); err != nil {
+		fmt.Println(err)
+		os.Exit(1)
+	}
+}
+
+func init() {
+	cobra.OnInitialize(initConfig)
+
+	// Here you will define your flags and configuration settings.
+	// Cobra supports persistent flags, which, if defined here,
+	// will be global for your application.
+	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.testproject.yaml)")
+
+	// Cobra also supports local flags, which will only run
+	// when this action is called directly.
+	RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
+}
+
+// initConfig reads in config file and ENV variables if set.
+func initConfig() {
+	if cfgFile != "" {
+		// Use config file from the flag.
+		viper.SetConfigFile(cfgFile)
+	} else {
+		// Find home directory.
+		home, err := homedir.Dir()
+		if err != nil {
+			fmt.Println(home)
+			os.Exit(1)
+		}
+
+		// Search config in home directory with name ".cobra" (without extension).
+		viper.AddConfigPath(home)
+		viper.SetConfigName(".cobra")
+	}
+
+	viper.AutomaticEnv() // read in environment variables that match
+
+	// If a config file is found, read it in.
+	if err := viper.ReadInConfig(); err == nil {
+		fmt.Println("Using config file:", viper.ConfigFileUsed())
+	}
+}
diff --git a/cobra/cmd/testdata/test.go.golden b/cobra/cmd/testdata/test.go.golden
new file mode 100644
index 0000000..c8319d1
--- /dev/null
+++ b/cobra/cmd/testdata/test.go.golden
@@ -0,0 +1,49 @@
+// Copyright © 2017 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 = &cobra.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")
+	},
+}
+
+func init() {
+	RootCmd.AddCommand(testCmd)
+
+	// Here you will define your flags and configuration settings.
+
+	// Cobra supports Persistent Flags which will work for this command
+	// and all subcommands, e.g.:
+	// testCmd.PersistentFlags().String("foo", "", "A help for foo")
+
+	// Cobra supports local flags which will only run when this command
+	// is called directly, e.g.:
+	// testCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
+}
diff --git a/command_test.go b/command_test.go
index d8c5021..24abd3e 100644
--- a/command_test.go
+++ b/command_test.go
@@ -146,7 +146,7 @@ func TestInitHelpFlagMergesFlags(t *testing.T) {
 	cmd := Command{Use: "do"}
 	baseCmd.AddCommand(&cmd)
 
-	cmd.initHelpFlag()
+	cmd.InitDefaultHelpFlag()
 	actual := cmd.Flags().Lookup("help").Usage
 	if actual != usage {
 		t.Fatalf("Expected the help flag from the base command with usage '%s', but got the default with usage '%s'", usage, actual)
@@ -227,8 +227,7 @@ func TestFlagErrorFunc(t *testing.T) {
 
 // TestSortedFlags checks,
 // if cmd.LocalFlags() is unsorted when cmd.Flags().SortFlags set to false.
-//
-// Source: https://github.com/spf13/cobra/issues/404
+// https://github.com/spf13/cobra/issues/404
 func TestSortedFlags(t *testing.T) {
 	cmd := &Command{}
 	cmd.Flags().SortFlags = false
@@ -264,8 +263,7 @@ func isStringInStringSlice(s string, ss []string) bool {
 // TestHelpFlagInHelp checks,
 // if '--help' flag is shown in help for child (executing `parent help child`),
 // that has no other flags.
-//
-// Source: https://github.com/spf13/cobra/issues/302
+// https://github.com/spf13/cobra/issues/302
 func TestHelpFlagInHelp(t *testing.T) {
 	output := new(bytes.Buffer)
 	parent := &Command{Use: "parent", Long: "long", Run: func(*Command, []string) { return }}