Repository: spf13/cobra
Pull request #436 (2017-05-08 06:33:12)

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


Patch:
diff --git a/README.md b/README.md
index ae48aa0..5508909 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@ Many of the most widely used Go projects are built using Cobra including:
 * [Hugo](http://gohugo.io)
 * [rkt](https://github.com/coreos/rkt)
 * [etcd](https://github.com/coreos/etcd)
-* [Docker](https://github.com/docker/docker)
+* [Moby (former Docker)](https://github.com/moby/moby)
 * [Docker (distribution)](https://github.com/docker/distribution)
 * [OpenShift](https://www.openshift.com/)
 * [Delve](https://github.com/derekparker/delve)
@@ -114,7 +114,7 @@ and flags that are only available to that command.
 In the example above, 'port' is the flag.
 
 Flag functionality is provided by the [pflag
-library](https://github.com/ogier/pflag), a fork of the flag standard library
+library](https://github.com/spf13/pflag), a fork of the flag standard library
 which maintains the same interface while adding POSIX compliance.
 
 ## Usage
@@ -127,10 +127,10 @@ tree is assigned to the commander which is finally executed.
 
 # Installing
 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:
+of the library. This command will install the `cobra` generator executable
+along with the library and its dependencies:
 
-    go get -v github.com/spf13/cobra/cobra
+    go get -u github.com/spf13/cobra
 
 Next, include Cobra in your application:
 
@@ -860,39 +860,12 @@ out everything Cobra knows about the flags for each command.
 command.DebugFlags()
 ```
 
-## Release Notes
-* **0.9.0** June 17, 2014
-  * flags can appears anywhere in the args (provided they are unambiguous)
-  * --help prints usage screen for app or command
-  * Prefix matching for commands
-  * Cleaner looking help and usage output
-  * Extensive test suite
-* **0.8.0** Nov 5, 2013
-  * Reworked interface to remove commander completely
-  * Command now primary structure
-  * No initialization needed
-  * Usage & Help templates & functions definable at any level
-  * Updated Readme
-* **0.7.0** Sept 24, 2013
-  * Needs more eyes
-  * Test suite
-  * Support for automatic error messages
-  * Support for help command
-  * Support for printing to any io.Writer instead of os.Stderr
-  * Support for persistent flags which cascade down tree
-  * Ready for integration into Hugo
-* **0.1.0** Sept 3, 2013
-  * Implement first draft
-
 ## Extensions
 
 Libraries for extending Cobra:
 
 * [cmdns](https://github.com/gosuri/cmdns): Enables name spacing a command's immediate children. It provides an alternative way to structure subcommands, similar to `heroku apps:create` and `ovrclk clusters:launch`.
 
-## ToDo
-* Launch proper documentation site
-
 ## Contributing
 
 1. Fork it
@@ -912,6 +885,3 @@ Names in no particular order:
 ## License
 
 Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt)
-
-
-[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/spf13/cobra/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
diff --git a/bash_completions.go b/bash_completions.go
index a0d0402..5d6238b 100644
--- a/bash_completions.go
+++ b/bash_completions.go
@@ -1,6 +1,7 @@
 package cobra
 
 import (
+	"bytes"
 	"fmt"
 	"io"
 	"os"
@@ -18,12 +19,9 @@ const (
 	BashCompSubdirsInDir    = "cobra_annotation_bash_completion_subdirs_in_dir"
 )
 
-func preamble(out io.Writer, name string) error {
-	_, err := fmt.Fprintf(out, "# bash completion for %-36s -*- shell-script -*-\n", name)
-	if err != nil {
-		return err
-	}
-	preamStr := `
+func writePreamble(buf *bytes.Buffer, name string) {
+	buf.WriteString(fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name))
+	buf.WriteString(`
 __debug()
 {
     if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then
@@ -247,18 +245,13 @@ __handle_word()
     __handle_word
 }
 
-`
-	_, err = fmt.Fprint(out, preamStr)
-	return err
+`)
 }
 
-func postscript(w io.Writer, name string) error {
+func writePostscript(buf *bytes.Buffer, name string) {
 	name = strings.Replace(name, ":", "__", -1)
-	_, err := fmt.Fprintf(w, "__start_%s()\n", name)
-	if err != nil {
-		return err
-	}
-	_, err = fmt.Fprintf(w, `{
+	buf.WriteString(fmt.Sprintf("__start_%s()\n", name))
+	buf.WriteString(fmt.Sprintf(`{
     local cur prev words cword
     declare -A flaghash 2>/dev/null || :
     if declare -F _init_completion >/dev/null 2>&1; then
@@ -282,197 +275,132 @@ func postscript(w io.Writer, name string) error {
     __handle_word
 }
 
-`, name)
-	if err != nil {
-		return err
-	}
-	_, err = fmt.Fprintf(w, `if [[ $(type -t compopt) = "builtin" ]]; then
+`, name))
+	buf.WriteString(fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then
     complete -o default -F __start_%s %s
 else
     complete -o default -o nospace -F __start_%s %s
 fi
 
-`, name, name, name, name)
-	if err != nil {
-		return err
-	}
-	_, err = fmt.Fprintf(w, "# ex: ts=4 sw=4 et filetype=sh\n")
-	return err
+`, name, name, name, name))
+	buf.WriteString("# ex: ts=4 sw=4 et filetype=sh\n")
 }
 
-func writeCommands(cmd *Command, w io.Writer) error {
-	if _, err := fmt.Fprintf(w, "    commands=()\n"); err != nil {
-		return err
-	}
+func writeCommands(buf *bytes.Buffer, cmd *Command) {
+	buf.WriteString("    commands=()\n")
 	for _, c := range cmd.Commands() {
 		if !c.IsAvailableCommand() || c == cmd.helpCommand {
 			continue
 		}
-		if _, err := fmt.Fprintf(w, "    commands+=(%q)\n", c.Name()); err != nil {
-			return err
-		}
+		buf.WriteString(fmt.Sprintf("    commands+=(%q)\n", c.Name()))
 	}
-	_, err := fmt.Fprintf(w, "\n")
-	return err
+	buf.WriteString("\n")
 }
 
-func writeFlagHandler(name string, annotations map[string][]string, w io.Writer) error {
+func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]string) {
 	for key, value := range annotations {
 		switch key {
 		case BashCompFilenameExt:
-			_, err := fmt.Fprintf(w, "    flags_with_completion+=(%q)\n", name)
-			if err != nil {
-				return err
-			}
+			buf.WriteString(fmt.Sprintf("    flags_with_completion+=(%q)\n", name))
 
+			var ext string
 			if len(value) > 0 {
-				ext := "__handle_filename_extension_flag " + strings.Join(value, "|")
-				_, err = fmt.Fprintf(w, "    flags_completion+=(%q)\n", ext)
+				ext = "__handle_filename_extension_flag " + strings.Join(value, "|")
 			} else {
-				ext := "_filedir"
-				_, err = fmt.Fprintf(w, "    flags_completion+=(%q)\n", ext)
-			}
-			if err != nil {
-				return err
+				ext = "_filedir"
 			}
+			buf.WriteString(fmt.Sprintf("    flags_completion+=(%q)\n", ext))
 		case BashCompCustom:
-			_, err := fmt.Fprintf(w, "    flags_with_completion+=(%q)\n", name)
-			if err != nil {
-				return err
-			}
+			buf.WriteString(fmt.Sprintf("    flags_with_completion+=(%q)\n", name))
 			if len(value) > 0 {
 				handlers := strings.Join(value, "; ")
-				_, err = fmt.Fprintf(w, "    flags_completion+=(%q)\n", handlers)
+				buf.WriteString(fmt.Sprintf("    flags_completion+=(%q)\n", handlers))
 			} else {
-				_, err = fmt.Fprintf(w, "    flags_completion+=(:)\n")
-			}
-			if err != nil {
-				return err
+				buf.WriteString("    flags_completion+=(:)\n")
 			}
 		case BashCompSubdirsInDir:
-			_, err := fmt.Fprintf(w, "    flags_with_completion+=(%q)\n", name)
+			buf.WriteString(fmt.Sprintf("    flags_with_completion+=(%q)\n", name))
 
+			var ext string
 			if len(value) == 1 {
-				ext := "__handle_subdirs_in_dir_flag " + value[0]
-				_, err = fmt.Fprintf(w, "    flags_completion+=(%q)\n", ext)
+				ext = "__handle_subdirs_in_dir_flag " + value[0]
 			} else {
-				ext := "_filedir -d"
-				_, err = fmt.Fprintf(w, "    flags_completion+=(%q)\n", ext)
-			}
-			if err != nil {
-				return err
+				ext = "_filedir -d"
 			}
+			buf.WriteString(fmt.Sprintf("    flags_completion+=(%q)\n", ext))
 		}
 	}
-	return nil
 }
 
-func writeShortFlag(flag *pflag.Flag, w io.Writer) error {
-	b := (len(flag.NoOptDefVal) > 0)
+func writeShortFlag(buf *bytes.Buffer, flag *pflag.Flag) {
 	name := flag.Shorthand
 	format := "    "
-	if !b {
+	if len(flag.NoOptDefVal) == 0 {
 		format += "two_word_"
 	}
 	format += "flags+=(\"-%s\")\n"
-	if _, err := fmt.Fprintf(w, format, name); err != nil {
-		return err
-	}
-	return writeFlagHandler("-"+name, flag.Annotations, w)
+	buf.WriteString(fmt.Sprintf(format, name))
+	writeFlagHandler(buf, "-"+name, flag.Annotations)
 }
 
-func writeFlag(flag *pflag.Flag, w io.Writer) error {
-	b := (len(flag.NoOptDefVal) > 0)
+func writeFlag(buf *bytes.Buffer, flag *pflag.Flag) {
 	name := flag.Name
 	format := "    flags+=(\"--%s"
-	if !b {
+	if len(flag.NoOptDefVal) == 0 {
 		format += "="
 	}
 	format += "\")\n"
-	if _, err := fmt.Fprintf(w, format, name); err != nil {
-		return err
-	}
-	return writeFlagHandler("--"+name, flag.Annotations, w)
+	buf.WriteString(fmt.Sprintf(format, name))
+	writeFlagHandler(buf, "--"+name, flag.Annotations)
 }
 
-func writeLocalNonPersistentFlag(flag *pflag.Flag, w io.Writer) error {
-	b := (len(flag.NoOptDefVal) > 0)
+func writeLocalNonPersistentFlag(buf *bytes.Buffer, flag *pflag.Flag) {
 	name := flag.Name
 	format := "    local_nonpersistent_flags+=(\"--%s"
-	if !b {
+	if len(flag.NoOptDefVal) == 0 {
 		format += "="
 	}
 	format += "\")\n"
-	_, err := fmt.Fprintf(w, format, name)
-	return err
+	buf.WriteString(fmt.Sprintf(format, name))
 }
 
-func writeFlags(cmd *Command, w io.Writer) error {
-	_, err := fmt.Fprintf(w, `    flags=()
+func writeFlags(buf *bytes.Buffer, cmd *Command) {
+	buf.WriteString(`    flags=()
     two_word_flags=()
     local_nonpersistent_flags=()
     flags_with_completion=()
     flags_completion=()
 
 `)
-	if err != nil {
-		return err
-	}
 	localNonPersistentFlags := cmd.LocalNonPersistentFlags()
-	var visitErr error
 	cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
 		if nonCompletableFlag(flag) {
 			return
 		}
-		if err := writeFlag(flag, w); err != nil {
-			visitErr = err
-			return
-		}
+		writeFlag(buf, flag)
 		if len(flag.Shorthand) > 0 {
-			if err := writeShortFlag(flag, w); err != nil {
-				visitErr = err
-				return
-			}
+			writeShortFlag(buf, flag)
 		}
 		if localNonPersistentFlags.Lookup(flag.Name) != nil {
-			if err := writeLocalNonPersistentFlag(flag, w); err != nil {
-				visitErr = err
-				return
-			}
+			writeLocalNonPersistentFlag(buf, flag)
 		}
 	})
-	if visitErr != nil {
-		return visitErr
-	}
 	cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
 		if nonCompletableFlag(flag) {
 			return
 		}
-		if err := writeFlag(flag, w); err != nil {
-			visitErr = err
-			return
-		}
+		writeFlag(buf, flag)
 		if len(flag.Shorthand) > 0 {
-			if err := writeShortFlag(flag, w); err != nil {
-				visitErr = err
-				return
-			}
+			writeShortFlag(buf, flag)
 		}
 	})
-	if visitErr != nil {
-		return visitErr
-	}
 
-	_, err = fmt.Fprintf(w, "\n")
-	return err
+	buf.WriteString("\n")
 }
 
-func writeRequiredFlag(cmd *Command, w io.Writer) error {
-	if _, err := fmt.Fprintf(w, "    must_have_one_flag=()\n"); err != nil {
-		return err
-	}
+func writeRequiredFlag(buf *bytes.Buffer, cmd *Command) {
+	buf.WriteString("    must_have_one_flag=()\n")
 	flags := cmd.NonInheritedFlags()
-	var visitErr error
 	flags.VisitAll(func(flag *pflag.Flag) {
 		if nonCompletableFlag(flag) {
 			return
@@ -481,107 +409,68 @@ func writeRequiredFlag(cmd *Command, w io.Writer) error {
 			switch key {
 			case BashCompOneRequiredFlag:
 				format := "    must_have_one_flag+=(\"--%s"
-				b := (flag.Value.Type() == "bool")
-				if !b {
+				if flag.Value.Type() != "bool" {
 					format += "="
 				}
 				format += "\")\n"
-				if _, err := fmt.Fprintf(w, format, flag.Name); err != nil {
-					visitErr = err
-					return
-				}
+				buf.WriteString(fmt.Sprintf(format, flag.Name))
 
 				if len(flag.Shorthand) > 0 {
-					if _, err := fmt.Fprintf(w, "    must_have_one_flag+=(\"-%s\")\n", flag.Shorthand); err != nil {
-						visitErr = err
-						return
-					}
+					buf.WriteString(fmt.Sprintf("    must_have_one_flag+=(\"-%s\")\n", flag.Shorthand))
 				}
 			}
 		}
 	})
-	return visitErr
 }
 
-func writeRequiredNouns(cmd *Command, w io.Writer) error {
-	if _, err := fmt.Fprintf(w, "    must_have_one_noun=()\n"); err != nil {
-		return err
-	}
+func writeRequiredNouns(buf *bytes.Buffer, cmd *Command) {
+	buf.WriteString("    must_have_one_noun=()\n")
 	sort.Sort(sort.StringSlice(cmd.ValidArgs))
 	for _, value := range cmd.ValidArgs {
-		if _, err := fmt.Fprintf(w, "    must_have_one_noun+=(%q)\n", value); err != nil {
-			return err
-		}
+		buf.WriteString(fmt.Sprintf("    must_have_one_noun+=(%q)\n", value))
 	}
-	return nil
 }
 
-func writeArgAliases(cmd *Command, w io.Writer) error {
-	if _, err := fmt.Fprintf(w, "    noun_aliases=()\n"); err != nil {
-		return err
-	}
+func writeArgAliases(buf *bytes.Buffer, cmd *Command) {
+	buf.WriteString("    noun_aliases=()\n")
 	sort.Sort(sort.StringSlice(cmd.ArgAliases))
 	for _, value := range cmd.ArgAliases {
-		if _, err := fmt.Fprintf(w, "    noun_aliases+=(%q)\n", value); err != nil {
-			return err
-		}
+		buf.WriteString(fmt.Sprintf("    noun_aliases+=(%q)\n", value))
 	}
-	return nil
 }
 
-func gen(cmd *Command, w io.Writer) error {
+func gen(buf *bytes.Buffer, cmd *Command) {
 	for _, c := range cmd.Commands() {
 		if !c.IsAvailableCommand() || c == cmd.helpCommand {
 			continue
 		}
-		if err := gen(c, w); err != nil {
-			return err
-		}
+		gen(buf, c)
 	}
 	commandName := cmd.CommandPath()
 	commandName = strings.Replace(commandName, " ", "_", -1)
 	commandName = strings.Replace(commandName, ":", "__", -1)
-	if _, err := fmt.Fprintf(w, "_%s()\n{\n", commandName); err != nil {
-		return err
-	}
-	if _, err := fmt.Fprintf(w, "    last_command=%q\n", commandName); err != nil {
-		return err
-	}
-	if err := writeCommands(cmd, w); err != nil {
-		return err
-	}
-	if err := writeFlags(cmd, w); err != nil {
-		return err
-	}
-	if err := writeRequiredFlag(cmd, w); err != nil {
-		return err
-	}
-	if err := writeRequiredNouns(cmd, w); err != nil {
-		return err
-	}
-	if err := writeArgAliases(cmd, w); err != nil {
-		return err
-	}
-	if _, err := fmt.Fprintf(w, "}\n\n"); err != nil {
-		return err
-	}
-	return nil
+	buf.WriteString(fmt.Sprintf("_%s()\n{\n", commandName))
+	buf.WriteString(fmt.Sprintf("    last_command=%q\n", commandName))
+	writeCommands(buf, cmd)
+	writeFlags(buf, cmd)
+	writeRequiredFlag(buf, cmd)
+	writeRequiredNouns(buf, cmd)
+	writeArgAliases(buf, cmd)
+	buf.WriteString("}\n\n")
 }
 
 // GenBashCompletion generates bash completion file and writes to the passed writer.
 func (cmd *Command) GenBashCompletion(w io.Writer) error {
-	if err := preamble(w, cmd.Name()); err != nil {
-		return err
-	}
+	buf := new(bytes.Buffer)
+	writePreamble(buf, cmd.Name())
 	if len(cmd.BashCompletionFunction) > 0 {
-		if _, err := fmt.Fprintf(w, "%s\n", cmd.BashCompletionFunction); err != nil {
-			return err
-		}
+		buf.WriteString(cmd.BashCompletionFunction + "\n")
 	}
-	if err := gen(cmd, w); err != nil {
-		return err
-	}
-	return postscript(w, cmd.Name())
+	gen(buf, cmd)
+	writePostscript(buf, cmd.Name())
+
+	_, err := buf.WriteTo(w)
+	return err
 }
 
 func nonCompletableFlag(flag *pflag.Flag) bool {
diff --git a/bash_completions.md b/bash_completions.md
index 7fa970f..52bd39d 100644
--- a/bash_completions.md
+++ b/bash_completions.md
@@ -106,7 +106,7 @@ node                 pod                    replicationcontroller  service
 
 If your nouns have a number of aliases, you can define them alongside `ValidArgs` using `ArgAliases`:
 
-```go`
+```go
 argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }
 
 cmd := &cobra.Command{
diff --git a/cobra.go b/cobra.go
index b655768..2726d19 100644
--- a/cobra.go
+++ b/cobra.go
@@ -19,14 +19,21 @@ package cobra
 import (
 	"fmt"
 	"io"
+	"reflect"
+	"strconv"
 	"strings"
 	"text/template"
 	"unicode"
 )
 
 var templateFuncs = template.FuncMap{
-	"trimTrailingWhitespaces": trimTrailingWhitespaces,
-	"rpad": rpad,
+	"trim":                    strings.TrimSpace,
+	"trimRightSpace":          trimRightSpace,
+	"trimTrailingWhitespaces": trimRightSpace,
+	"appendIfNotPresent":      appendIfNotPresent,
+	"rpad":                    rpad,
+	"gt":                      Gt,
+	"eq":                      Eq,
 }
 
 var initializers []func()
@@ -59,10 +66,70 @@ func OnInitialize(y ...func()) {
 	initializers = append(initializers, y...)
 }
 
-func trimTrailingWhitespaces(s string) string {
+// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
+
+// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
+// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as
+// ints and then compared.
+func Gt(a interface{}, b interface{}) bool {
+	var left, right int64
+	av := reflect.ValueOf(a)
+
+	switch av.Kind() {
+	case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
+		left = int64(av.Len())
+	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+		left = av.Int()
+	case reflect.String:
+		left, _ = strconv.ParseInt(av.String(), 10, 64)
+	}
+
+	bv := reflect.ValueOf(b)
+
+	switch bv.Kind() {
+	case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
+		right = int64(bv.Len())
+	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+		right = bv.Int()
+	case reflect.String:
+		right, _ = strconv.ParseInt(bv.String(), 10, 64)
+	}
+
+	return left > right
+}
+
+// FIXME Eq is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
+
+// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
+func Eq(a interface{}, b interface{}) bool {
+	av := reflect.ValueOf(a)
+	bv := reflect.ValueOf(b)
+
+	switch av.Kind() {
+	case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
+		panic("Eq called on unsupported type")
+	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+		return av.Int() == bv.Int()
+	case reflect.String:
+		return av.String() == bv.String()
+	}
+	return false
+}
+
+func trimRightSpace(s string) string {
 	return strings.TrimRightFunc(s, unicode.IsSpace)
 }
 
+// FIXME appendIfNotPresent is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
+
+// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s.
+func appendIfNotPresent(s, stringToAppend string) string {
+	if strings.Contains(s, stringToAppend) {
+		return s
+	}
+	return s + " " + stringToAppend
+}
+
 // rpad adds padding to the right of a string.
 func rpad(s string, padding int) string {
 	template := fmt.Sprintf("%%-%ds", padding)
@@ -71,8 +138,10 @@ func rpad(s string, padding int) string {
 
 // tmpl executes the given template text on data, writing the result to w.
 func tmpl(w io.Writer, text string, data interface{}) error {
-	t := template.New("top").Funcs(templateFuncs)
-	return template.Must(t.Parse(text)).Execute(w, data)
+	t := template.New("top")
+	t.Funcs(templateFuncs)
+	template.Must(t.Parse(text))
+	return t.Execute(w, data)
 }
 
 // ld compares two strings and returns the levenshtein distance between them.
diff --git a/cobra/cmd/add.go b/cobra/cmd/add.go
index 20c6538..8897f8f 100644
--- a/cobra/cmd/add.go
+++ b/cobra/cmd/add.go
@@ -20,7 +20,6 @@ import (
 	"unicode"
 
 	"github.com/spf13/cobra"
-	"github.com/spf13/viper"
 )
 
 func init() {
@@ -117,7 +116,7 @@ func createCmdFile(license License, path, cmdName string) {
 	template := `{{comment .copyright}}
 {{comment .license}}
 
-package cmd
+package {{.cmdPackage}}
 
 import (
 	"fmt"
@@ -158,7 +157,7 @@ func init() {
 	data := make(map[string]interface{})
 	data["copyright"] = copyrightLine()
 	data["license"] = license.Header
-	data["viper"] = viper.GetBool("useViper")
+	data["cmdPackage"] = filepath.Base(filepath.Dir(path)) // last dir of path
 	data["parentName"] = parentName
 	data["cmdName"] = cmdName
 
diff --git a/cobra/cmd/helpers.go b/cobra/cmd/helpers.go
index fc9dd85..6114227 100644
--- a/cobra/cmd/helpers.go
+++ b/cobra/cmd/helpers.go
@@ -23,19 +23,16 @@ import (
 	"text/template"
 )
 
-var projectPath string
-
 var cmdDirs = [...]string{"cmd", "cmds", "command", "commands"}
 var srcPaths []string
 
 func init() {
-	// Initialize goPaths and srcPaths
+	// Initialize srcPaths.
 	envGoPath := os.Getenv("GOPATH")
-	if envGoPath == "" {
+	goPaths := filepath.SplitList(envGoPath)
+	if len(goPaths) == 0 {
 		er("$GOPATH is not set")
 	}
-
-	goPaths := filepath.SplitList(envGoPath)
 	srcPaths = make([]string, 0, len(goPaths))
 	for _, goPath := range goPaths {
 		srcPaths = append(srcPaths, filepath.Join(goPath, "src"))
@@ -83,11 +80,8 @@ func exists(path string) bool {
 	return false
 }
 
-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)
+	tmpl, err := template.New("").Funcs(template.FuncMap{"comment": commentifyString}).Parse(tmplStr)
 	if err != nil {
 		return "", err
 	}
diff --git a/cobra/cmd/init.go b/cobra/cmd/init.go
index 788bdb5..0e2b22a 100644
--- a/cobra/cmd/init.go
+++ b/cobra/cmd/init.go
@@ -197,13 +197,13 @@ func initConfig() {
 		// Find home directory.
 		home, err := homedir.Dir()
 		if err != nil {
-			fmt.Println(home)
+			fmt.Println(err)
 			os.Exit(1)
 		}
 
-		// Search config in home directory with name ".cobra" (without extension).
+		// Search config in home directory with name ".{{ .appName }}" (without extension).
 		viper.AddConfigPath(home)
-		viper.SetConfigName(".cobra")
+		viper.SetConfigName(".{{ .appName }}")
 	}
 
 	viper.AutomaticEnv() // read in environment variables that match
diff --git a/cobra/cmd/project.go b/cobra/cmd/project.go
index a3e6d91..de1168a 100644
--- a/cobra/cmd/project.go
+++ b/cobra/cmd/project.go
@@ -3,6 +3,7 @@ package cmd
 import (
 	"os"
 	"path/filepath"
+	"runtime"
 	"strings"
 )
 
@@ -37,7 +38,7 @@ func NewProject(projectName string) *Project {
 		}
 		for _, srcPath := range srcPaths {
 			goPath := filepath.Dir(srcPath)
-			if filepath.HasPrefix(wd, goPath) {
+			if filepathHasPrefix(wd, goPath) {
 				p.absPath = filepath.Join(srcPath, projectName)
 				break
 			}
@@ -90,7 +91,7 @@ func NewProjectFromPath(absPath string) *Project {
 func trimSrcPath(absPath, srcPath string) string {
 	relPath, err := filepath.Rel(srcPath, absPath)
 	if err != nil {
-		er("Cobra supports project only within $GOPATH")
+		er("Cobra supports project only within $GOPATH: " + err.Error())
 	}
 	return relPath
 }
@@ -172,7 +173,7 @@ func (p *Project) SrcPath() string {
 	}
 
 	for _, srcPath := range srcPaths {
-		if strings.HasPrefix(p.absPath, srcPath) {
+		if filepathHasPrefix(p.absPath, srcPath) {
 			p.srcPath = srcPath
 			break
 		}
@@ -180,3 +181,15 @@ func (p *Project) SrcPath() string {
 
 	return p.srcPath
 }
+
+func filepathHasPrefix(path string, prefix string) bool {
+	if len(path) <= len(prefix) {
+		return false
+	}
+	if runtime.GOOS == "windows" {
+		// Paths in windows are case-insensitive.
+		return strings.EqualFold(path[0:len(prefix)], prefix)
+	}
+	return path[0:len(prefix)] == prefix
+
+}
diff --git a/cobra/cmd/root.go b/cobra/cmd/root.go
index 967eecc..cfc7852 100644
--- a/cobra/cmd/root.go
+++ b/cobra/cmd/root.go
@@ -15,46 +15,48 @@ package cmd
 
 import (
 	"fmt"
-	"os"
 
 	homedir "github.com/mitchellh/go-homedir"
 	"github.com/spf13/cobra"
 	"github.com/spf13/viper"
 )
 
-var cfgFile, projectBase, userLicense string // are used for flags
+var (
+	// Used for flags.
+	cfgFile, projectBase, userLicense string
 
-var RootCmd = &cobra.Command{
-	Use:   "cobra",
-	Short: "A generator for Cobra based Applications",
-	Long: `Cobra is a CLI library for Go that empowers applications.
+	rootCmd = &cobra.Command{
+		Use:   "cobra",
+		Short: "A generator for Cobra based Applications",
+		Long: `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.`,
-}
+	}
+)
 
+// Execute executes the root command.
 func Execute() {
-	if err := RootCmd.Execute(); err != nil {
-		fmt.Println(err)
-		os.Exit(1)
+	if err := rootCmd.Execute(); err != nil {
+		er(err)
 	}
 }
 
 func init() {
 	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")
-	RootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `license` in config)")
-	RootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration")
-	viper.BindPFlag("author", RootCmd.PersistentFlags().Lookup("author"))
-	viper.BindPFlag("projectbase", RootCmd.PersistentFlags().Lookup("projectbase"))
-	viper.BindPFlag("useViper", RootCmd.PersistentFlags().Lookup("viper"))
+	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")
+	rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `license` in config)")
+	rootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration")
+	viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
+	viper.BindPFlag("projectbase", rootCmd.PersistentFlags().Lookup("projectbase"))
+	viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
 	viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
 	viper.SetDefault("license", "apache")
 
-	RootCmd.AddCommand(initCmd)
-	RootCmd.AddCommand(addCmd)
+	rootCmd.AddCommand(initCmd)
+	rootCmd.AddCommand(addCmd)
 
 }
 
@@ -66,8 +68,7 @@ func initViper() {
 		// Find home directory.
 		home, err := homedir.Dir()
 		if err != nil {
-			fmt.Println(home)
-			os.Exit(1)
+			er(err)
 		}
 
 		// Search config in home directory with name ".cobra" (without extension).
diff --git a/command.go b/command.go
index 5a81860..f37667f 100644
--- a/command.go
+++ b/command.go
@@ -28,113 +28,147 @@ import (
 )
 
 // Command is just that, a command for your application.
-// eg.  'go run' ... 'run' is the command. Cobra requires
+// E.g.  'go run ...' - 'run' is the command. Cobra requires
 // you to define the usage and description as part of your command
 // definition to ensure usability.
 type Command struct {
-	// Name is the command name, usually the executable's name.
-	name string
-	// The one-line usage message.
+	// Use is the one-line usage message.
 	Use string
-	// An array of aliases that can be used instead of the first word in Use.
+
+	// Aliases is an array of aliases that can be used instead of the first word in Use.
 	Aliases []string
-	// An array of command names for which this command will be suggested - similar to aliases but only suggests.
+
+	// SuggestFor is an array of command names for which this command will be suggested -
+	// similar to aliases but only suggests.
 	SuggestFor []string
-	// The short description shown in the 'help' output.
+
+	// Short is the short description shown in the 'help' output.
 	Short string
-	// The long message shown in the 'help <this-command>' output.
+
+	// Long is the long message shown in the 'help <this-command>' output.
 	Long string
-	// Examples of how to use the command
+
+	// Example is examples of how to use the command.
 	Example string
-	// List of all valid non-flag arguments that are accepted in bash completions
+
+	// ValidArgs is list of all valid non-flag arguments that are accepted in bash completions
 	ValidArgs []string
-	// List of aliases for ValidArgs. These are not suggested to the user in the bash
-	// completion, but accepted if entered manually.
+
+	// ArgAliases is List of aliases for ValidArgs.
+	// These are not suggested to the user in the bash completion,
+	// but accepted if entered manually.
 	ArgAliases []string
-	// Custom functions used by the bash autocompletion generator
+
+	// BashCompletionFunction is custom functions used by the bash autocompletion generator.
 	BashCompletionFunction string
-	// Is this command deprecated and should print this string when used?
+
+	// Deprecated defines, if this command is deprecated and should print this string when used.
 	Deprecated string
-	// Is this command hidden and should NOT show up in the list of available commands?
+
+	// Hidden defines, if this command is hidden and should NOT show up in the list of available commands.
 	Hidden bool
+
 	// Annotations are key/value pairs that can be used by applications to identify or
-	// group commands
+	// group commands.
 	Annotations map[string]string
-	// Full set of flags
-	flags *flag.FlagSet
-	// Set of flags childrens of this command will inherit
-	pflags *flag.FlagSet
-	// Flags that are declared specifically by this command (not inherited).
-	lflags *flag.FlagSet
-	// Inherited flags.
-	iflags *flag.FlagSet
-	// All persistent flags of cmd's parents.
-	parentsPflags *flag.FlagSet
-	// SilenceErrors is an option to quiet errors down stream
-	SilenceErrors bool
-	// Silence Usage is an option to silence usage when an error occurs.
-	SilenceUsage bool
+
 	// The *Run functions are executed in the following order:
 	//   * PersistentPreRun()
 	//   * PreRun()
 	//   * Run()
 	//   * PostRun()
 	//   * PersistentPostRun()
-	// All functions get the same args, the arguments after the command name
-	// PersistentPreRun: children of this command will inherit and execute
+	// All functions get the same args, the arguments after the command name.
+	//
+	// PersistentPreRun: children of this command will inherit and execute.
 	PersistentPreRun func(cmd *Command, args []string)
-	// PersistentPreRunE: PersistentPreRun but returns an error
+	// PersistentPreRunE: PersistentPreRun but returns an error.
 	PersistentPreRunE func(cmd *Command, args []string) error
 	// PreRun: children of this command will not inherit.
 	PreRun func(cmd *Command, args []string)
-	// PreRunE: PreRun but returns an error
+	// PreRunE: PreRun but returns an error.
 	PreRunE func(cmd *Command, args []string) error
-	// Run: Typically the actual work function. Most commands will only implement this
+	// Run: Typically the actual work function. Most commands will only implement this.
 	Run func(cmd *Command, args []string)
-	// RunE: Run but returns an error
+	// RunE: Run but returns an error.
 	RunE func(cmd *Command, args []string) error
 	// PostRun: run after the Run command.
 	PostRun func(cmd *Command, args []string)
-	// PostRunE: PostRun but returns an error
+	// PostRunE: PostRun but returns an error.
 	PostRunE func(cmd *Command, args []string) error
-	// PersistentPostRun: children of this command will inherit and execute after PostRun
+	// PersistentPostRun: children of this command will inherit and execute after PostRun.
 	PersistentPostRun func(cmd *Command, args []string)
-	// PersistentPostRunE: PersistentPostRun but returns an error
+	// PersistentPostRunE: PersistentPostRun but returns an error.
 	PersistentPostRunE func(cmd *Command, args []string) error
-	// DisableAutoGenTag remove
+
+	// SilenceErrors is an option to quiet errors down stream.
+	SilenceErrors bool
+
+	// SilenceUsage is an option to silence usage when an error occurs.
+	SilenceUsage bool
+
+	// DisableFlagParsing disables the flag parsing.
+	// If this is true all flags will be passed to the command as arguments.
+	DisableFlagParsing bool
+
+	// DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")
+	// will be printed by generating docs for this command.
 	DisableAutoGenTag bool
-	// Commands is the list of commands supported by this program.
+
+	// DisableSuggestions disables the suggestions based on Levenshtein distance
+	// that go along with 'unknown command' messages.
+	DisableSuggestions bool
+	// SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.
+	// Must be > 0.
+	SuggestionsMinimumDistance int
+
+	// name is the command name, usually the executable's name.
+	name string
+	// commands is the list of commands supported by this program.
 	commands []*Command
-	// Parent Command for this command
+	// parent is a parent command for this command.
 	parent *Command
-	// max lengths of commands' string lengths for use in padding
+	// Max lengths of commands' string lengths for use in padding.
 	commandsMaxUseLen         int
 	commandsMaxCommandPathLen int
 	commandsMaxNameLen        int
-	// is commands slice are sorted or not
+	// commandsAreSorted defines, if command slice are sorted or not.
 	commandsAreSorted bool
 
+	// args is actual args parsed from flags.
+	args []string
 	// 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
-	usageTemplate string               // Can be defined by Application
-	flagErrorFunc func(*Command, error) error
-	helpTemplate  string                   // Can be defined by Application
-	helpFunc      func(*Command, []string) // Help can be defined by application
-	helpCommand   *Command                 // The help command
-	// The global normalization function that we can use on every pFlag set and children commands
+	// flags is full set of flags.
+	flags *flag.FlagSet
+	// pflags contains persistent flags.
+	pflags *flag.FlagSet
+	// lflags contains local flags.
+	lflags *flag.FlagSet
+	// iflags contains inherited flags.
+	iflags *flag.FlagSet
+	// parentsPflags is all persistent flags of cmd's parents.
+	parentsPflags *flag.FlagSet
+	// globNormFunc is the global normalization function
+	// that we can use on every pflag set and children commands
 	globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName
 
-	// Disable the suggestions based on Levenshtein distance that go along with 'unknown command' messages
-	DisableSuggestions bool
-	// If displaying suggestions, allows to set the minimum levenshtein distance to display, must be > 0
-	SuggestionsMinimumDistance int
-
-	// Disable the flag parsing. If this is true all flags will be passed to the command as arguments.
-	DisableFlagParsing bool
+	// output is an output writer defined by user.
+	output io.Writer
+	// usageFunc is usage func defined by user.
+	usageFunc func(*Command) error
+	// usageTemplate is usage template defined by user.
+	usageTemplate string
+	// flagErrorFunc is func defined by user and it's called when the parsing of
+	// flags returns an error.
+	flagErrorFunc func(*Command, error) error
+	// helpTemplate is help template defined by user.
+	helpTemplate string
+	// helpFunc is help func defined by user.
+	helpFunc func(*Command, []string)
+	// helpCommand is command with usage 'help'. If it's not defined by user,
+	// cobra uses default help command.
+	helpCommand *Command
 }
 
 // SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden
@@ -396,37 +430,28 @@ func stripFlags(args []string, c *Command) []string {
 	c.mergePersistentFlags()
 
 	commands := []string{}
-	inQuote := false
 	flags := c.Flags()
 
 Loop:
 	for len(args) > 0 {
 		s := args[0]
 		args = args[1:]
-		if !inQuote {
-			switch {
-			case strings.HasPrefix(s, "\"") || strings.Contains(s, "=\""):
-				inQuote = true
-			case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
-				// If '--flag arg' then
-				// delete arg from args.
-				fallthrough // (do the same as below)
-			case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):
-				// If '-f arg' then
-				// delete 'arg' from args or break the loop if len(args) <= 1.
-				if len(args) <= 1 {
-					break Loop
-				} else {
-					args = args[1:]
-					continue
-				}
-			case s != "" && !strings.HasPrefix(s, "-"):
-				commands = append(commands, s)
+		switch {
+		case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
+			// If '--flag arg' then
+			// delete arg from args.
+			fallthrough // (do the same as below)
+		case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):
+			// If '-f arg' then
+			// delete 'arg' from args or break the loop if len(args) <= 1.
+			if len(args) <= 1 {
+				break Loop
+			} else {
+				args = args[1:]
+				continue
 			}
-		}
-
-		if strings.HasSuffix(s, "\"") && !strings.HasSuffix(s, "\\\"") {
-			inQuote = false
+		case s != "" && !strings.HasPrefix(s, "-"):
+			commands = append(commands, s)
 		}
 	}
 
@@ -675,7 +700,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
 
 	// initialize help as the last point possible to allow for user
 	// overriding
-	c.initHelpCmd()
+	c.InitDefaultHelpCmd()
 
 	var args []string
 
@@ -739,31 +764,32 @@ func (c *Command) InitDefaultHelpFlag() {
 	}
 }
 
-func (c *Command) initHelpCmd() {
-	if c.helpCommand == nil {
-		if !c.HasSubCommands() {
-			return
-		}
+// InitDefaultHelpCmd adds default help command to c.
+// It is called automatically by executing the c or by calling help and usage.
+// If c already has help command or c has no subcommands, it will do nothing.
+func (c *Command) InitDefaultHelpCmd() {
+	if c.helpCommand != nil || !c.HasSubCommands() {
+		return
+	}
 
-		c.helpCommand = &Command{
-			Use:   "help [command]",
-			Short: "Help about any command",
-			Long: `Help provides help for any command in the application.
+	c.helpCommand = &Command{
+		Use:   "help [command]",
+		Short: "Help about any command",
+		Long: `Help provides help for any command in the application.
     Simply type ` + c.Name() + ` help [path to command] for full details.`,
-			PersistentPreRun:  func(cmd *Command, args []string) {},
-			PersistentPostRun: func(cmd *Command, args []string) {},
-
-			Run: func(c *Command, args []string) {
-				cmd, _, e := c.Root().Find(args)
-				if cmd == nil || e != nil {
-					c.Printf("Unknown help topic %#q\n", args)
-					c.Root().Usage()
-				} else {
-					cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
-					cmd.Help()
-				}
-			},
-		}
+		PersistentPreRun:  func(cmd *Command, args []string) {},
+		PersistentPostRun: func(cmd *Command, args []string) {},
+
+		Run: func(c *Command, args []string) {
+			cmd, _, e := c.Root().Find(args)
+			if cmd == nil || e != nil {
+				c.Printf("Unknown help topic %#q\n", args)
+				c.Root().Usage()
+			} else {
+				cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
+				cmd.Help()
+			}
+		},
 	}
 	c.RemoveCommand(c.helpCommand)
 	c.AddCommand(c.helpCommand)
@@ -1241,8 +1267,8 @@ func (c *Command) Parent() *Command {
 // mergePersistentFlags merges c.PersistentFlags() to c.Flags()
 // and adds missing persistent flags of all parents.
 func (c *Command) mergePersistentFlags() {
-	c.Flags().AddFlagSet(c.PersistentFlags())
 	c.updateParentsPflags()
+	c.Flags().AddFlagSet(c.PersistentFlags())
 	c.Flags().AddFlagSet(c.parentsPflags)
 }
 
diff --git a/doc/man_docs.go b/doc/man_docs.go
index 68513cf..74b284d 100644
--- a/doc/man_docs.go
+++ b/doc/man_docs.go
@@ -77,6 +77,8 @@ func GenManTreeFromOpts(cmd *cobra.Command, opts GenManTreeOptions) error {
 	return GenMan(cmd, &headerCopy, f)
 }
 
+// GenManTreeOptions is the options for generating the man pages.
+// Used only in GenManTreeFromOpts.
 type GenManTreeOptions struct {
 	Header           *GenManHeader
 	Path             string
diff --git a/doc/md_docs.go b/doc/md_docs.go
index 21ab922..9bbfa36 100644
--- a/doc/md_docs.go
+++ b/doc/md_docs.go
@@ -126,6 +126,8 @@ func GenMarkdownTree(cmd *cobra.Command, dir string) error {
 	return GenMarkdownTreeCustom(cmd, dir, emptyStr, identity)
 }
 
+// GenMarkdownTreeCustom is the the same as GenMarkdownTree, but
+// with custom filePrepender and linkHandler.
 func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {
 	for _, c := range cmd.Commands() {
 		if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {


Test patch:
diff --git a/bash_completions_test.go b/bash_completions_test.go
index 185570b..a626360 100644
--- a/bash_completions_test.go
+++ b/bash_completions_test.go
@@ -2,16 +2,13 @@ package cobra
 
 import (
 	"bytes"
-	"fmt"
+	"io/ioutil"
 	"os"
 	"os/exec"
 	"strings"
 	"testing"
 )
 
-var _ = fmt.Println
-var _ = os.Stderr
-
 func checkOmit(t *testing.T, found, unexpected string) {
 	if strings.Contains(found, unexpected) {
 		t.Errorf("Unexpected response.\nGot: %q\nBut should not have!\n", unexpected)
@@ -178,3 +175,22 @@ func TestBashCompletionDeprecatedFlag(t *testing.T) {
 		t.Errorf("expected completion to not include %q flag: Got %v", flagName, bashCompletion)
 	}
 }
+
+func BenchmarkBashCompletion(b *testing.B) {
+	c := initializeWithRootCmd()
+	cmdEcho.AddCommand(cmdTimes)
+	c.AddCommand(cmdEcho, cmdPrint, cmdDeprecated, cmdColon)
+
+	file, err := ioutil.TempFile("", "")
+	if err != nil {
+		b.Fatal(err)
+	}
+	defer os.Remove(file.Name())
+
+	b.ResetTimer()
+	for i := 0; i < b.N; i++ {
+		if err := c.GenBashCompletion(file); err != nil {
+			b.Fatal(err)
+		}
+	}
+}
diff --git a/cobra/cmd/init_test.go b/cobra/cmd/init_test.go
index f97be30..9a918b9 100644
--- a/cobra/cmd/init_test.go
+++ b/cobra/cmd/init_test.go
@@ -18,7 +18,7 @@ func TestGoldenInitCmd(t *testing.T) {
 	defer os.RemoveAll(project.AbsPath())
 
 	os.Args = []string{"cobra", "init", projectName}
-	if err := RootCmd.Execute(); err != nil {
+	if err := rootCmd.Execute(); err != nil {
 		t.Fatal("Error by execution:", err)
 	}
 
@@ -54,7 +54,9 @@ func TestGoldenInitCmd(t *testing.T) {
 				if err != nil {
 					return err
 				}
-				ioutil.WriteFile(goldenPath, got, 0644)
+				if err := ioutil.WriteFile(goldenPath, got, 0644); err != nil {
+					t.Fatal("Error while updating file:", err)
+				}
 			}
 			return compareFiles(path, goldenPath)
 		}
diff --git a/cobra/cmd/project_test.go b/cobra/cmd/project_test.go
index 2774094..037f7c5 100644
--- a/cobra/cmd/project_test.go
+++ b/cobra/cmd/project_test.go
@@ -1,7 +1,6 @@
 package cmd
 
 import (
-	"path/filepath"
 	"testing"
 )
 
@@ -17,7 +16,7 @@ func TestFindExistingPackage(t *testing.T) {
 
 func hasGoPathPrefix(path string) bool {
 	for _, srcPath := range srcPaths {
-		if filepath.HasPrefix(path, srcPath) {
+		if filepathHasPrefix(path, srcPath) {
 			return true
 		}
 	}
diff --git a/cobra/cmd/testdata/root.go.golden b/cobra/cmd/testdata/root.go.golden
index a8f4ff1..13e9a77 100644
--- a/cobra/cmd/testdata/root.go.golden
+++ b/cobra/cmd/testdata/root.go.golden
@@ -70,13 +70,13 @@ func initConfig() {
 		// Find home directory.
 		home, err := homedir.Dir()
 		if err != nil {
-			fmt.Println(home)
+			fmt.Println(err)
 			os.Exit(1)
 		}
 
-		// Search config in home directory with name ".cobra" (without extension).
+		// Search config in home directory with name ".testproject" (without extension).
 		viper.AddConfigPath(home)
-		viper.SetConfigName(".cobra")
+		viper.SetConfigName(".testproject")
 	}
 
 	viper.AutomaticEnv() // read in environment variables that match
diff --git a/cobra_test.go b/cobra_test.go
index 6f3ceb1..576c97d 100644
--- a/cobra_test.go
+++ b/cobra_test.go
@@ -13,13 +13,12 @@ import (
 	"github.com/spf13/pflag"
 )
 
-var tp, te, tt, t1, tr []string
+var tp, te, tt, tr []string
 var rootPersPre, echoPre, echoPersPre, timesPersPre []string
 var flagb1, flagb2, flagb3, flagbr, flagbp bool
 var flags1, flags2a, flags2b, flags3, outs string
 var flagi1, flagi2, flagi3, flagi4, flagir int
-var globalFlag1 bool
-var flagEcho, rootcalled bool
+var rootcalled bool
 var versionUsed int
 
 const strtwoParentHelp = "help message for parent flag strtwo"
@@ -227,36 +226,36 @@ type resulter struct {
 	Command *Command
 }
 
-func fullSetupTest(input string) resulter {
+func fullSetupTest(args ...string) resulter {
 	c := initializeWithRootCmd()
 
-	return fullTester(c, input)
+	return fullTester(c, args...)
 }
 
-func noRRSetupTestSilenced(input string) resulter {
+func noRRSetupTestSilenced(args ...string) resulter {
 	c := initialize()
 	c.SilenceErrors = true
 	c.SilenceUsage = true
-	return fullTester(c, input)
+	return fullTester(c, args...)
 }
 
-func noRRSetupTest(input string) resulter {
+func noRRSetupTest(args ...string) resulter {
 	c := initialize()
 
-	return fullTester(c, input)
+	return fullTester(c, args...)
 }
 
-func rootOnlySetupTest(input string) resulter {
+func rootOnlySetupTest(args ...string) resulter {
 	c := initializeWithRootCmd()
 
-	return simpleTester(c, input)
+	return simpleTester(c, args...)
 }
 
-func simpleTester(c *Command, input string) resulter {
+func simpleTester(c *Command, args ...string) resulter {
 	buf := new(bytes.Buffer)
 	// Testing flag with invalid input
 	c.SetOutput(buf)
-	c.SetArgs(strings.Split(input, " "))
+	c.SetArgs(args)
 
 	err := c.Execute()
 	output := buf.String()
@@ -264,11 +263,11 @@ func simpleTester(c *Command, input string) resulter {
 	return resulter{err, output, c}
 }
 
-func simpleTesterC(c *Command, input string) resulter {
+func simpleTesterC(c *Command, args ...string) resulter {
 	buf := new(bytes.Buffer)
 	// Testing flag with invalid input
 	c.SetOutput(buf)
-	c.SetArgs(strings.Split(input, " "))
+	c.SetArgs(args)
 
 	cmd, err := c.ExecuteC()
 	output := buf.String()
@@ -276,13 +275,13 @@ func simpleTesterC(c *Command, input string) resulter {
 	return resulter{err, output, cmd}
 }
 
-func fullTester(c *Command, input string) resulter {
+func fullTester(c *Command, args ...string) resulter {
 	buf := new(bytes.Buffer)
 	// Testing flag with invalid input
 	c.SetOutput(buf)
 	cmdEcho.AddCommand(cmdTimes)
 	c.AddCommand(cmdPrint, cmdEcho, cmdSubNoRun, cmdCustomFlags, cmdDeprecated)
-	c.SetArgs(strings.Split(input, " "))
+	c.SetArgs(args)
 
 	err := c.Execute()
 	output := buf.String()
@@ -332,7 +331,7 @@ func checkOutputContains(t *testing.T, c *Command, check string) {
 }
 
 func TestSingleCommand(t *testing.T) {
-	noRRSetupTest("print one two")
+	noRRSetupTest("print", "one", "two")
 
 	if te != nil || tt != nil {
 		t.Error("Wrong command called")
@@ -346,7 +345,7 @@ func TestSingleCommand(t *testing.T) {
 }
 
 func TestChildCommand(t *testing.T) {
-	noRRSetupTest("echo times one two")
+	noRRSetupTest("echo", "times", "one", "two")
 
 	if te != nil || tp != nil {
 		t.Error("Wrong command called")
@@ -360,7 +359,7 @@ func TestChildCommand(t *testing.T) {
 }
 
 func TestCommandAlias(t *testing.T) {
-	noRRSetupTest("say times one two")
+	noRRSetupTest("say", "times", "one", "two")
 
 	if te != nil || tp != nil {
 		t.Error("Wrong command called")
@@ -375,7 +374,7 @@ func TestCommandAlias(t *testing.T) {
 
 func TestPrefixMatching(t *testing.T) {
 	EnablePrefixMatching = true
-	noRRSetupTest("ech times one two")
+	noRRSetupTest("ech", "times", "one", "two")
 
 	if te != nil || tp != nil {
 		t.Error("Wrong command called")
@@ -393,7 +392,7 @@ func TestPrefixMatching(t *testing.T) {
 func TestNoPrefixMatching(t *testing.T) {
 	EnablePrefixMatching = false
 
-	noRRSetupTest("ech times one two")
+	noRRSetupTest("ech", "times", "one", "two")
 
 	if !(tt == nil && te == nil && tp == nil) {
 		t.Error("Wrong command called")
@@ -402,7 +401,7 @@ func TestNoPrefixMatching(t *testing.T) {
 
 func TestAliasPrefixMatching(t *testing.T) {
 	EnablePrefixMatching = true
-	noRRSetupTest("sa times one two")
+	noRRSetupTest("sa", "times", "one", "two")
 
 	if te != nil || tp != nil {
 		t.Error("Wrong command called")
@@ -419,7 +418,7 @@ func TestAliasPrefixMatching(t *testing.T) {
 func TestChildSameName(t *testing.T) {
 	c := initializeWithSameName()
 	c.AddCommand(cmdPrint, cmdEcho)
-	c.SetArgs(strings.Split("print one two", " "))
+	c.SetArgs([]string{"print", "one", "two"})
 	c.Execute()
 
 	if te != nil || tt != nil {
@@ -437,7 +436,7 @@ func TestGrandChildSameName(t *testing.T) {
 	c := initializeWithSameName()
 	cmdTimes.AddCommand(cmdPrint)
 	c.AddCommand(cmdTimes)
-	c.SetArgs(strings.Split("times print one two", " "))
+	c.SetArgs([]string{"times", "print", "one", "two"})
 	c.Execute()
 
 	if te != nil || tt != nil {
@@ -454,13 +453,13 @@ func TestGrandChildSameName(t *testing.T) {
 func TestUsage(t *testing.T) {
 	x := fullSetupTest("help")
 	checkResultContains(t, x, cmdRootWithRun.Use+" [flags]")
-	x = fullSetupTest("help customflags")
+	x = fullSetupTest("help", "customflags")
 	checkResultContains(t, x, cmdCustomFlags.Use)
 	checkResultOmits(t, x, cmdCustomFlags.Use+" [flags]")
 }
 
 func TestFlagLong(t *testing.T) {
-	noRRSetupTest("echo --intone=13 something -- here")
+	noRRSetupTest("echo", "--intone=13", "something", "--", "here")
 
 	if cmdEcho.ArgsLenAtDash() != 1 {
 		t.Errorf("expected argsLenAtDash: %d but got %d", 1, cmdRootNoRun.ArgsLenAtDash())
@@ -477,7 +476,7 @@ func TestFlagLong(t *testing.T) {
 }
 
 func TestFlagShort(t *testing.T) {
-	noRRSetupTest("echo -i13 -- something here")
+	noRRSetupTest("echo", "-i13", "--", "something", "here")
 
 	if cmdEcho.ArgsLenAtDash() != 0 {
 		t.Errorf("expected argsLenAtDash: %d but got %d", 0, cmdRootNoRun.ArgsLenAtDash())
@@ -492,7 +491,7 @@ func TestFlagShort(t *testing.T) {
 		t.Errorf("default flag value changed, 234 expected, %d given", flagi2)
 	}
 
-	noRRSetupTest("echo -i 13 something here")
+	noRRSetupTest("echo", "-i", "13", "something", "here")
 
 	if strings.Join(te, " ") != "something here" {
 		t.Errorf("flags didn't leave proper args remaining..%s given", te)
@@ -504,7 +503,7 @@ func TestFlagShort(t *testing.T) {
 		t.Errorf("default flag value changed, 234 expected, %d given", flagi2)
 	}
 
-	noRRSetupTest("print -i99 one two")
+	noRRSetupTest("print", "-i99", "one", "two")
 
 	if strings.Join(tp, " ") != "one two" {
 		t.Errorf("flags didn't leave proper args remaining..%s given", tp)
@@ -518,14 +517,14 @@ func TestFlagShort(t *testing.T) {
 }
 
 func TestChildCommandFlags(t *testing.T) {
-	noRRSetupTest("echo times -j 99 one two")
+	noRRSetupTest("echo", "times", "-j", "99", "one", "two")
 
 	if strings.Join(tt, " ") != "one two" {
 		t.Errorf("flags didn't leave proper args remaining..%s given", tt)
 	}
 
 	// Testing with flag that shouldn't be persistent
-	r := noRRSetupTest("echo times -j 99 -i77 one two")
+	r := noRRSetupTest("echo", "times", "-j", "99", "-i77", "one", "two")
 
 	if r.Error == nil {
 		t.Errorf("invalid flag should generate error")
@@ -544,7 +543,7 @@ func TestChildCommandFlags(t *testing.T) {
 	}
 
 	// Testing with flag only existing on child
-	r = noRRSetupTest("echo -j 99 -i77 one two")
+	r = noRRSetupTest("echo", "-j", "99", "-i77", "one", "two")
 
 	if r.Error == nil {
 		t.Errorf("invalid flag should generate error")
@@ -554,7 +553,7 @@ func TestChildCommandFlags(t *testing.T) {
 	}
 
 	// Testing with persistent flag overwritten by child
-	noRRSetupTest("echo times --strtwo=child one two")
+	noRRSetupTest("echo", "times", "--strtwo=child", "one", "two")
 
 	if flags2b != "child" {
 		t.Errorf("flag value should be child, %s given", flags2b)
@@ -565,7 +564,7 @@ func TestChildCommandFlags(t *testing.T) {
 	}
 
 	// Testing flag with invalid input
-	r = noRRSetupTest("echo -i10E")
+	r = noRRSetupTest("echo", "-i10E")
 
 	if r.Error == nil {
 		t.Errorf("invalid input should generate error")
@@ -576,7 +575,7 @@ func TestChildCommandFlags(t *testing.T) {
 }
 
 func TestTrailingCommandFlags(t *testing.T) {
-	x := fullSetupTest("echo two -x")
+	x := fullSetupTest("echo", "two", "-x")
 
 	if x.Error == nil {
 		t.Errorf("invalid flag should generate error")
@@ -587,7 +586,7 @@ func TestInvalidSubcommandFlags(t *testing.T) {
 	cmd := initializeWithRootCmd()
 	cmd.AddCommand(cmdTimes)
 
-	result := simpleTester(cmd, "times --inttwo=2 --badflag=bar")
+	result := simpleTester(cmd, "times", "--inttwo=2", "--badflag=bar")
 	// given that we are not checking here result.Error we check for
 	// stock usage message
 	checkResultContains(t, result, "cobra-test times [# times]")
@@ -617,14 +616,14 @@ func TestSubcommandExecuteC(t *testing.T) {
 
 	cmd.AddCommand(double, echo)
 
-	result := simpleTesterC(cmd, "double hello world")
+	result := simpleTesterC(cmd, "double", "hello", "world")
 	checkResultContains(t, result, "hello world hello world")
 
 	if result.Command.Name() != "double" {
 		t.Errorf("invalid cmd returned from ExecuteC: should be 'double' but got %s", result.Command.Name())
 	}
 
-	result = simpleTesterC(cmd, "echo msg to be echoed")
+	result = simpleTesterC(cmd, "echo", "msg", "to", "be", "echoed")
 	checkResultContains(t, result, "msg to be echoed")
 
 	if result.Command.Name() != "echo" {
@@ -650,16 +649,16 @@ func TestSubcommandArgEvaluation(t *testing.T) {
 	}
 	first.AddCommand(second)
 
-	result := simpleTester(cmd, "first second first third")
+	result := simpleTester(cmd, "first", "second", "first", "third")
 
-	expectedOutput := fmt.Sprintf("%v", []string{"first third"})
+	expectedOutput := fmt.Sprint([]string{"first third"})
 	if result.Output != expectedOutput {
 		t.Errorf("exptected %v, got %v", expectedOutput, result.Output)
 	}
 }
 
 func TestPersistentFlags(t *testing.T) {
-	fullSetupTest("echo -s something -p more here")
+	fullSetupTest("echo", "-s", "something", "-p", "more", "here")
 
 	// persistentFlag should act like normal flag on its own command
 	if strings.Join(te, " ") != "more here" {
@@ -673,7 +672,7 @@ func TestPersistentFlags(t *testing.T) {
 	}
 
 	// persistentFlag should act like normal flag on its own command
-	fullSetupTest("echo times -s again -c -p test here")
+	fullSetupTest("echo", "times", "-s", "again", "-c", "-p", "test", "here")
 
 	if strings.Join(tt, " ") != "test here" {
 		t.Errorf("flags didn't leave proper args remaining. %s given", tt)
@@ -695,17 +694,17 @@ func TestHelpCommand(t *testing.T) {
 	x := fullSetupTest("help")
 	checkResultContains(t, x, cmdRootWithRun.Long)
 
-	x = fullSetupTest("help echo")
+	x = fullSetupTest("help", "echo")
 	checkResultContains(t, x, cmdEcho.Long)
 
-	x = fullSetupTest("help echo times")
+	x = fullSetupTest("help", "echo", "times")
 	checkResultContains(t, x, cmdTimes.Long)
 }
 
 func TestChildCommandHelp(t *testing.T) {
-	c := noRRSetupTest("print --help")
+	c := noRRSetupTest("print", "--help")
 	checkResultContains(t, c, strtwoParentHelp)
-	r := noRRSetupTest("echo times --help")
+	r := noRRSetupTest("echo", "times", "--help")
 	checkResultContains(t, r, strtwoChildHelp)
 }
 
@@ -717,7 +716,7 @@ func TestNonRunChildHelp(t *testing.T) {
 func TestRunnableRootCommand(t *testing.T) {
 	x := fullSetupTest("")
 
-	if rootcalled != true {
+	if !rootcalled {
 		t.Errorf("Root Function was not called\n out:%v", x.Error)
 	}
 }
@@ -751,7 +750,6 @@ func TestVisitParents(t *testing.T) {
 }
 
 func TestRunnableRootCommandNilInput(t *testing.T) {
-	var emptyArg []string
 	c := initializeWithRootCmd()
 
 	buf := new(bytes.Buffer)
@@ -759,23 +757,20 @@ func TestRunnableRootCommandNilInput(t *testing.T) {
 	c.SetOutput(buf)
 	cmdEcho.AddCommand(cmdTimes)
 	c.AddCommand(cmdPrint, cmdEcho)
-	c.SetArgs(emptyArg)
+	c.SetArgs([]string{})
 
 	err := c.Execute()
 	if err != nil {
 		t.Errorf("Execute() failed with %v", err)
 	}
 
-	if rootcalled != true {
+	if !rootcalled {
 		t.Errorf("Root Function was not called")
 	}
 }
 
 func TestRunnableRootCommandEmptyInput(t *testing.T) {
-	args := make([]string, 3)
-	args[0] = ""
-	args[1] = "--introot=12"
-	args[2] = ""
+	args := []string{"", "--introot=12", ""}
 	c := initializeWithRootCmd()
 
 	buf := new(bytes.Buffer)
@@ -787,13 +782,13 @@ func TestRunnableRootCommandEmptyInput(t *testing.T) {
 
 	c.Execute()
 
-	if rootcalled != true {
-		t.Errorf("Root Function was not called.\n\nOutput was:\n\n%s\n", buf)
+	if !rootcalled {
+		t.Errorf("Root Function was not called.\nOutput was:\n%s\n", buf)
 	}
 }
 
 func TestInvalidSubcommandWhenArgsAllowed(t *testing.T) {
-	fullSetupTest("echo invalid-sub")
+	fullSetupTest("echo", "invalid-sub")
 
 	if te[0] != "invalid-sub" {
 		t.Errorf("Subcommand didn't work...")
@@ -801,9 +796,9 @@ func TestInvalidSubcommandWhenArgsAllowed(t *testing.T) {
 }
 
 func TestRootFlags(t *testing.T) {
-	fullSetupTest("-i 17 -b")
+	fullSetupTest("-i", "17", "-b")
 
-	if flagbr != true {
+	if !flagbr {
 		t.Errorf("flag value should be true, %v given", flagbr)
 	}
 
@@ -826,7 +821,7 @@ func TestRootHelp(t *testing.T) {
 		t.Errorf("--help shouldn't display subcommand's usage, Got: \n %s", x.Output)
 	}
 
-	x = fullSetupTest("echo --help")
+	x = fullSetupTest("echo", "--help")
 
 	if strings.Contains(x.Output, cmdTimes.Use) {
 		t.Errorf("--help shouldn't display subsubcommand's usage, Got: \n %s", x.Output)
@@ -861,7 +856,6 @@ func TestFlagAccess(t *testing.T) {
 }
 
 func TestNoNRunnableRootCommandNilInput(t *testing.T) {
-	var args []string
 	c := initialize()
 
 	buf := new(bytes.Buffer)
@@ -869,7 +863,7 @@ func TestNoNRunnableRootCommandNilInput(t *testing.T) {
 	c.SetOutput(buf)
 	cmdEcho.AddCommand(cmdTimes)
 	c.AddCommand(cmdPrint, cmdEcho)
-	c.SetArgs(args)
+	c.SetArgs([]string{})
 
 	c.Execute()
 
@@ -888,7 +882,7 @@ func TestRootNoCommandHelp(t *testing.T) {
 		t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
 	}
 
-	x = rootOnlySetupTest("echo --help")
+	x = rootOnlySetupTest("echo", "--help")
 
 	checkResultOmits(t, x, "Available Commands:")
 	checkResultOmits(t, x, "for more information about a command")
@@ -906,7 +900,7 @@ func TestRootUnknownCommand(t *testing.T) {
 		t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output)
 	}
 
-	r = noRRSetupTest("--strtwo=a bogus")
+	r = noRRSetupTest("--strtwo=a", "bogus")
 	if r.Output != s {
 		t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output)
 	}
@@ -919,7 +913,7 @@ func TestRootUnknownCommandSilenced(t *testing.T) {
 		t.Errorf("Unexpected response.\nExpecting to be: \n\"\"\n Got:\n %q\n", r.Output)
 	}
 
-	r = noRRSetupTestSilenced("--strtwo=a bogus")
+	r = noRRSetupTestSilenced("--strtwo=a", "bogus")
 	if r.Output != "" {
 		t.Errorf("Unexpected response.\nExpecting to be:\n\"\"\nGot:\n %q\n", r.Output)
 	}
@@ -966,56 +960,27 @@ func TestRootSuggestions(t *testing.T) {
 
 func TestFlagsBeforeCommand(t *testing.T) {
 	// short without space
-	x := fullSetupTest("-i10 echo")
+	x := fullSetupTest("-i10", "echo")
 	if x.Error != nil {
 		t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
 	}
 
-	// short (int) with equals
-	// It appears that pflags doesn't support this...
-	// Commenting out until support can be added
-
-	//x = noRRSetupTest("echo -i=10")
-	//if x.Error != nil {
-	//t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)
-	//}
+	x = noRRSetupTest("echo", "-i=10")
+	if x.Error != nil {
+		t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)
+	}
 
 	// long with equals
-	x = noRRSetupTest("--intone=123 echo one two")
+	x = noRRSetupTest("--intone=123", "echo", "one", "two")
 	if x.Error != nil {
 		t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)
 	}
 
 	// With parsing error properly reported
-	x = fullSetupTest("-i10E echo")
+	x = fullSetupTest("-i10E", "echo")
 	if !strings.Contains(x.Error.Error(), "invalid syntax") {
 		t.Errorf("Wrong error message displayed, \n %s", x.Error)
 	}
-
-	//With quotes
-	x = fullSetupTest("-s=\"walking\" echo")
-	if x.Error != nil {
-		t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
-	}
-
-	//With quotes and space
-	x = fullSetupTest("-s=\"walking fast\" echo")
-	if x.Error != nil {
-		t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
-	}
-
-	//With inner quote
-	x = fullSetupTest("-s=\"walking \\\"Inner Quote\\\" fast\" echo")
-	if x.Error != nil {
-		t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
-	}
-
-	//With quotes and space
-	x = fullSetupTest("-s=\"walking \\\"Inner Quote\\\" fast\" echo")
-	if x.Error != nil {
-		t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
-	}
-
 }
 
 func TestRemoveCommand(t *testing.T) {
@@ -1081,7 +1046,7 @@ func TestDeprecatedSub(t *testing.T) {
 }
 
 func TestPreRun(t *testing.T) {
-	noRRSetupTest("echo one two")
+	noRRSetupTest("echo", "one", "two")
 	if echoPre == nil || echoPersPre == nil {
 		t.Error("PreRun or PersistentPreRun not called")
 	}
@@ -1089,7 +1054,7 @@ func TestPreRun(t *testing.T) {
 		t.Error("Wrong *Pre functions called!")
 	}
 
-	noRRSetupTest("echo times one two")
+	noRRSetupTest("echo", "times", "one", "two")
 	if timesPersPre == nil {
 		t.Error("PreRun or PersistentPreRun not called")
 	}
@@ -1097,7 +1062,7 @@ func TestPreRun(t *testing.T) {
 		t.Error("Wrong *Pre functions called!")
 	}
 
-	noRRSetupTest("print one two")
+	noRRSetupTest("print", "one", "two")
 	if rootPersPre == nil {
 		t.Error("Parent PersistentPreRun not called but should not have been")
 	}
@@ -1115,10 +1080,10 @@ func TestPeristentPreRunPropagation(t *testing.T) {
 	// Now add cmdPrint to rootCmd
 	rootCmd.AddCommand(cmdPrint)
 
-	rootCmd.SetArgs(strings.Split("print echosub lala", " "))
+	rootCmd.SetArgs([]string{"print", "echosub", "lala"})
 	rootCmd.Execute()
 
-	if rootPersPre == nil || len(rootPersPre) == 0 || rootPersPre[0] != "lala" {
+	if len(rootPersPre) == 0 || rootPersPre[0] != "lala" {
 		t.Error("RootCmd PersistentPreRun not called but should have been")
 	}
 }
@@ -1150,12 +1115,12 @@ func TestGlobalNormFuncPropagation(t *testing.T) {
 
 func TestFlagOnPflagCommandLine(t *testing.T) {
 	flagName := "flagOnCommandLine"
-	pflag.CommandLine.String(flagName, "", "about my flag")
+	pflag.String(flagName, "", "about my flag")
 	r := fullSetupTest("--help")
 
 	checkResultContains(t, r, flagName)
 
-	// reset CommandLine flagset
+	// Reset pflag.CommandLine flagset.
 	pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)
 }
 
diff --git a/command_test.go b/command_test.go
index 24abd3e..978bacc 100644
--- a/command_test.go
+++ b/command_test.go
@@ -227,7 +227,7 @@ func TestFlagErrorFunc(t *testing.T) {
 
 // TestSortedFlags checks,
 // if cmd.LocalFlags() is unsorted when cmd.Flags().SortFlags set to false.
-// https://github.com/spf13/cobra/issues/404
+// Related to https://github.com/spf13/cobra/issues/404.
 func TestSortedFlags(t *testing.T) {
 	cmd := &Command{}
 	cmd.Flags().SortFlags = false
@@ -263,13 +263,13 @@ 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.
-// https://github.com/spf13/cobra/issues/302
+// Related to 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 }}
+	parent := &Command{Use: "parent", Run: func(*Command, []string) {}}
 	parent.SetOutput(output)
 
-	child := &Command{Use: "child", Long: "long", Run: func(*Command, []string) { return }}
+	child := &Command{Use: "child", Run: func(*Command, []string) {}}
 	parent.AddCommand(child)
 
 	parent.SetArgs([]string{"help", "child"})
@@ -279,6 +279,22 @@ func TestHelpFlagInHelp(t *testing.T) {
 	}
 
 	if !strings.Contains(output.String(), "[flags]") {
-		t.Fatalf("\nExpecting to contain: %v\nGot: %v", "[flags]", output.String())
+		t.Errorf("\nExpecting to contain: %v\nGot: %v", "[flags]", output.String())
 	}
 }
+
+// TestMergeCommandLineToFlags checks,
+// if pflag.CommandLine is correctly merged to c.Flags() after first call
+// of c.mergePersistentFlags.
+// Related to https://github.com/spf13/cobra/issues/443.
+func TestMergeCommandLineToFlags(t *testing.T) {
+	pflag.Bool("boolflag", false, "")
+	c := &Command{Use: "c", Run: func(*Command, []string) {}}
+	c.mergePersistentFlags()
+	if c.Flags().Lookup("boolflag") == nil {
+		t.Fatal("Expecting to have flag from CommandLine in c.Flags()")
+	}
+
+	// Reset pflag.CommandLine flagset.
+	pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)
+}