From 3be50ddeba1fbd75feb38e42468685662a34b074 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Thu, 1 Mar 2018 08:50:30 -0800 Subject: [PATCH 01/94] README.md: reorganize into Core Team, Alumni --- README.md | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1932fff1..ab0bc0e8 100644 --- a/README.md +++ b/README.md @@ -140,6 +140,32 @@ These are the humans that form the Git LFS core team, which runs the project. In alphabetical order: -| [@andyneff](https://github.com/andyneff) | [@rubyist](https://github.com/rubyist) | [@sinbad](https://github.com/sinbad) | [@technoweenie](https://github.com/technoweenie) | [@ttaylorr](https://github.com/ttaylorr) | -|---|---|---|---|---| -| [![](https://avatars1.githubusercontent.com/u/7596961?v=3&s=100)](https://github.com/andyneff) | [![](https://avatars1.githubusercontent.com/u/143?v=3&s=100)](https://github.com/rubyist) | [![](https://avatars1.githubusercontent.com/u/142735?v=3&s=100)](https://github.com/sinbad) | [![](https://avatars3.githubusercontent.com/u/21?v=3&s=100)](https://github.com/technoweenie) | [![](https://avatars3.githubusercontent.com/u/443245?v=3&s=100)](https://github.com/ttaylorr) | +| [@larsxschneider][larsxschneider-user] | [@ttaylorr][ttaylorr-user] | +|---|---| +| [![][larsxschneider-img]][larsxschneider-user] | [![][ttaylorr-img]][ttaylorr-user] | + +[larsxschneider-img]: https://avatars1.githubusercontent.com/u/477434?s=100&v=4 +[ttaylorr-img]: https://avatars2.githubusercontent.com/u/443245?s=100&v=4 +[larsxschneider-user]: https://github.com/larsxschneider +[ttaylorr-user]: https://github.com/ttaylorr + +### Alumni + +These are the humans that have in the past formed the Git LFS core team, or +have otherwise contributed a significant amount to the project. Git LFS would +not be possible without them. + +In alphabetical order: + +| [@andyneff][andyneff-user] | [@rubyist][rubyist-user] | [@sinbad][sinbad-user] | [@technoweenie][technoweenie-user] | +|---|---|---|---| +| [![][andyneff-img]][andyneff-user] | [![][rubyist-img]][rubyist-user] | [![][sinbad-img]][sinbad-user] | [![][technoweenie-img]][technoweenie-user] | + +[andyneff-img]: https://avatars1.githubusercontent.com/u/7596961?v=3&s=100 +[rubyist-img]: https://avatars1.githubusercontent.com/u/143?v=3&s=100 +[sinbad-img]: https://avatars1.githubusercontent.com/u/142735?v=3&s=100 +[technoweenie-img]: https://avatars3.githubusercontent.com/u/21?v=3&s=100 +[andyneff-user]: https://github.com/andyneff +[sinbad-user]: https://github.com/sinbad +[rubyist-user]: https://github.com/rubyist +[technoweenie-user]: https://github.com/technoweenie From 96775c62f71d795af1547f6ef92c2a8602fd32df Mon Sep 17 00:00:00 2001 From: Jasmin Lapalme Date: Mon, 19 Mar 2018 09:41:35 -0400 Subject: [PATCH 02/94] Add object-map option to get a map from the old sha1 to new sha1 #2766 --- commands/command_migrate.go | 10 ++++++++-- commands/command_migrate_import.go | 3 ++- git/githistory/rewriter.go | 20 ++++++++++++++++++++ test/test-migrate-import.sh | 17 +++++++++++++++++ 4 files changed, 47 insertions(+), 3 deletions(-) diff --git a/commands/command_migrate.go b/commands/command_migrate.go index 8aef8ab9..391524cd 100644 --- a/commands/command_migrate.go +++ b/commands/command_migrate.go @@ -32,6 +32,10 @@ var ( // migrateVerbose enables verbose logging migrateVerbose bool + + // objectMapFile is the path to the map of old sha1 to new sha1 + // commits + objectMapFilePath string ) // migrate takes the given command and arguments, *odb.ObjectDatabase, as well @@ -83,8 +87,9 @@ func rewriteOptions(args []string, opts *githistory.RewriteOptions, l *tasklog.L Include: include, Exclude: exclude, - UpdateRefs: opts.UpdateRefs, - Verbose: opts.Verbose, + UpdateRefs: opts.UpdateRefs, + Verbose: opts.Verbose, + ObjectMapFilePath: opts.ObjectMapFilePath, BlobFn: opts.BlobFn, TreeCallbackFn: opts.TreeCallbackFn, @@ -281,6 +286,7 @@ func init() { importCmd := NewCommand("import", migrateImportCommand) importCmd.Flags().BoolVar(&migrateVerbose, "verbose", false, "Verbose logging") + importCmd.Flags().StringVar(&objectMapFilePath, "object-map", "", "Object map file") RegisterCommand("migrate", nil, func(cmd *cobra.Command) { cmd.PersistentFlags().StringVarP(&includeArg, "include", "I", "", "Include a list of paths") diff --git a/commands/command_migrate_import.go b/commands/command_migrate_import.go index b9ac784b..0833f24b 100644 --- a/commands/command_migrate_import.go +++ b/commands/command_migrate_import.go @@ -36,7 +36,8 @@ func migrateImportCommand(cmd *cobra.Command, args []string) { gitfilter := lfs.NewGitFilter(cfg) migrate(args, rewriter, l, &githistory.RewriteOptions{ - Verbose: migrateVerbose, + Verbose: migrateVerbose, + ObjectMapFilePath: objectMapFilePath, BlobFn: func(path string, b *odb.Blob) (*odb.Blob, error) { if filepath.Base(path) == ".gitattributes" { return b, nil diff --git a/git/githistory/rewriter.go b/git/githistory/rewriter.go index 566e57e9..07f1d529 100644 --- a/git/githistory/rewriter.go +++ b/git/githistory/rewriter.go @@ -54,6 +54,10 @@ type RewriteOptions struct { // Verbose mode prints migrated objects. Verbose bool + // ObjectMapFilePath is the path to the map of old sha1 to new sha1 + // commits + ObjectMapFilePath string + // BlobFn specifies a function to rewrite blobs. // // It is called once per unique, unchanged path. That is to say, if @@ -188,6 +192,15 @@ func (r *Rewriter) Rewrite(opt *RewriteOptions) ([]byte, error) { vPerc = perc } + var objectMapFile *os.File + if len(opt.ObjectMapFilePath) > 0 { + objectMapFile, err = os.Create(opt.ObjectMapFilePath) + if err != nil { + return nil, fmt.Errorf("Could not create object map file: %v", err) + } + defer objectMapFile.Close() + } + // Keep track of the last commit that we rewrote. Callers often want // this so that they can perform a git-update-ref(1). var tip []byte @@ -253,6 +266,13 @@ func (r *Rewriter) Rewrite(opt *RewriteOptions) ([]byte, error) { if err != nil { return nil, err } + if len(opt.ObjectMapFilePath) > 0 { + mapStr := fmt.Sprintf("%s,%s\n", hex.EncodeToString(oid), hex.EncodeToString(newSha)) + _, err := objectMapFile.WriteString(mapStr) + if err != nil { + return nil, err + } + } } // Cache that commit so that we can reassign children of this diff --git a/test/test-migrate-import.sh b/test/test-migrate-import.sh index 1c1ff4ba..a2775bac 100755 --- a/test/test-migrate-import.sh +++ b/test/test-migrate-import.sh @@ -616,3 +616,20 @@ begin_test "migrate import (handle copies of files)" [ "$oid_root" = "$oid_root_after_migration" ] ) end_test + +begin_test "migrate import (--object-map)" +( + set -e + + setup_multiple_local_branches + + output_dir=$(mktemp -d) + + git log --all --pretty='format:%H' > "${output_dir}/old_sha.txt" + git lfs migrate import --everything --object-map "${output_dir}/object-map.txt" + git log --all --pretty='format:%H' > "${output_dir}/new_sha.txt" + paste -d',' "${output_dir}/old_sha.txt" "${output_dir}/new_sha.txt" > "${output_dir}/expected-map.txt" + + diff -u "${output_dir}/expected-map.txt" "${output_dir}/object-map.txt" +) +end_test From 3a7d54bf9c813d381d830e2e59ad9e6d03a81819 Mon Sep 17 00:00:00 2001 From: Jasmin Lapalme Date: Mon, 19 Mar 2018 20:49:10 -0400 Subject: [PATCH 03/94] Add missing import --- git/githistory/rewriter.go | 1 + 1 file changed, 1 insertion(+) diff --git a/git/githistory/rewriter.go b/git/githistory/rewriter.go index 07f1d529..4d4e1453 100644 --- a/git/githistory/rewriter.go +++ b/git/githistory/rewriter.go @@ -4,6 +4,7 @@ import ( "encoding/hex" "fmt" "io" + "os" "strings" "sync" From cdcd9dc616b180a3dcbdb3e2369747223915145f Mon Sep 17 00:00:00 2001 From: Jasmin Lapalme Date: Mon, 19 Mar 2018 21:12:10 -0400 Subject: [PATCH 04/94] Add documentation for --object-map --- docs/man/git-lfs-migrate.1.ronn | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/man/git-lfs-migrate.1.ronn b/docs/man/git-lfs-migrate.1.ronn index 7ee3782a..d81b980e 100644 --- a/docs/man/git-lfs-migrate.1.ronn +++ b/docs/man/git-lfs-migrate.1.ronn @@ -80,6 +80,11 @@ options and these additional ones: * `--verbose` Print the commit oid and filename of migrated files to STDOUT. +* `--object-map=` + Write to 'path' a file with the mapping of each rewritten commits. The file + format is CSV with this pattern: + * `OLD-SHA,NEW-SHA` + If `--include` or `--exclude` (`-I`, `-X`, respectively) are given, the .gitattributes will be modified to include any new filepath patterns as given by those flags. From 8a18b6085363a4b34a26be150a6eb01a49ebc8e3 Mon Sep 17 00:00:00 2001 From: Jasmin Lapalme Date: Mon, 19 Mar 2018 21:35:01 -0400 Subject: [PATCH 05/94] Remove backquote in the object map file format --- docs/man/git-lfs-migrate.1.ronn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/man/git-lfs-migrate.1.ronn b/docs/man/git-lfs-migrate.1.ronn index d81b980e..01a17f90 100644 --- a/docs/man/git-lfs-migrate.1.ronn +++ b/docs/man/git-lfs-migrate.1.ronn @@ -83,7 +83,7 @@ options and these additional ones: * `--object-map=` Write to 'path' a file with the mapping of each rewritten commits. The file format is CSV with this pattern: - * `OLD-SHA,NEW-SHA` + * OLD-SHA,NEW-SHA If `--include` or `--exclude` (`-I`, `-X`, respectively) are given, the .gitattributes will be modified to include any new filepath patterns as given by From 2409b3e99f24210d08ff9c1d2b64a4af1ce7114c Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Tue, 20 Mar 2018 20:02:52 -0400 Subject: [PATCH 06/94] commands/{un,}track: rename conversion functions --- commands/command_track.go | 8 ++++---- commands/command_untrack.go | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/commands/command_track.go b/commands/command_track.go index 3472f9c3..db013dfd 100644 --- a/commands/command_track.go +++ b/commands/command_track.go @@ -81,7 +81,7 @@ ArgsLoop: } // Generate the new / changed attrib line for merging - encodedArg := escapeTrackPattern(pattern) + encodedArg := escapeAttrPattern(pattern) lockableArg := "" if trackLockableFlag { // no need to test trackNotLockableFlag, if we got here we're disabling lockableArg = " " + git.LockableAttrib @@ -95,7 +95,7 @@ ArgsLoop: writeablePatterns = append(writeablePatterns, pattern) } - Print("Tracking %q", unescapeTrackPattern(encodedArg)) + Print("Tracking %q", unescapeAttrPattern(encodedArg)) } // Now read the whole local attributes file and iterate over the contents, @@ -258,7 +258,7 @@ var ( } ) -func escapeTrackPattern(unescaped string) string { +func escapeAttrPattern(unescaped string) string { var escaped string = strings.Replace(unescaped, `\`, "/", -1) for from, to := range trackEscapePatterns { @@ -268,7 +268,7 @@ func escapeTrackPattern(unescaped string) string { return escaped } -func unescapeTrackPattern(escaped string) string { +func unescapeAttrPattern(escaped string) string { var unescaped string = escaped for to, from := range trackEscapePatterns { diff --git a/commands/command_untrack.go b/commands/command_untrack.go index 0b51fca8..99c59d4b 100644 --- a/commands/command_untrack.go +++ b/commands/command_untrack.go @@ -55,7 +55,7 @@ func untrackCommand(cmd *cobra.Command, args []string) { path := strings.Fields(line)[0] if removePath(path, args) { - Print("Untracking %q", unescapeTrackPattern(path)) + Print("Untracking %q", unescapeAttrPattern(path)) } else { attributesFile.WriteString(line + "\n") } @@ -64,7 +64,7 @@ func untrackCommand(cmd *cobra.Command, args []string) { func removePath(path string, args []string) bool { for _, t := range args { - if path == escapeTrackPattern(t) { + if path == escapeAttrPattern(t) { return true } } From 89c5fa0635e570a857bad3397894dbc5abcd4e83 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Tue, 20 Mar 2018 20:36:04 -0400 Subject: [PATCH 07/94] commands: teach migrate to escape attribute filters --- commands/command_migrate_import.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/commands/command_migrate_import.go b/commands/command_migrate_import.go index b9ac784b..606ba4c7 100644 --- a/commands/command_migrate_import.go +++ b/commands/command_migrate_import.go @@ -123,11 +123,11 @@ func trackedFromFilter(filter *filepathfilter.Filter) *tools.OrderedSet { tracked := tools.NewOrderedSet() for _, include := range filter.Include() { - tracked.Add(fmt.Sprintf("%s filter=lfs diff=lfs merge=lfs -text", include)) + tracked.Add(fmt.Sprintf("%s filter=lfs diff=lfs merge=lfs -text", escapeAttrPattern(include))) } for _, exclude := range filter.Exclude() { - tracked.Add(fmt.Sprintf("%s text -filter -merge -diff", exclude)) + tracked.Add(fmt.Sprintf("%s text -filter -merge -diff", escapeAttrPattern(exclude))) } return tracked From 11199f0176ab4e84d1f231e60dee3222b4f0f971 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Tue, 20 Mar 2018 20:37:02 -0400 Subject: [PATCH 08/94] test: add setup_local_branch_with_space to migrate fixtures --- test/test-migrate-fixtures.sh | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/test/test-migrate-fixtures.sh b/test/test-migrate-fixtures.sh index e461279c..9be71f4d 100755 --- a/test/test-migrate-fixtures.sh +++ b/test/test-migrate-fixtures.sh @@ -79,6 +79,27 @@ setup_multiple_local_branches() { git checkout master } +# setup_local_branch_with_space creates a repository as follows: +# +# A +# \ +# refs/heads/master +# +# - Commit 'A' has 50 bytes in a file named "a file.txt". +setup_local_branch_with_space() { + set -e + + reponame="migrate-local-branch-with-space" + filename="a file.txt" + + remove_and_create_local_repo "$reponame" + + base64 < /dev/urandom | head -c 50 > "$filename" + + git add "$filename" + git commit -m "initial commit" +} + # setup_single_remote_branch creates a repository as follows: # # A---B From 570405749f2d32d1b20d0f223ce3e7e40d954cd4 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Tue, 20 Mar 2018 20:37:14 -0400 Subject: [PATCH 09/94] test: add migrate import case with --include containing space --- test/test-migrate-import.sh | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/test/test-migrate-import.sh b/test/test-migrate-import.sh index 1c1ff4ba..1ed1c75a 100755 --- a/test/test-migrate-import.sh +++ b/test/test-migrate-import.sh @@ -616,3 +616,24 @@ begin_test "migrate import (handle copies of files)" [ "$oid_root" = "$oid_root_after_migration" ] ) end_test + +begin_test "migrate import (--include with space)" +( + set -e + + setup_local_branch_with_space + + oid="$(calc_oid "$(git cat-file -p :"a file.txt")")" + + git lfs migrate import --include "a file.txt" + + assert_pointer "refs/heads/master" "a file.txt" "$oid" 50 + cat .gitattributes + if [ 1 -ne "$(grep -c "a\[\[:space:\]\]file.txt" .gitattributes)" ]; then + echo >&2 "fatal: expected \"a[[:space:]]file.txt\" to appear in .gitattributes" + echo >&2 "fatal: got" + sed -e 's/^/ /g' < .gitattributes >&2 + exit 1 + fi +) +end_test From edba2fb86ee93ba241b61a630636eddac31199e1 Mon Sep 17 00:00:00 2001 From: Jasmin Lapalme Date: Tue, 20 Mar 2018 21:27:15 -0400 Subject: [PATCH 10/94] Reformulate to remove the * --- docs/man/git-lfs-migrate.1.ronn | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/man/git-lfs-migrate.1.ronn b/docs/man/git-lfs-migrate.1.ronn index 01a17f90..996f4742 100644 --- a/docs/man/git-lfs-migrate.1.ronn +++ b/docs/man/git-lfs-migrate.1.ronn @@ -82,8 +82,7 @@ options and these additional ones: * `--object-map=` Write to 'path' a file with the mapping of each rewritten commits. The file - format is CSV with this pattern: - * OLD-SHA,NEW-SHA + format is CSV with this pattern: `OLD-SHA`,`NEW-SHA` If `--include` or `--exclude` (`-I`, `-X`, respectively) are given, the .gitattributes will be modified to include any new filepath patterns as given by From 22cbb86df7e2761b57c97cb7eade3186549a9d0b Mon Sep 17 00:00:00 2001 From: Jasmin Lapalme Date: Tue, 20 Mar 2018 21:42:02 -0400 Subject: [PATCH 11/94] Rewrite to be shorter --- git/githistory/rewriter.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/git/githistory/rewriter.go b/git/githistory/rewriter.go index 4d4e1453..bafe7de6 100644 --- a/git/githistory/rewriter.go +++ b/git/githistory/rewriter.go @@ -267,9 +267,8 @@ func (r *Rewriter) Rewrite(opt *RewriteOptions) ([]byte, error) { if err != nil { return nil, err } - if len(opt.ObjectMapFilePath) > 0 { - mapStr := fmt.Sprintf("%s,%s\n", hex.EncodeToString(oid), hex.EncodeToString(newSha)) - _, err := objectMapFile.WriteString(mapStr) + if objectMapFile != nil { + _, err := fmt.Fprintf(objectMapFile, "%s,%s\n", hex.EncodeToString(oid), hex.EncodeToString(newSha)) if err != nil { return nil, err } From 670f5b4171f3f334378818bb65cb45b6116fcbc0 Mon Sep 17 00:00:00 2001 From: Jasmin Lapalme Date: Tue, 20 Mar 2018 23:20:19 -0400 Subject: [PATCH 12/94] Sort the outputs to list commits in the same order --- test/test-migrate-import.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test-migrate-import.sh b/test/test-migrate-import.sh index a2775bac..be1bc26f 100755 --- a/test/test-migrate-import.sh +++ b/test/test-migrate-import.sh @@ -630,6 +630,6 @@ begin_test "migrate import (--object-map)" git log --all --pretty='format:%H' > "${output_dir}/new_sha.txt" paste -d',' "${output_dir}/old_sha.txt" "${output_dir}/new_sha.txt" > "${output_dir}/expected-map.txt" - diff -u "${output_dir}/expected-map.txt" "${output_dir}/object-map.txt" + diff -u <(sort "${output_dir}/expected-map.txt") <(sort "${output_dir}/object-map.txt") ) end_test From 667580ee23a2bbcfa8a4dc4f1a5655daa315711b Mon Sep 17 00:00:00 2001 From: Jasmin Lapalme Date: Wed, 21 Mar 2018 14:57:45 -0400 Subject: [PATCH 13/94] Prevent overwriting an existing file --- git/githistory/rewriter.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/git/githistory/rewriter.go b/git/githistory/rewriter.go index bafe7de6..dc380dcb 100644 --- a/git/githistory/rewriter.go +++ b/git/githistory/rewriter.go @@ -195,7 +195,7 @@ func (r *Rewriter) Rewrite(opt *RewriteOptions) ([]byte, error) { var objectMapFile *os.File if len(opt.ObjectMapFilePath) > 0 { - objectMapFile, err = os.Create(opt.ObjectMapFilePath) + objectMapFile, err = os.OpenFile(opt.ObjectMapFilePath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666) if err != nil { return nil, fmt.Errorf("Could not create object map file: %v", err) } From f765705f78f205cd27852c7dd02ddb40370de864 Mon Sep 17 00:00:00 2001 From: Jasmin Lapalme Date: Wed, 21 Mar 2018 14:59:00 -0400 Subject: [PATCH 14/94] Use %x to remove the explicit call to EncodeToString --- git/githistory/rewriter.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/git/githistory/rewriter.go b/git/githistory/rewriter.go index dc380dcb..2ba0c533 100644 --- a/git/githistory/rewriter.go +++ b/git/githistory/rewriter.go @@ -268,8 +268,7 @@ func (r *Rewriter) Rewrite(opt *RewriteOptions) ([]byte, error) { return nil, err } if objectMapFile != nil { - _, err := fmt.Fprintf(objectMapFile, "%s,%s\n", hex.EncodeToString(oid), hex.EncodeToString(newSha)) - if err != nil { + if _, err := fmt.Fprintf(objectMapFile, "%x,%x\n", oid, newSha); err != nil { return nil, err } } From cc80c2549330266a39098d0d9671e329426d9b76 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 23 Mar 2018 12:11:52 -0400 Subject: [PATCH 15/94] test: ensure that git-mergetool(1) works with large files --- test/test-mergetool.sh | 51 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100755 test/test-mergetool.sh diff --git a/test/test-mergetool.sh b/test/test-mergetool.sh new file mode 100755 index 00000000..baac2e81 --- /dev/null +++ b/test/test-mergetool.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash + +. "test/testlib.sh" + +begin_test "mergetool works with large files" +( + set -e + + reponame="mergetool-works-with-large-files" + git init "$reponame" + cd "$reponame" + + git lfs track "*.dat" + printf "base" > conflict.dat + git add .gitattributes conflict.dat + git commit -m "initial commit" + + git checkout -b conflict + printf "b" > conflict.dat + git add conflict.dat + git commit -m "conflict.dat: b" + + git checkout master + + printf "a" > conflict.dat + git add conflict.dat + git commit -m "conflict.dat: a" + + set +e + git merge conflict + set -e + + git config mergetool.inspect.cmd ' + for i in BASE LOCAL REMOTE; do + echo "\$$i=$(eval "cat \"\$$i\"")"; + done; + exit 1 + ' + git config mergetool.inspect.trustExitCode true + + yes | git mergetool \ + --no-prompt \ + --tool=inspect \ + -- conflict.dat 2>&1 \ + | tee mergetool.log + + grep "\$BASE=base" mergetool.log + grep "\$LOCAL=a" mergetool.log + grep "\$REMOTE=b" mergetool.log +) +end_test From 6d04b603c96ed16eddf01bfff65a3a19509a22e5 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 23 Mar 2018 13:04:10 -0400 Subject: [PATCH 16/94] README.md: :nail_care: --- README.md | 119 +++++++++++++++++++++++++----------------------------- 1 file changed, 54 insertions(+), 65 deletions(-) diff --git a/README.md b/README.md index 1932fff1..3f9fac3f 100644 --- a/README.md +++ b/README.md @@ -11,86 +11,88 @@ [5]: https://ci.appveyor.com/api/projects/status/46a5yoqc3hk59bl5/branch/master?svg=true [6]: https://ci.appveyor.com/project/git-lfs/git-lfs/branch/master -Git LFS is a command line extension and [specification](docs/spec.md) for -managing large files with Git. The client is written in Go, with pre-compiled -binaries available for Mac, Windows, Linux, and FreeBSD. Check out the -[Git LFS website][page] for an overview of features. +[Git LFS](https://git-lfs.github.com) is a command line extension and +[specification](docs/spec.md) for managing large files with Git. -[page]: https://git-lfs.github.com/ +The client is written in Go, with pre-compiled binaries available for Mac, +Windows, Linux, and FreeBSD. Check out the [website](http://git-lfs.github.com) +for an overview of features. ## Getting Started -By default, the Git LFS client needs a Git LFS server to sync the large files -it manages. This works out of the box when using popular git repository -hosting providers like GitHub, Atlassian, etc. When you host your own -vanilla git server, for example, you need to either use a separate -[Git LFS server instance](https://github.com/git-lfs/git-lfs/wiki/Implementations), -or use the [custom transfer adapter](docs/custom-transfers.md) with -a transfer agent in blind mode, without having to use a Git LFS server instance. +### Installation -You can install the Git LFS client in several different ways, depending on -your setup and preferences. +You can install the Git LFS client in several different ways, depending on your +setup and preferences. -* Linux users can install Debian or RPM packages from [PackageCloud](https://packagecloud.io/github/git-lfs/install). See the [Installation Guide](./INSTALLING.md) for details. -* Mac users can install from [Homebrew](https://github.com/Homebrew/homebrew) with `brew install git-lfs`, or from [MacPorts](https://www.macports.org) with `port install git-lfs`. -* Windows users can install from [Chocolatey](https://chocolatey.org/) with `choco install git-lfs`. -* [Binary packages are available][rel] for Windows, Mac, Linux, and FreeBSD. -* You can build it with Go 1.8.1+. See the [Contributing Guide](./CONTRIBUTING.md) for instructions. +* **Linux users**. Debian and RPM packages are available from + [PackageCloud](https://packagecloud.io/git-lfs/install). +* **macOS users**. [Homebrew](https://brew.sh) bottles are distributed, and can + be installed via `brew install git-lfs`. +* **Windows users**. Chocolatey packages are distributed, and can be installed + via `choco install git-lfs`. -[rel]: https://github.com/git-lfs/git-lfs/releases +In addition, [binary packages](https://github.com/git-lfs/git-lfs/releases) are +available for Linux, macOS, Windows, and FreeBSD. This repository can also be +built-from-source using the latest version of [Go](https://golang.org). -Note: Git LFS requires Git v1.8.5 or higher. +### Usage -Once installed, you need to setup the global Git hooks for Git LFS. This only -needs to be done once per machine. +Git LFS requires a global installation once per-machine. This can be done by +running: ```bash $ git lfs install ``` -Now, it's time to add some large files to a repository. The first step is to -specify file patterns to store with Git LFS. These file patterns are stored in -`.gitattributes`. +To begin using Git LFS within your Git repository, you can indicate which files +you would like Git LFS to manage. This can be done by running the following +_from within Git repository_: ```bash -$ mkdir large-repo -$ cd large-repo -$ git init - -# Add all zip files through Git LFS -$ git lfs track "*.zip" +$ git lfs track "*.psd" ``` -Now you're ready to push some commits: +(Where `*.psd` is the pattern of filenames that you wish to track. You can read +more about this pattern syntax +[here](https://git-scm.org/docs/git-attribute://git-scm.com/docs/gitattributes)). + +After any invocation of `git-lfs-track(1)` or `git-lfs-untrack(1)`, you _must +commit changes to your `.gitattributes` file_. This can be done by running: ```bash $ git add .gitattributes -$ git add my.zip -$ git commit -m "add zip" +$ git commit -m "track *.psd files using Git LFS" ``` -You can confirm that Git LFS is managing your zip file: +You can now interact with your Git repository as usual, and Git LFS will take +care of managing your large files. For example, changing a file named `my.psd` +(tracked above via `*.psd`): + +```bash +$ git add my.psd +$ git commit -m "add psd" +``` + +You can confirm that Git LFS is managing your PSD file: ```bash $ git lfs ls-files -my.zip +3c2f7aedfb * my.psd ``` Once you've made your commits, push your files to the Git remote: ```bash $ git push origin master -Sending my.zip -LFS: 12.58 MB / 12.58 MB 100.00 % -Counting objects: 2, done. -Delta compression using up to 8 threads. -Compressing objects: 100% (5/5), done. -Writing objects: 100% (5/5), 548 bytes | 0 bytes/s, done. -Total 5 (delta 1), reused 0 (delta 0) +Uploading LFS objects: 100% (1/1), 810 B, 1.2 KB/s +# ... To https://github.com/git-lfs/git-lfs-test 67fcf6a..47b2002 master -> master ``` +Note: Git LFS requires Git v1.8.5 or higher. + ## Limitations Git LFS maintains a list of currently known limitations, which you can find and @@ -105,34 +107,21 @@ $ git lfs help ``` The [official documentation](docs) has command references and specifications for -the tool. You can ask questions in the [Git LFS chat room][chat], or [file a new -issue][ish]. Be sure to include details about the problem so we can -troubleshoot it. +the tool. -1. Include the output of `git lfs env`, which shows how your Git environment -is setup. -2. Include `GIT_TRACE=1` in any bad Git commands to enable debug messages. -3. If the output includes a message like `Errors logged to /path/to/.git/lfs/objects/logs/*.log`, -throw the contents in the issue, or as a link to a Gist or paste site. +You can always [open an issue](https://github.com/git-lfs/git-lfs/issues), and +one of the Core Team members will respond to you. Please be sure to include: -[chat]: https://gitter.im/git-lfs/git-lfs -[ish]: https://github.com/git-lfs/git-lfs/issues +1. The output of `git lfs env`, which displays helpful information about your + Git repository useful in debugging. +2. Any failed commands re-run with `GIT_TRACE=1` in the environment, which + displays additional information pertaining to why a command crashed. ## Contributing See [CONTRIBUTING.md](CONTRIBUTING.md) for info on working on Git LFS and sending patches. Related projects are listed on the [Implementations wiki -page][impl]. You can also join [the project's chat room][chat]. - -[impl]: https://github.com/git-lfs/git-lfs/wiki/Implementations - -### Using LFS from other Go code - -At the moment git-lfs is only focussed on the stability of its command line -interface, and the [server APIs](docs/api/README.md). The contents of the -source packages is subject to change. We therefore currently discourage other -Go code from depending on the git-lfs packages directly; an API to be used by -external Go code may be provided in future. +page](https://github.com/git-lfs/git-lfs/wiki/Implementations). ## Core Team From 98414e8bd78a9a86e8fd5fe460e4c5496d6ff1ba Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 26 Mar 2018 19:13:00 -0700 Subject: [PATCH 17/94] README.md: mention note about `git lfs track` retroactively --- README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/README.md b/README.md index 67850f9e..f18eac50 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,16 @@ $ git add my.psd $ git commit -m "add psd" ``` +> _Tip:_ if you have large files already in your repository's history, `git lfs +> track` will _not_ track them retroactively. To migrate existing large files +> in your history to use Git LFS, use `git lfs migrate`. For example: +> +> ``` +> $ git lfs migrate import --include="*.psd" +> ``` +> +> For more information, read [`git-lfs-migrate(1)`](https://github.com/git-lfs/git-lfs/blob/master/docs/man/git-lfs-migrate.1.ronn). + You can confirm that Git LFS is managing your PSD file: ```bash From acac3c458520332c3dbea4ad0a02b4701f2b69d0 Mon Sep 17 00:00:00 2001 From: Steffen Prohaska Date: Sat, 10 Mar 2018 15:43:44 +0100 Subject: [PATCH 18/94] Map local abspath to file:// endpoint URL It can be used to configure a standalone transfer agent for local files, like: ``` git config lfs.customtransfer.file.path git-lfs-standalonetransfer-file git config lfs.file:///.standalonetransferagent file ``` The `file://` scheme is required for Git config URL match to work. An absolute path alone cannot be used for URL matching. An example implementation of a transfer agent is available as Gist . Signed-off-by: Steffen Prohaska --- lfsapi/endpoint.go | 7 +++++++ lfsapi/endpoint_finder.go | 3 +++ lfsapi/endpoint_finder_test.go | 16 ++++++++++++++++ 3 files changed, 26 insertions(+) diff --git a/lfsapi/endpoint.go b/lfsapi/endpoint.go index 8e91c11d..7ecb1598 100644 --- a/lfsapi/endpoint.go +++ b/lfsapi/endpoint.go @@ -106,3 +106,10 @@ func endpointFromGitUrl(u *url.URL, e *endpointGitFinder) Endpoint { u.Scheme = e.gitProtocol return Endpoint{Url: u.String()} } + +func endpointFromLocalPath(path string) Endpoint { + if !strings.HasSuffix(path, ".git") { + path = fmt.Sprintf("%s/.git", path) + } + return Endpoint{Url: fmt.Sprintf("file://%s", path)} +} diff --git a/lfsapi/endpoint_finder.go b/lfsapi/endpoint_finder.go index 9c7f8783..84c4f2ef 100644 --- a/lfsapi/endpoint_finder.go +++ b/lfsapi/endpoint_finder.go @@ -170,6 +170,9 @@ func (e *endpointGitFinder) NewEndpointFromCloneURL(rawurl string) Endpoint { func (e *endpointGitFinder) NewEndpoint(rawurl string) Endpoint { rawurl = e.ReplaceUrlAlias(rawurl) + if strings.HasPrefix(rawurl, "/") { + return endpointFromLocalPath(rawurl) + } u, err := url.Parse(rawurl) if err != nil { return endpointFromBareSshUrl(rawurl) diff --git a/lfsapi/endpoint_finder_test.go b/lfsapi/endpoint_finder_test.go index 0af7696f..3ff6f091 100644 --- a/lfsapi/endpoint_finder_test.go +++ b/lfsapi/endpoint_finder_test.go @@ -250,6 +250,22 @@ func TestBareGitEndpointAddsLfsSuffix(t *testing.T) { assert.Equal(t, "", e.SshPort) } +func TestLocalPathEndpointAddsDotGitDir(t *testing.T) { + finder := NewEndpointFinder(NewContext(nil, nil, map[string]string{ + "remote.origin.url": "/local/path", + })) + e := finder.Endpoint("download", "") + assert.Equal(t, "file:///local/path/.git/info/lfs", e.Url) +} + +func TestLocalPathEndpointPreservesDotGit(t *testing.T) { + finder := NewEndpointFinder(NewContext(nil, nil, map[string]string{ + "remote.origin.url": "/local/path.git", + })) + e := finder.Endpoint("download", "") + assert.Equal(t, "file:///local/path.git/info/lfs", e.Url) +} + func TestAccessConfig(t *testing.T) { type accessTest struct { Access string From 1c8209bacf9a5c1eda44d9d0109ff4a55087bdc1 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Thu, 5 Apr 2018 10:46:12 -0700 Subject: [PATCH 19/94] commands/path.go: introduce trimCurrentPrefix to remove "./" There exist cases within Git LFS where we would like to perform a "pseudo-clean" on a given filepath. It should behave similarly to a call to filepath.Clean, but should only remove the beginning "./" (macOS, *nix) or ".\" (Windows, etc). This patch introduces trimCurrentPrefix, which removes such prefixes. It will be used in subsequent patches to perform prefix-independent comparison against arguments to "git lfs track" and "git lfs untrack" and the contents of a repository's .gitattributes file. Since we assume that the contents of ".gitattributes" are written on multiple platforms, each with their own platform-specific prefixes, trimCurrentPrefix is instructed to remove _all_ prefixes, not just the current platforms. --- commands/path.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/commands/path.go b/commands/path.go index 1aa70833..5ab636ee 100644 --- a/commands/path.go +++ b/commands/path.go @@ -12,6 +12,18 @@ func gitLineEnding(git env) string { } } +const ( + windowsPrefix = `.\` + nixPrefix = `./` +) + +func trimCurrentPrefix(p string) string { + if strings.HasPrefix(p, windowsPrefix) { + return strings.TrimPrefix(p, windowsPrefix) + } + return strings.TrimPrefix(p, nixPrefix) +} + type env interface { Get(string) (string, bool) } From 49bdc2b1b0bde83a6bca29591d6769f286d0203f Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Thu, 5 Apr 2018 10:51:26 -0700 Subject: [PATCH 20/94] commands/{un,}track: local-prefix agnostic comparison This patch use the trimCurrentPrefix utility introduced in the previous patch to make all .gitattributes comparisons agnostic to the "current-prefix" of "./" or ".\". Since we treat both sides of the comparison as having passed through "trimCurrentPrefix", we harden ourselves against "legacy"-style .gitattributes patterns containing prefixes, and "modern"-style ones lacking prefixes. That means that both combinations of "git lfs untrack ./a.dat" and "git lfs untrack a.dat" will remove both of these lines from a .gittatributes file: ./a.dat filter=lfs ... a.dat filter=lfs ... Signed-off-by: Taylor Blau --- commands/command_track.go | 2 +- commands/command_untrack.go | 3 +- test/test-track.sh | 18 +++++++++++ test/test-untrack.sh | 62 +++++++++++++++++++++++++++++++++++++ 4 files changed, 83 insertions(+), 2 deletions(-) diff --git a/commands/command_track.go b/commands/command_track.go index db013dfd..5ba06925 100644 --- a/commands/command_track.go +++ b/commands/command_track.go @@ -67,7 +67,7 @@ func trackCommand(cmd *cobra.Command, args []string) { var writeablePatterns []string ArgsLoop: for _, unsanitizedPattern := range args { - pattern := cleanRootPath(unsanitizedPattern) + pattern := trimCurrentPrefix(cleanRootPath(unsanitizedPattern)) if !trackNoModifyAttrsFlag { for _, known := range knownPatterns { if known.Path == filepath.Join(relpath, pattern) && diff --git a/commands/command_untrack.go b/commands/command_untrack.go index 99c59d4b..f15bfbb3 100644 --- a/commands/command_untrack.go +++ b/commands/command_untrack.go @@ -63,8 +63,9 @@ func untrackCommand(cmd *cobra.Command, args []string) { } func removePath(path string, args []string) bool { + withoutCurrentDir := trimCurrentPrefix(path) for _, t := range args { - if path == escapeAttrPattern(t) { + if withoutCurrentDir == escapeAttrPattern(trimCurrentPrefix(t)) { return true } } diff --git a/test/test-track.sh b/test/test-track.sh index 65ec3423..02ff7ce0 100755 --- a/test/test-track.sh +++ b/test/test-track.sh @@ -540,3 +540,21 @@ begin_test "track (with comments)" [ "0" -eq "$(grep -c "\.png" track.log)" ] ) end_test + +begin_test "track (with current-directory prefix)" +( + set -e + + reponame="track-with-current-directory-prefix" + git init "$reponame" + cd "$reponame" + + git lfs track "./a.dat" + printf "a" > a.dat + + git add .gitattributes a.dat + git commit -m "initial commit" + + grep -e "^a.dat" .gitattributes +) +end_test diff --git a/test/test-untrack.sh b/test/test-untrack.sh index e484c9fe..2e5005ea 100755 --- a/test/test-untrack.sh +++ b/test/test-untrack.sh @@ -72,3 +72,65 @@ begin_test "untrack removes escape sequences" assert_attributes_count "\\#" "filter=lfs" 0 ) end_test + +begin_test "untrack removes prefixed patterns (legacy)" +( + set -e + + reponame="untrack-removes-prefix-patterns-legacy" + git init "$reponame" + cd "$reponame" + + echo "./a.dat filter=lfs diff=lfs merge=lfs" > .gitattributes + printf "a" > a.dat + git add .gitattributes a.dat + git commit -m "initial commit" + + git lfs untrack "./a.dat" + + if [ ! -z "$(cat .gitattributes)" ]; then + echo &>2 "fatal: expected 'git lfs untrack' to clear .gitattributes" + exit 1 + fi + + git checkout -- .gitattributes + + git lfs untrack "a.dat" + + if [ ! -z "$(cat .gitattributes)" ]; then + echo &>2 "fatal: expected 'git lfs untrack' to clear .gitattributes" + exit 1 + fi +) +end_test + +begin_test "untrack removes prefixed patterns (modern)" +( + set -e + + reponame="untrack-removes-prefix-patterns-modern" + git init "$reponame" + cd "$reponame" + + echo "a.dat filter=lfs diff=lfs merge=lfs" > .gitattributes + printf "a" > a.dat + git add .gitattributes a.dat + git commit -m "initial commit" + + git lfs untrack "./a.dat" + + if [ ! -z "$(cat .gitattributes)" ]; then + echo &>2 "fatal: expected 'git lfs untrack' to clear .gitattributes" + exit 1 + fi + + git checkout -- .gitattributes + + git lfs untrack "a.dat" + + if [ ! -z "$(cat .gitattributes)" ]; then + echo &>2 "fatal: expected 'git lfs untrack' to clear .gitattributes" + exit 1 + fi +) +end_test From 712769b37c610a88fae6a3ed104120c998b1ac77 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Thu, 5 Apr 2018 12:17:37 -0700 Subject: [PATCH 21/94] commands/path.go: add documentation to trimCurrentPrefix --- commands/path.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/commands/path.go b/commands/path.go index 5ab636ee..4e7568cc 100644 --- a/commands/path.go +++ b/commands/path.go @@ -17,6 +17,12 @@ const ( nixPrefix = `./` ) +// trimCurrentPrefix removes a leading prefix of "./" or ".\" (referring to the +// current directory in a platform independent manner). +// +// It is useful for callers such as "git lfs track" and "git lfs untrack", that +// wish to compare filepaths and/or attributes patterns without cleaning across +// multiple platforms. func trimCurrentPrefix(p string) string { if strings.HasPrefix(p, windowsPrefix) { return strings.TrimPrefix(p, windowsPrefix) From 79f72cf57ca195093c94e18dc725c790465120a0 Mon Sep 17 00:00:00 2001 From: Steffen Prohaska Date: Sat, 7 Apr 2018 13:37:57 +0200 Subject: [PATCH 22/94] Add hint that file:// URLs require a standalone transfer agent Local remotes can only work with a standalone transfer agent. This commit adds a hint that refers to the documentation for details. The output of `git lfs fetch`, for example, now looks like: ``` fetch: Fetching reference refs/heads/master Downloading LFS objects: 0% (0/1), 0 B | 0 B/s hint: The remote resolves to a file:// URL, which can only work with a hint: standalone transfer agent. See section "Using a Custom Transfer Type hint: without the API server" in custom-transfers.md for details. batch request: missing protocol: "file:///..." error: failed to fetch some objects from 'file:///...' ``` The hint is printed in `NewRequest()`, when it is clear that an actual request is about to fail. A potential alternative would be to print the hint earlier, for example in `NewManifest()` or `NewEndpoint()`. But being too eager could cause printing spurious hints that would not be followed by an error, which might be confusing. Signed-off-by: Steffen Prohaska --- lfsapi/client.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/lfsapi/client.go b/lfsapi/client.go index ce20c3ab..de69d70a 100644 --- a/lfsapi/client.go +++ b/lfsapi/client.go @@ -27,7 +27,18 @@ var ( httpRE = regexp.MustCompile(`\Ahttps?://`) ) +var hintFileUrl = strings.TrimSpace(` +hint: The remote resolves to a file:// URL, which can only work with a +hint: standalone transfer agent. See section "Using a Custom Transfer Type +hint: without the API server" in custom-transfers.md for details. +`) + func (c *Client) NewRequest(method string, e Endpoint, suffix string, body interface{}) (*http.Request, error) { + if strings.HasPrefix(e.Url, "file://") { + // Initial `\n` to avoid overprinting `Downloading LFS...`. + fmt.Fprintf(os.Stderr, "\n%s\n", hintFileUrl) + } + sshRes, err := c.SSH.Resolve(e, method) if err != nil { tracerx.Printf("ssh: %s failed, error: %s, message: %s", From 074822305694dec7a8d8afe5a2f9c8c0f4f3c60b Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 9 Apr 2018 14:44:44 -0700 Subject: [PATCH 23/94] README.md: note the correct PackageCloud URL --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f18eac50..47800d62 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ You can install the Git LFS client in several different ways, depending on your setup and preferences. * **Linux users**. Debian and RPM packages are available from - [PackageCloud](https://packagecloud.io/git-lfs/install). + [PackageCloud](https://packagecloud.io/github/install). * **macOS users**. [Homebrew](https://brew.sh) bottles are distributed, and can be installed via `brew install git-lfs`. * **Windows users**. Chocolatey packages are distributed, and can be installed From 3105d041616b95b2e786a395cfc3a4caa141ab8b Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 9 Apr 2018 14:49:54 -0700 Subject: [PATCH 24/94] README.md: PackageCloud typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 47800d62..f8005055 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ You can install the Git LFS client in several different ways, depending on your setup and preferences. * **Linux users**. Debian and RPM packages are available from - [PackageCloud](https://packagecloud.io/github/install). + [PackageCloud](https://packagecloud.io/github/git-lfs/install). * **macOS users**. [Homebrew](https://brew.sh) bottles are distributed, and can be installed via `brew install git-lfs`. * **Windows users**. Chocolatey packages are distributed, and can be installed From 156d3fa9a8ba0f74a867b24114c76f112e39afe0 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 9 Apr 2018 14:51:12 -0700 Subject: [PATCH 25/94] script/packagecloud.rb: release on Ubuntu Bionic --- script/packagecloud.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/script/packagecloud.rb b/script/packagecloud.rb index 6a57347a..1b8b1382 100644 --- a/script/packagecloud.rb +++ b/script/packagecloud.rb @@ -62,6 +62,7 @@ $distro_name_map = { ubuntu/yakkety ubuntu/zesty ubuntu/artful + ubuntu/bionic ), } From 9292790d05f9344742d458d5b5558beef1f843da Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Thu, 12 Apr 2018 11:44:35 -0700 Subject: [PATCH 26/94] glide.yaml: update github.com/spf13/pflag --- glide.lock | 6 +- glide.yaml | 2 +- vendor/github.com/spf13/pflag/.gitignore | 2 + vendor/github.com/spf13/pflag/.travis.yml | 19 +- vendor/github.com/spf13/pflag/README.md | 80 +- vendor/github.com/spf13/pflag/bool.go | 15 +- vendor/github.com/spf13/pflag/bool_slice.go | 147 +++ .../github.com/spf13/pflag/bool_slice_test.go | 215 +++++ vendor/github.com/spf13/pflag/bool_test.go | 7 +- vendor/github.com/spf13/pflag/bytes.go | 105 +++ vendor/github.com/spf13/pflag/bytes_test.go | 72 ++ vendor/github.com/spf13/pflag/count.go | 34 +- vendor/github.com/spf13/pflag/count_test.go | 9 +- vendor/github.com/spf13/pflag/duration.go | 8 +- .../github.com/spf13/pflag/duration_slice.go | 128 +++ .../spf13/pflag/duration_slice_test.go | 165 ++++ vendor/github.com/spf13/pflag/example_test.go | 79 +- vendor/github.com/spf13/pflag/flag.go | 869 ++++++++++++++---- vendor/github.com/spf13/pflag/flag_test.go | 512 ++++++++++- vendor/github.com/spf13/pflag/float32.go | 15 +- vendor/github.com/spf13/pflag/float64.go | 15 +- vendor/github.com/spf13/pflag/golangflag.go | 105 +++ .../github.com/spf13/pflag/golangflag_test.go | 47 + vendor/github.com/spf13/pflag/int.go | 15 +- vendor/github.com/spf13/pflag/int16.go | 88 ++ vendor/github.com/spf13/pflag/int32.go | 15 +- vendor/github.com/spf13/pflag/int64.go | 15 +- vendor/github.com/spf13/pflag/int8.go | 15 +- vendor/github.com/spf13/pflag/int_slice.go | 12 +- .../github.com/spf13/pflag/int_slice_test.go | 13 +- vendor/github.com/spf13/pflag/ip.go | 10 +- vendor/github.com/spf13/pflag/ip_slice.go | 148 +++ .../github.com/spf13/pflag/ip_slice_test.go | 222 +++++ vendor/github.com/spf13/pflag/ipmask.go | 10 +- vendor/github.com/spf13/pflag/ipnet.go | 24 +- .../github.com/spf13/pflag/printusage_test.go | 74 ++ vendor/github.com/spf13/pflag/string.go | 12 +- vendor/github.com/spf13/pflag/string_array.go | 103 +++ .../spf13/pflag/string_array_test.go | 233 +++++ vendor/github.com/spf13/pflag/string_slice.go | 72 +- .../spf13/pflag/string_slice_test.go | 112 +++ vendor/github.com/spf13/pflag/uint.go | 15 +- vendor/github.com/spf13/pflag/uint16.go | 17 +- vendor/github.com/spf13/pflag/uint32.go | 19 +- vendor/github.com/spf13/pflag/uint64.go | 15 +- vendor/github.com/spf13/pflag/uint8.go | 15 +- vendor/github.com/spf13/pflag/uint_slice.go | 126 +++ .../github.com/spf13/pflag/uint_slice_test.go | 161 ++++ vendor/github.com/spf13/pflag/verify/all.sh | 69 ++ vendor/github.com/spf13/pflag/verify/gofmt.sh | 19 + .../github.com/spf13/pflag/verify/golint.sh | 15 + 51 files changed, 3839 insertions(+), 481 deletions(-) create mode 100644 vendor/github.com/spf13/pflag/.gitignore create mode 100644 vendor/github.com/spf13/pflag/bool_slice.go create mode 100644 vendor/github.com/spf13/pflag/bool_slice_test.go create mode 100644 vendor/github.com/spf13/pflag/bytes.go create mode 100644 vendor/github.com/spf13/pflag/bytes_test.go create mode 100644 vendor/github.com/spf13/pflag/duration_slice.go create mode 100644 vendor/github.com/spf13/pflag/duration_slice_test.go create mode 100644 vendor/github.com/spf13/pflag/golangflag.go create mode 100644 vendor/github.com/spf13/pflag/golangflag_test.go create mode 100644 vendor/github.com/spf13/pflag/int16.go create mode 100644 vendor/github.com/spf13/pflag/ip_slice.go create mode 100644 vendor/github.com/spf13/pflag/ip_slice_test.go create mode 100644 vendor/github.com/spf13/pflag/printusage_test.go create mode 100644 vendor/github.com/spf13/pflag/string_array.go create mode 100644 vendor/github.com/spf13/pflag/string_array_test.go create mode 100644 vendor/github.com/spf13/pflag/uint_slice.go create mode 100644 vendor/github.com/spf13/pflag/uint_slice_test.go create mode 100755 vendor/github.com/spf13/pflag/verify/all.sh create mode 100755 vendor/github.com/spf13/pflag/verify/gofmt.sh create mode 100755 vendor/github.com/spf13/pflag/verify/golint.sh diff --git a/glide.lock b/glide.lock index a4cb1f48..326fe58d 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ -hash: bad2138ca7787101a7a23af2464319cc580f4285e90c07d11eb9f90ad3bb9604 -updated: 2018-02-27T14:39:39.133796-08:00 +hash: 4d534cebec7c429b863d7e5dbe03b3b6d92ac662e2c106cd6cf0534882c65c7b +updated: 2018-04-12T11:44:32.221586-07:00 imports: - name: github.com/alexbrainman/sspi version: 4729b3d4d8581b2db83864d1018926e4154f9406 @@ -32,7 +32,7 @@ imports: - name: github.com/spf13/cobra version: c55cdf33856a08e4822738728b41783292812889 - name: github.com/spf13/pflag - version: 580b9be06c33d8ba9dcc8757ea56b7642472c2f5 + version: 583c0c0531f06d5278b7d917446061adc344b5cd - name: github.com/stretchr/testify version: 6cb3b85ef5a0efef77caef88363ec4d4b5c0976d subpackages: diff --git a/glide.yaml b/glide.yaml index eee8a77a..be0fc82a 100644 --- a/glide.yaml +++ b/glide.yaml @@ -15,7 +15,7 @@ import: - package: github.com/spf13/cobra version: c55cdf33856a08e4822738728b41783292812889 - package: github.com/spf13/pflag - version: 580b9be06c33d8ba9dcc8757ea56b7642472c2f5 + version: 583c0c0531f06d5278b7d917446061adc344b5cd - package: github.com/stretchr/testify version: 6cb3b85ef5a0efef77caef88363ec4d4b5c0976d - package: github.com/ThomsonReutersEikon/go-ntlm diff --git a/vendor/github.com/spf13/pflag/.gitignore b/vendor/github.com/spf13/pflag/.gitignore new file mode 100644 index 00000000..c3da2901 --- /dev/null +++ b/vendor/github.com/spf13/pflag/.gitignore @@ -0,0 +1,2 @@ +.idea/* + diff --git a/vendor/github.com/spf13/pflag/.travis.yml b/vendor/github.com/spf13/pflag/.travis.yml index c4d88e37..f8a63b30 100644 --- a/vendor/github.com/spf13/pflag/.travis.yml +++ b/vendor/github.com/spf13/pflag/.travis.yml @@ -3,6 +3,19 @@ sudo: false language: go go: - - 1.3 - - 1.4 - - tip + - 1.7.3 + - 1.8.1 + - tip + +matrix: + allow_failures: + - go: tip + +install: + - go get github.com/golang/lint/golint + - export PATH=$GOPATH/bin:$PATH + - go install ./... + +script: + - verify/all.sh -v + - go test ./... diff --git a/vendor/github.com/spf13/pflag/README.md b/vendor/github.com/spf13/pflag/README.md index deee9316..b052414d 100644 --- a/vendor/github.com/spf13/pflag/README.md +++ b/vendor/github.com/spf13/pflag/README.md @@ -1,4 +1,6 @@ [![Build Status](https://travis-ci.org/spf13/pflag.svg?branch=master)](https://travis-ci.org/spf13/pflag) +[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/pflag)](https://goreportcard.com/report/github.com/spf13/pflag) +[![GoDoc](https://godoc.org/github.com/spf13/pflag?status.svg)](https://godoc.org/github.com/spf13/pflag) ## Description @@ -85,7 +87,7 @@ fmt.Println("flagvar has value ", flagvar) ``` There are helpers function to get values later if you have the FlagSet but -it was difficult to keep up with all of the the flag pointers in your code. +it was difficult to keep up with all of the flag pointers in your code. If you have a pflag.FlagSet with a flag called 'flagname' of type int you can use GetInt() to get the int value. But notice that 'flagname' must exist and it must be an int. GetString("flagname") will fail. @@ -106,9 +108,9 @@ that give one-letter shorthands for flags. You can use these by appending var ip = flag.IntP("flagname", "f", 1234, "help message") var flagvar bool func init() { - flag.BoolVarP("boolname", "b", true, "help message") + flag.BoolVarP(&flagvar, "boolname", "b", true, "help message") } -flag.VarP(&flagVar, "varname", "v", 1234, "help message") +flag.VarP(&flagVal, "varname", "v", "help message") ``` Shorthand letters can be used with single dashes on the command line. @@ -216,13 +218,79 @@ func aliasNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName { myFlagSet.SetNormalizeFunc(aliasNormalizeFunc) ``` +## Deprecating a flag or its shorthand +It is possible to deprecate a flag, or just its shorthand. Deprecating a flag/shorthand hides it from help text and prints a usage message when the deprecated flag/shorthand is used. + +**Example #1**: You want to deprecate a flag named "badflag" as well as inform the users what flag they should use instead. +```go +// deprecate a flag by specifying its name and a usage message +flags.MarkDeprecated("badflag", "please use --good-flag instead") +``` +This hides "badflag" from help text, and prints `Flag --badflag has been deprecated, please use --good-flag instead` when "badflag" is used. + +**Example #2**: You want to keep a flag name "noshorthandflag" but deprecate its shortname "n". +```go +// deprecate a flag shorthand by specifying its flag name and a usage message +flags.MarkShorthandDeprecated("noshorthandflag", "please use --noshorthandflag only") +``` +This hides the shortname "n" from help text, and prints `Flag shorthand -n has been deprecated, please use --noshorthandflag only` when the shorthand "n" is used. + +Note that usage message is essential here, and it should not be empty. + +## Hidden flags +It is possible to mark a flag as hidden, meaning it will still function as normal, however will not show up in usage/help text. + +**Example**: You have a flag named "secretFlag" that you need for internal use only and don't want it showing up in help text, or for its usage text to be available. +```go +// hide a flag by specifying its name +flags.MarkHidden("secretFlag") +``` + +## Disable sorting of flags +`pflag` allows you to disable sorting of flags for help and usage message. + +**Example**: +```go +flags.BoolP("verbose", "v", false, "verbose output") +flags.String("coolflag", "yeaah", "it's really cool flag") +flags.Int("usefulflag", 777, "sometimes it's very useful") +flags.SortFlags = false +flags.PrintDefaults() +``` +**Output**: +``` + -v, --verbose verbose output + --coolflag string it's really cool flag (default "yeaah") + --usefulflag int sometimes it's very useful (default 777) +``` + + +## Supporting Go flags when using pflag +In order to support flags defined using Go's `flag` package, they must be added to the `pflag` flagset. This is usually necessary +to support flags defined by third-party dependencies (e.g. `golang/glog`). + +**Example**: You want to add the Go flags to the `CommandLine` flagset +```go +import ( + goflag "flag" + flag "github.com/spf13/pflag" +) + +var ip *int = flag.Int("flagname", 1234, "help message for flagname") + +func main() { + flag.CommandLine.AddGoFlagSet(goflag.CommandLine) + flag.Parse() +} +``` + ## More info You can see the full reference documentation of the pflag package [at godoc.org][3], or through go's standard documentation system by running `godoc -http=:6060` and browsing to -[http://localhost:6060/pkg/github.com/ogier/pflag][2] after +[http://localhost:6060/pkg/github.com/spf13/pflag][2] after installation. -[2]: http://localhost:6060/pkg/github.com/ogier/pflag -[3]: http://godoc.org/github.com/ogier/pflag +[2]: http://localhost:6060/pkg/github.com/spf13/pflag +[3]: http://godoc.org/github.com/spf13/pflag diff --git a/vendor/github.com/spf13/pflag/bool.go b/vendor/github.com/spf13/pflag/bool.go index 04c9b5af..c4c5c0bf 100644 --- a/vendor/github.com/spf13/pflag/bool.go +++ b/vendor/github.com/spf13/pflag/bool.go @@ -1,9 +1,6 @@ package pflag -import ( - "fmt" - "strconv" -) +import "strconv" // optional interface to indicate boolean flags that can be // supplied without "=value" text @@ -30,7 +27,7 @@ func (b *boolValue) Type() string { return "bool" } -func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) } +func (b *boolValue) String() string { return strconv.FormatBool(bool(*b)) } func (b *boolValue) IsBoolFlag() bool { return true } @@ -53,7 +50,7 @@ func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) { f.BoolVarP(p, name, "", value, usage) } -// Like BoolVar, but accepts a shorthand letter that can be used after a single dash. +// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) { flag := f.VarPF(newBoolValue(value, p), name, shorthand, usage) flag.NoOptDefVal = "true" @@ -65,7 +62,7 @@ func BoolVar(p *bool, name string, value bool, usage string) { BoolVarP(p, name, "", value, usage) } -// Like BoolVar, but accepts a shorthand letter that can be used after a single dash. +// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash. func BoolVarP(p *bool, name, shorthand string, value bool, usage string) { flag := CommandLine.VarPF(newBoolValue(value, p), name, shorthand, usage) flag.NoOptDefVal = "true" @@ -77,7 +74,7 @@ func (f *FlagSet) Bool(name string, value bool, usage string) *bool { return f.BoolP(name, "", value, usage) } -// Like Bool, but accepts a shorthand letter that can be used after a single dash. +// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool { p := new(bool) f.BoolVarP(p, name, shorthand, value, usage) @@ -90,7 +87,7 @@ func Bool(name string, value bool, usage string) *bool { return BoolP(name, "", value, usage) } -// Like Bool, but accepts a shorthand letter that can be used after a single dash. +// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash. func BoolP(name, shorthand string, value bool, usage string) *bool { b := CommandLine.BoolP(name, shorthand, value, usage) return b diff --git a/vendor/github.com/spf13/pflag/bool_slice.go b/vendor/github.com/spf13/pflag/bool_slice.go new file mode 100644 index 00000000..5af02f1a --- /dev/null +++ b/vendor/github.com/spf13/pflag/bool_slice.go @@ -0,0 +1,147 @@ +package pflag + +import ( + "io" + "strconv" + "strings" +) + +// -- boolSlice Value +type boolSliceValue struct { + value *[]bool + changed bool +} + +func newBoolSliceValue(val []bool, p *[]bool) *boolSliceValue { + bsv := new(boolSliceValue) + bsv.value = p + *bsv.value = val + return bsv +} + +// Set converts, and assigns, the comma-separated boolean argument string representation as the []bool value of this flag. +// If Set is called on a flag that already has a []bool assigned, the newly converted values will be appended. +func (s *boolSliceValue) Set(val string) error { + + // remove all quote characters + rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "") + + // read flag arguments with CSV parser + boolStrSlice, err := readAsCSV(rmQuote.Replace(val)) + if err != nil && err != io.EOF { + return err + } + + // parse boolean values into slice + out := make([]bool, 0, len(boolStrSlice)) + for _, boolStr := range boolStrSlice { + b, err := strconv.ParseBool(strings.TrimSpace(boolStr)) + if err != nil { + return err + } + out = append(out, b) + } + + if !s.changed { + *s.value = out + } else { + *s.value = append(*s.value, out...) + } + + s.changed = true + + return nil +} + +// Type returns a string that uniquely represents this flag's type. +func (s *boolSliceValue) Type() string { + return "boolSlice" +} + +// String defines a "native" format for this boolean slice flag value. +func (s *boolSliceValue) String() string { + + boolStrSlice := make([]string, len(*s.value)) + for i, b := range *s.value { + boolStrSlice[i] = strconv.FormatBool(b) + } + + out, _ := writeAsCSV(boolStrSlice) + + return "[" + out + "]" +} + +func boolSliceConv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // Empty string would cause a slice with one (empty) entry + if len(val) == 0 { + return []bool{}, nil + } + ss := strings.Split(val, ",") + out := make([]bool, len(ss)) + for i, t := range ss { + var err error + out[i], err = strconv.ParseBool(t) + if err != nil { + return nil, err + } + } + return out, nil +} + +// GetBoolSlice returns the []bool value of a flag with the given name. +func (f *FlagSet) GetBoolSlice(name string) ([]bool, error) { + val, err := f.getFlagType(name, "boolSlice", boolSliceConv) + if err != nil { + return []bool{}, err + } + return val.([]bool), nil +} + +// BoolSliceVar defines a boolSlice flag with specified name, default value, and usage string. +// The argument p points to a []bool variable in which to store the value of the flag. +func (f *FlagSet) BoolSliceVar(p *[]bool, name string, value []bool, usage string) { + f.VarP(newBoolSliceValue(value, p), name, "", usage) +} + +// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) { + f.VarP(newBoolSliceValue(value, p), name, shorthand, usage) +} + +// BoolSliceVar defines a []bool flag with specified name, default value, and usage string. +// The argument p points to a []bool variable in which to store the value of the flag. +func BoolSliceVar(p *[]bool, name string, value []bool, usage string) { + CommandLine.VarP(newBoolSliceValue(value, p), name, "", usage) +} + +// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash. +func BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) { + CommandLine.VarP(newBoolSliceValue(value, p), name, shorthand, usage) +} + +// BoolSlice defines a []bool flag with specified name, default value, and usage string. +// The return value is the address of a []bool variable that stores the value of the flag. +func (f *FlagSet) BoolSlice(name string, value []bool, usage string) *[]bool { + p := []bool{} + f.BoolSliceVarP(&p, name, "", value, usage) + return &p +} + +// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool { + p := []bool{} + f.BoolSliceVarP(&p, name, shorthand, value, usage) + return &p +} + +// BoolSlice defines a []bool flag with specified name, default value, and usage string. +// The return value is the address of a []bool variable that stores the value of the flag. +func BoolSlice(name string, value []bool, usage string) *[]bool { + return CommandLine.BoolSliceP(name, "", value, usage) +} + +// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash. +func BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool { + return CommandLine.BoolSliceP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/bool_slice_test.go b/vendor/github.com/spf13/pflag/bool_slice_test.go new file mode 100644 index 00000000..b617dd23 --- /dev/null +++ b/vendor/github.com/spf13/pflag/bool_slice_test.go @@ -0,0 +1,215 @@ +package pflag + +import ( + "fmt" + "strconv" + "strings" + "testing" +) + +func setUpBSFlagSet(bsp *[]bool) *FlagSet { + f := NewFlagSet("test", ContinueOnError) + f.BoolSliceVar(bsp, "bs", []bool{}, "Command separated list!") + return f +} + +func setUpBSFlagSetWithDefault(bsp *[]bool) *FlagSet { + f := NewFlagSet("test", ContinueOnError) + f.BoolSliceVar(bsp, "bs", []bool{false, true}, "Command separated list!") + return f +} + +func TestEmptyBS(t *testing.T) { + var bs []bool + f := setUpBSFlagSet(&bs) + err := f.Parse([]string{}) + if err != nil { + t.Fatal("expected no error; got", err) + } + + getBS, err := f.GetBoolSlice("bs") + if err != nil { + t.Fatal("got an error from GetBoolSlice():", err) + } + if len(getBS) != 0 { + t.Fatalf("got bs %v with len=%d but expected length=0", getBS, len(getBS)) + } +} + +func TestBS(t *testing.T) { + var bs []bool + f := setUpBSFlagSet(&bs) + + vals := []string{"1", "F", "TRUE", "0"} + arg := fmt.Sprintf("--bs=%s", strings.Join(vals, ",")) + err := f.Parse([]string{arg}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range bs { + b, err := strconv.ParseBool(vals[i]) + if err != nil { + t.Fatalf("got error: %v", err) + } + if b != v { + t.Fatalf("expected is[%d] to be %s but got: %t", i, vals[i], v) + } + } + getBS, err := f.GetBoolSlice("bs") + if err != nil { + t.Fatalf("got error: %v", err) + } + for i, v := range getBS { + b, err := strconv.ParseBool(vals[i]) + if err != nil { + t.Fatalf("got error: %v", err) + } + if b != v { + t.Fatalf("expected bs[%d] to be %s but got: %t from GetBoolSlice", i, vals[i], v) + } + } +} + +func TestBSDefault(t *testing.T) { + var bs []bool + f := setUpBSFlagSetWithDefault(&bs) + + vals := []string{"false", "T"} + + err := f.Parse([]string{}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range bs { + b, err := strconv.ParseBool(vals[i]) + if err != nil { + t.Fatalf("got error: %v", err) + } + if b != v { + t.Fatalf("expected bs[%d] to be %t from GetBoolSlice but got: %t", i, b, v) + } + } + + getBS, err := f.GetBoolSlice("bs") + if err != nil { + t.Fatal("got an error from GetBoolSlice():", err) + } + for i, v := range getBS { + b, err := strconv.ParseBool(vals[i]) + if err != nil { + t.Fatal("got an error from GetBoolSlice():", err) + } + if b != v { + t.Fatalf("expected bs[%d] to be %t from GetBoolSlice but got: %t", i, b, v) + } + } +} + +func TestBSWithDefault(t *testing.T) { + var bs []bool + f := setUpBSFlagSetWithDefault(&bs) + + vals := []string{"FALSE", "1"} + arg := fmt.Sprintf("--bs=%s", strings.Join(vals, ",")) + err := f.Parse([]string{arg}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range bs { + b, err := strconv.ParseBool(vals[i]) + if err != nil { + t.Fatalf("got error: %v", err) + } + if b != v { + t.Fatalf("expected bs[%d] to be %t but got: %t", i, b, v) + } + } + + getBS, err := f.GetBoolSlice("bs") + if err != nil { + t.Fatal("got an error from GetBoolSlice():", err) + } + for i, v := range getBS { + b, err := strconv.ParseBool(vals[i]) + if err != nil { + t.Fatalf("got error: %v", err) + } + if b != v { + t.Fatalf("expected bs[%d] to be %t from GetBoolSlice but got: %t", i, b, v) + } + } +} + +func TestBSCalledTwice(t *testing.T) { + var bs []bool + f := setUpBSFlagSet(&bs) + + in := []string{"T,F", "T"} + expected := []bool{true, false, true} + argfmt := "--bs=%s" + arg1 := fmt.Sprintf(argfmt, in[0]) + arg2 := fmt.Sprintf(argfmt, in[1]) + err := f.Parse([]string{arg1, arg2}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range bs { + if expected[i] != v { + t.Fatalf("expected bs[%d] to be %t but got %t", i, expected[i], v) + } + } +} + +func TestBSBadQuoting(t *testing.T) { + + tests := []struct { + Want []bool + FlagArg []string + }{ + { + Want: []bool{true, false, true}, + FlagArg: []string{"1", "0", "true"}, + }, + { + Want: []bool{true, false}, + FlagArg: []string{"True", "F"}, + }, + { + Want: []bool{true, false}, + FlagArg: []string{"T", "0"}, + }, + { + Want: []bool{true, false}, + FlagArg: []string{"1", "0"}, + }, + { + Want: []bool{true, false, false}, + FlagArg: []string{"true,false", "false"}, + }, + { + Want: []bool{true, false, false, true, false, true, false}, + FlagArg: []string{`"true,false,false,1,0, T"`, " false "}, + }, + { + Want: []bool{false, false, true, false, true, false, true}, + FlagArg: []string{`"0, False, T,false , true,F"`, "true"}, + }, + } + + for i, test := range tests { + + var bs []bool + f := setUpBSFlagSet(&bs) + + if err := f.Parse([]string{fmt.Sprintf("--bs=%s", strings.Join(test.FlagArg, ","))}); err != nil { + t.Fatalf("flag parsing failed with error: %s\nparsing:\t%#v\nwant:\t\t%#v", + err, test.FlagArg, test.Want[i]) + } + + for j, b := range bs { + if b != test.Want[j] { + t.Fatalf("bad value parsed for test %d on bool %d:\nwant:\t%t\ngot:\t%t", i, j, test.Want[j], b) + } + } + } +} diff --git a/vendor/github.com/spf13/pflag/bool_test.go b/vendor/github.com/spf13/pflag/bool_test.go index afd25ae2..a4319e79 100644 --- a/vendor/github.com/spf13/pflag/bool_test.go +++ b/vendor/github.com/spf13/pflag/bool_test.go @@ -6,7 +6,6 @@ package pflag import ( "bytes" - "fmt" "strconv" "testing" ) @@ -48,7 +47,7 @@ func (v *triStateValue) String() string { if *v == triStateMaybe { return strTriStateMaybe } - return fmt.Sprintf("%v", bool(*v == triStateTrue)) + return strconv.FormatBool(*v == triStateTrue) } // The type of the flag as required by the pflag.Value interface @@ -172,9 +171,9 @@ func TestBoolP(t *testing.T) { t.Error("expected no error, got ", err) } if *b != true { - t.Errorf("expected b=true got b=%s", b) + t.Errorf("expected b=true got b=%v", *b) } if *c != false { - t.Errorf("expect c=false got c=%s", c) + t.Errorf("expect c=false got c=%v", *c) } } diff --git a/vendor/github.com/spf13/pflag/bytes.go b/vendor/github.com/spf13/pflag/bytes.go new file mode 100644 index 00000000..12c58db9 --- /dev/null +++ b/vendor/github.com/spf13/pflag/bytes.go @@ -0,0 +1,105 @@ +package pflag + +import ( + "encoding/hex" + "fmt" + "strings" +) + +// BytesHex adapts []byte for use as a flag. Value of flag is HEX encoded +type bytesHexValue []byte + +func (bytesHex bytesHexValue) String() string { + return fmt.Sprintf("%X", []byte(bytesHex)) +} + +func (bytesHex *bytesHexValue) Set(value string) error { + bin, err := hex.DecodeString(strings.TrimSpace(value)) + + if err != nil { + return err + } + + *bytesHex = bin + + return nil +} + +func (*bytesHexValue) Type() string { + return "bytesHex" +} + +func newBytesHexValue(val []byte, p *[]byte) *bytesHexValue { + *p = val + return (*bytesHexValue)(p) +} + +func bytesHexConv(sval string) (interface{}, error) { + + bin, err := hex.DecodeString(sval) + + if err == nil { + return bin, nil + } + + return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err) +} + +// GetBytesHex return the []byte value of a flag with the given name +func (f *FlagSet) GetBytesHex(name string) ([]byte, error) { + val, err := f.getFlagType(name, "bytesHex", bytesHexConv) + + if err != nil { + return []byte{}, err + } + + return val.([]byte), nil +} + +// BytesHexVar defines an []byte flag with specified name, default value, and usage string. +// The argument p points to an []byte variable in which to store the value of the flag. +func (f *FlagSet) BytesHexVar(p *[]byte, name string, value []byte, usage string) { + f.VarP(newBytesHexValue(value, p), name, "", usage) +} + +// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) { + f.VarP(newBytesHexValue(value, p), name, shorthand, usage) +} + +// BytesHexVar defines an []byte flag with specified name, default value, and usage string. +// The argument p points to an []byte variable in which to store the value of the flag. +func BytesHexVar(p *[]byte, name string, value []byte, usage string) { + CommandLine.VarP(newBytesHexValue(value, p), name, "", usage) +} + +// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash. +func BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) { + CommandLine.VarP(newBytesHexValue(value, p), name, shorthand, usage) +} + +// BytesHex defines an []byte flag with specified name, default value, and usage string. +// The return value is the address of an []byte variable that stores the value of the flag. +func (f *FlagSet) BytesHex(name string, value []byte, usage string) *[]byte { + p := new([]byte) + f.BytesHexVarP(p, name, "", value, usage) + return p +} + +// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) BytesHexP(name, shorthand string, value []byte, usage string) *[]byte { + p := new([]byte) + f.BytesHexVarP(p, name, shorthand, value, usage) + return p +} + +// BytesHex defines an []byte flag with specified name, default value, and usage string. +// The return value is the address of an []byte variable that stores the value of the flag. +func BytesHex(name string, value []byte, usage string) *[]byte { + return CommandLine.BytesHexP(name, "", value, usage) +} + +// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash. +func BytesHexP(name, shorthand string, value []byte, usage string) *[]byte { + return CommandLine.BytesHexP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/bytes_test.go b/vendor/github.com/spf13/pflag/bytes_test.go new file mode 100644 index 00000000..cc4a769d --- /dev/null +++ b/vendor/github.com/spf13/pflag/bytes_test.go @@ -0,0 +1,72 @@ +package pflag + +import ( + "fmt" + "os" + "testing" +) + +func setUpBytesHex(bytesHex *[]byte) *FlagSet { + f := NewFlagSet("test", ContinueOnError) + f.BytesHexVar(bytesHex, "bytes", []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, "Some bytes in HEX") + f.BytesHexVarP(bytesHex, "bytes2", "B", []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, "Some bytes in HEX") + return f +} + +func TestBytesHex(t *testing.T) { + testCases := []struct { + input string + success bool + expected string + }{ + /// Positive cases + {"", true, ""}, // Is empty string OK ? + {"01", true, "01"}, + {"0101", true, "0101"}, + {"1234567890abcdef", true, "1234567890ABCDEF"}, + {"1234567890ABCDEF", true, "1234567890ABCDEF"}, + + // Negative cases + {"0", false, ""}, // Short string + {"000", false, ""}, /// Odd-length string + {"qq", false, ""}, /// non-hex character + } + + devnull, _ := os.Open(os.DevNull) + os.Stderr = devnull + + for i := range testCases { + var bytesHex []byte + f := setUpBytesHex(&bytesHex) + + tc := &testCases[i] + + // --bytes + args := []string{ + fmt.Sprintf("--bytes=%s", tc.input), + fmt.Sprintf("-B %s", tc.input), + fmt.Sprintf("--bytes2=%s", tc.input), + } + + for _, arg := range args { + err := f.Parse([]string{arg}) + + if err != nil && tc.success == true { + t.Errorf("expected success, got %q", err) + continue + } else if err == nil && tc.success == false { + // bytesHex, err := f.GetBytesHex("bytes") + t.Errorf("expected failure while processing %q", tc.input) + continue + } else if tc.success { + bytesHex, err := f.GetBytesHex("bytes") + if err != nil { + t.Errorf("Got error trying to fetch the IP flag: %v", err) + } + if fmt.Sprintf("%X", bytesHex) != tc.expected { + t.Errorf("expected %q, got '%X'", tc.expected, bytesHex) + } + } + } + } +} diff --git a/vendor/github.com/spf13/pflag/count.go b/vendor/github.com/spf13/pflag/count.go index d0613688..aa126e44 100644 --- a/vendor/github.com/spf13/pflag/count.go +++ b/vendor/github.com/spf13/pflag/count.go @@ -1,9 +1,6 @@ package pflag -import ( - "fmt" - "strconv" -) +import "strconv" // -- count Value type countValue int @@ -14,13 +11,13 @@ func newCountValue(val int, p *int) *countValue { } func (i *countValue) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 64) - // -1 means that no specific value was passed, so increment - if v == -1 { + // "+1" means that no specific value was passed, so increment + if s == "+1" { *i = countValue(*i + 1) - } else { - *i = countValue(v) + return nil } + v, err := strconv.ParseInt(s, 0, 0) + *i = countValue(v) return err } @@ -28,7 +25,7 @@ func (i *countValue) Type() string { return "count" } -func (i *countValue) String() string { return fmt.Sprintf("%v", *i) } +func (i *countValue) String() string { return strconv.Itoa(int(*i)) } func countConv(sval string) (interface{}, error) { i, err := strconv.Atoi(sval) @@ -38,6 +35,7 @@ func countConv(sval string) (interface{}, error) { return i, nil } +// GetCount return the int value of a flag with the given name func (f *FlagSet) GetCount(name string) (int, error) { val, err := f.getFlagType(name, "count", countConv) if err != nil { @@ -46,39 +44,53 @@ func (f *FlagSet) GetCount(name string) (int, error) { return val.(int), nil } +// CountVar defines a count flag with specified name, default value, and usage string. +// The argument p points to an int variable in which to store the value of the flag. +// A count flag will add 1 to its value evey time it is found on the command line func (f *FlagSet) CountVar(p *int, name string, usage string) { f.CountVarP(p, name, "", usage) } +// CountVarP is like CountVar only take a shorthand for the flag name. func (f *FlagSet) CountVarP(p *int, name, shorthand string, usage string) { flag := f.VarPF(newCountValue(0, p), name, shorthand, usage) - flag.NoOptDefVal = "-1" + flag.NoOptDefVal = "+1" } +// CountVar like CountVar only the flag is placed on the CommandLine instead of a given flag set func CountVar(p *int, name string, usage string) { CommandLine.CountVar(p, name, usage) } +// CountVarP is like CountVar only take a shorthand for the flag name. func CountVarP(p *int, name, shorthand string, usage string) { CommandLine.CountVarP(p, name, shorthand, usage) } +// Count defines a count flag with specified name, default value, and usage string. +// The return value is the address of an int variable that stores the value of the flag. +// A count flag will add 1 to its value evey time it is found on the command line func (f *FlagSet) Count(name string, usage string) *int { p := new(int) f.CountVarP(p, name, "", usage) return p } +// CountP is like Count only takes a shorthand for the flag name. func (f *FlagSet) CountP(name, shorthand string, usage string) *int { p := new(int) f.CountVarP(p, name, shorthand, usage) return p } +// Count defines a count flag with specified name, default value, and usage string. +// The return value is the address of an int variable that stores the value of the flag. +// A count flag will add 1 to its value evey time it is found on the command line func Count(name string, usage string) *int { return CommandLine.CountP(name, "", usage) } +// CountP is like Count only takes a shorthand for the flag name. func CountP(name, shorthand string, usage string) *int { return CommandLine.CountP(name, shorthand, usage) } diff --git a/vendor/github.com/spf13/pflag/count_test.go b/vendor/github.com/spf13/pflag/count_test.go index 716765cb..3785d375 100644 --- a/vendor/github.com/spf13/pflag/count_test.go +++ b/vendor/github.com/spf13/pflag/count_test.go @@ -1,13 +1,10 @@ package pflag import ( - "fmt" "os" "testing" ) -var _ = fmt.Printf - func setUpCount(c *int) *FlagSet { f := NewFlagSet("test", ContinueOnError) f.CountVarP(c, "verbose", "v", "a counter") @@ -20,10 +17,14 @@ func TestCount(t *testing.T) { success bool expected int }{ + {[]string{}, true, 0}, + {[]string{"-v"}, true, 1}, {[]string{"-vvv"}, true, 3}, {[]string{"-v", "-v", "-v"}, true, 3}, {[]string{"-v", "--verbose", "-v"}, true, 3}, {[]string{"-v=3", "-v"}, true, 4}, + {[]string{"--verbose=0"}, true, 0}, + {[]string{"-v=0"}, true, 0}, {[]string{"-v=a"}, false, 0}, } @@ -48,7 +49,7 @@ func TestCount(t *testing.T) { t.Errorf("Got error trying to fetch the counter flag") } if c != tc.expected { - t.Errorf("expected %q, got %q", tc.expected, c) + t.Errorf("expected %d, got %d", tc.expected, c) } } } diff --git a/vendor/github.com/spf13/pflag/duration.go b/vendor/github.com/spf13/pflag/duration.go index 382ffd3c..e9debef8 100644 --- a/vendor/github.com/spf13/pflag/duration.go +++ b/vendor/github.com/spf13/pflag/duration.go @@ -43,7 +43,7 @@ func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration f.VarP(newDurationValue(value, p), name, "", usage) } -// Like DurationVar, but accepts a shorthand letter that can be used after a single dash. +// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) { f.VarP(newDurationValue(value, p), name, shorthand, usage) } @@ -54,7 +54,7 @@ func DurationVar(p *time.Duration, name string, value time.Duration, usage strin CommandLine.VarP(newDurationValue(value, p), name, "", usage) } -// Like DurationVar, but accepts a shorthand letter that can be used after a single dash. +// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash. func DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) { CommandLine.VarP(newDurationValue(value, p), name, shorthand, usage) } @@ -67,7 +67,7 @@ func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time return p } -// Like Duration, but accepts a shorthand letter that can be used after a single dash. +// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration { p := new(time.Duration) f.DurationVarP(p, name, shorthand, value, usage) @@ -80,7 +80,7 @@ func Duration(name string, value time.Duration, usage string) *time.Duration { return CommandLine.DurationP(name, "", value, usage) } -// Like Duration, but accepts a shorthand letter that can be used after a single dash. +// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash. func DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration { return CommandLine.DurationP(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/duration_slice.go b/vendor/github.com/spf13/pflag/duration_slice.go new file mode 100644 index 00000000..52c6b6dc --- /dev/null +++ b/vendor/github.com/spf13/pflag/duration_slice.go @@ -0,0 +1,128 @@ +package pflag + +import ( + "fmt" + "strings" + "time" +) + +// -- durationSlice Value +type durationSliceValue struct { + value *[]time.Duration + changed bool +} + +func newDurationSliceValue(val []time.Duration, p *[]time.Duration) *durationSliceValue { + dsv := new(durationSliceValue) + dsv.value = p + *dsv.value = val + return dsv +} + +func (s *durationSliceValue) Set(val string) error { + ss := strings.Split(val, ",") + out := make([]time.Duration, len(ss)) + for i, d := range ss { + var err error + out[i], err = time.ParseDuration(d) + if err != nil { + return err + } + + } + if !s.changed { + *s.value = out + } else { + *s.value = append(*s.value, out...) + } + s.changed = true + return nil +} + +func (s *durationSliceValue) Type() string { + return "durationSlice" +} + +func (s *durationSliceValue) String() string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = fmt.Sprintf("%s", d) + } + return "[" + strings.Join(out, ",") + "]" +} + +func durationSliceConv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // Empty string would cause a slice with one (empty) entry + if len(val) == 0 { + return []time.Duration{}, nil + } + ss := strings.Split(val, ",") + out := make([]time.Duration, len(ss)) + for i, d := range ss { + var err error + out[i], err = time.ParseDuration(d) + if err != nil { + return nil, err + } + + } + return out, nil +} + +// GetDurationSlice returns the []time.Duration value of a flag with the given name +func (f *FlagSet) GetDurationSlice(name string) ([]time.Duration, error) { + val, err := f.getFlagType(name, "durationSlice", durationSliceConv) + if err != nil { + return []time.Duration{}, err + } + return val.([]time.Duration), nil +} + +// DurationSliceVar defines a durationSlice flag with specified name, default value, and usage string. +// The argument p points to a []time.Duration variable in which to store the value of the flag. +func (f *FlagSet) DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) { + f.VarP(newDurationSliceValue(value, p), name, "", usage) +} + +// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) { + f.VarP(newDurationSliceValue(value, p), name, shorthand, usage) +} + +// DurationSliceVar defines a duration[] flag with specified name, default value, and usage string. +// The argument p points to a duration[] variable in which to store the value of the flag. +func DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) { + CommandLine.VarP(newDurationSliceValue(value, p), name, "", usage) +} + +// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash. +func DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) { + CommandLine.VarP(newDurationSliceValue(value, p), name, shorthand, usage) +} + +// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string. +// The return value is the address of a []time.Duration variable that stores the value of the flag. +func (f *FlagSet) DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration { + p := []time.Duration{} + f.DurationSliceVarP(&p, name, "", value, usage) + return &p +} + +// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration { + p := []time.Duration{} + f.DurationSliceVarP(&p, name, shorthand, value, usage) + return &p +} + +// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string. +// The return value is the address of a []time.Duration variable that stores the value of the flag. +func DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration { + return CommandLine.DurationSliceP(name, "", value, usage) +} + +// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash. +func DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration { + return CommandLine.DurationSliceP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/duration_slice_test.go b/vendor/github.com/spf13/pflag/duration_slice_test.go new file mode 100644 index 00000000..489b012f --- /dev/null +++ b/vendor/github.com/spf13/pflag/duration_slice_test.go @@ -0,0 +1,165 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code ds governed by a BSD-style +// license that can be found in the LICENSE file. + +package pflag + +import ( + "fmt" + "strings" + "testing" + "time" +) + +func setUpDSFlagSet(dsp *[]time.Duration) *FlagSet { + f := NewFlagSet("test", ContinueOnError) + f.DurationSliceVar(dsp, "ds", []time.Duration{}, "Command separated list!") + return f +} + +func setUpDSFlagSetWithDefault(dsp *[]time.Duration) *FlagSet { + f := NewFlagSet("test", ContinueOnError) + f.DurationSliceVar(dsp, "ds", []time.Duration{0, 1}, "Command separated list!") + return f +} + +func TestEmptyDS(t *testing.T) { + var ds []time.Duration + f := setUpDSFlagSet(&ds) + err := f.Parse([]string{}) + if err != nil { + t.Fatal("expected no error; got", err) + } + + getDS, err := f.GetDurationSlice("ds") + if err != nil { + t.Fatal("got an error from GetDurationSlice():", err) + } + if len(getDS) != 0 { + t.Fatalf("got ds %v with len=%d but expected length=0", getDS, len(getDS)) + } +} + +func TestDS(t *testing.T) { + var ds []time.Duration + f := setUpDSFlagSet(&ds) + + vals := []string{"1ns", "2ms", "3m", "4h"} + arg := fmt.Sprintf("--ds=%s", strings.Join(vals, ",")) + err := f.Parse([]string{arg}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range ds { + d, err := time.ParseDuration(vals[i]) + if err != nil { + t.Fatalf("got error: %v", err) + } + if d != v { + t.Fatalf("expected ds[%d] to be %s but got: %d", i, vals[i], v) + } + } + getDS, err := f.GetDurationSlice("ds") + if err != nil { + t.Fatalf("got error: %v", err) + } + for i, v := range getDS { + d, err := time.ParseDuration(vals[i]) + if err != nil { + t.Fatalf("got error: %v", err) + } + if d != v { + t.Fatalf("expected ds[%d] to be %s but got: %d from GetDurationSlice", i, vals[i], v) + } + } +} + +func TestDSDefault(t *testing.T) { + var ds []time.Duration + f := setUpDSFlagSetWithDefault(&ds) + + vals := []string{"0s", "1ns"} + + err := f.Parse([]string{}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range ds { + d, err := time.ParseDuration(vals[i]) + if err != nil { + t.Fatalf("got error: %v", err) + } + if d != v { + t.Fatalf("expected ds[%d] to be %d but got: %d", i, d, v) + } + } + + getDS, err := f.GetDurationSlice("ds") + if err != nil { + t.Fatal("got an error from GetDurationSlice():", err) + } + for i, v := range getDS { + d, err := time.ParseDuration(vals[i]) + if err != nil { + t.Fatal("got an error from GetDurationSlice():", err) + } + if d != v { + t.Fatalf("expected ds[%d] to be %d from GetDurationSlice but got: %d", i, d, v) + } + } +} + +func TestDSWithDefault(t *testing.T) { + var ds []time.Duration + f := setUpDSFlagSetWithDefault(&ds) + + vals := []string{"1ns", "2ns"} + arg := fmt.Sprintf("--ds=%s", strings.Join(vals, ",")) + err := f.Parse([]string{arg}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range ds { + d, err := time.ParseDuration(vals[i]) + if err != nil { + t.Fatalf("got error: %v", err) + } + if d != v { + t.Fatalf("expected ds[%d] to be %d but got: %d", i, d, v) + } + } + + getDS, err := f.GetDurationSlice("ds") + if err != nil { + t.Fatal("got an error from GetDurationSlice():", err) + } + for i, v := range getDS { + d, err := time.ParseDuration(vals[i]) + if err != nil { + t.Fatalf("got error: %v", err) + } + if d != v { + t.Fatalf("expected ds[%d] to be %d from GetDurationSlice but got: %d", i, d, v) + } + } +} + +func TestDSCalledTwice(t *testing.T) { + var ds []time.Duration + f := setUpDSFlagSet(&ds) + + in := []string{"1ns,2ns", "3ns"} + expected := []time.Duration{1, 2, 3} + argfmt := "--ds=%s" + arg1 := fmt.Sprintf(argfmt, in[0]) + arg2 := fmt.Sprintf(argfmt, in[1]) + err := f.Parse([]string{arg1, arg2}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range ds { + if expected[i] != v { + t.Fatalf("expected ds[%d] to be %d but got: %d", i, expected[i], v) + } + } +} diff --git a/vendor/github.com/spf13/pflag/example_test.go b/vendor/github.com/spf13/pflag/example_test.go index 9be7a49f..abd7806f 100644 --- a/vendor/github.com/spf13/pflag/example_test.go +++ b/vendor/github.com/spf13/pflag/example_test.go @@ -2,76 +2,35 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// These examples demonstrate more intricate uses of the flag package. package pflag_test import ( - "errors" "fmt" - "strings" - "time" - flag "github.com/spf13/pflag" + "github.com/spf13/pflag" ) -// Example 1: A single string flag called "species" with default value "gopher". -var species = flag.String("species", "gopher", "the species we are studying") +func ExampleShorthandLookup() { + name := "verbose" + short := name[:1] -// Example 2: A flag with a shorthand letter. -var gopherType = flag.StringP("gopher_type", "g", "pocket", "the variety of gopher") + pflag.BoolP(name, short, false, "verbose output") -// Example 3: A user-defined flag type, a slice of durations. -type interval []time.Duration + // len(short) must be == 1 + flag := pflag.ShorthandLookup(short) -// String is the method to format the flag's value, part of the flag.Value interface. -// The String method's output will be used in diagnostics. -func (i *interval) String() string { - return fmt.Sprint(*i) + fmt.Println(flag.Name) } -func (i *interval) Type() string { - return "interval" -} - -// Set is the method to set the flag value, part of the flag.Value interface. -// Set's argument is a string to be parsed to set the flag. -// It's a comma-separated list, so we split it. -func (i *interval) Set(value string) error { - // If we wanted to allow the flag to be set multiple times, - // accumulating values, we would delete this if statement. - // That would permit usages such as - // -deltaT 10s -deltaT 15s - // and other combinations. - if len(*i) > 0 { - return errors.New("interval flag already set") - } - for _, dt := range strings.Split(value, ",") { - duration, err := time.ParseDuration(dt) - if err != nil { - return err - } - *i = append(*i, duration) - } - return nil -} - -// Define a flag to accumulate durations. Because it has a special type, -// we need to use the Var function and therefore create the flag during -// init. - -var intervalFlag interval - -func init() { - // Tie the command-line flag to the intervalFlag variable and - // set a usage message. - flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events") -} - -func Example() { - // All the interesting pieces are with the variables declared above, but - // to enable the flag package to see the flags defined there, one must - // execute, typically at the start of main (not init!): - // flag.Parse() - // We don't run it here because this is not a main function and - // the testing suite has already parsed the flags. +func ExampleFlagSet_ShorthandLookup() { + name := "verbose" + short := name[:1] + + fs := pflag.NewFlagSet("Example", pflag.ContinueOnError) + fs.BoolP(name, short, false, "verbose output") + + // len(short) must be == 1 + flag := fs.ShorthandLookup(short) + + fmt.Println(flag.Name) } diff --git a/vendor/github.com/spf13/pflag/flag.go b/vendor/github.com/spf13/pflag/flag.go index c45ad0f0..5eadc84e 100644 --- a/vendor/github.com/spf13/pflag/flag.go +++ b/vendor/github.com/spf13/pflag/flag.go @@ -3,104 +3,105 @@ // license that can be found in the LICENSE file. /* - pflag is a drop-in replacement for Go's flag package, implementing - POSIX/GNU-style --flags. +Package pflag is a drop-in replacement for Go's flag package, implementing +POSIX/GNU-style --flags. - pflag is compatible with the GNU extensions to the POSIX recommendations - for command-line options. See - http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html +pflag is compatible with the GNU extensions to the POSIX recommendations +for command-line options. See +http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html - Usage: +Usage: - pflag is a drop-in replacement of Go's native flag package. If you import - pflag under the name "flag" then all code should continue to function - with no changes. +pflag is a drop-in replacement of Go's native flag package. If you import +pflag under the name "flag" then all code should continue to function +with no changes. - import flag "github.com/ogier/pflag" + import flag "github.com/spf13/pflag" - There is one exception to this: if you directly instantiate the Flag struct - there is one more field "Shorthand" that you will need to set. - Most code never instantiates this struct directly, and instead uses - functions such as String(), BoolVar(), and Var(), and is therefore - unaffected. +There is one exception to this: if you directly instantiate the Flag struct +there is one more field "Shorthand" that you will need to set. +Most code never instantiates this struct directly, and instead uses +functions such as String(), BoolVar(), and Var(), and is therefore +unaffected. - Define flags using flag.String(), Bool(), Int(), etc. +Define flags using flag.String(), Bool(), Int(), etc. - This declares an integer flag, -flagname, stored in the pointer ip, with type *int. - var ip = flag.Int("flagname", 1234, "help message for flagname") - If you like, you can bind the flag to a variable using the Var() functions. - var flagvar int - func init() { - flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") - } - Or you can create custom flags that satisfy the Value interface (with - pointer receivers) and couple them to flag parsing by - flag.Var(&flagVal, "name", "help message for flagname") - For such flags, the default value is just the initial value of the variable. +This declares an integer flag, -flagname, stored in the pointer ip, with type *int. + var ip = flag.Int("flagname", 1234, "help message for flagname") +If you like, you can bind the flag to a variable using the Var() functions. + var flagvar int + func init() { + flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") + } +Or you can create custom flags that satisfy the Value interface (with +pointer receivers) and couple them to flag parsing by + flag.Var(&flagVal, "name", "help message for flagname") +For such flags, the default value is just the initial value of the variable. - After all flags are defined, call - flag.Parse() - to parse the command line into the defined flags. +After all flags are defined, call + flag.Parse() +to parse the command line into the defined flags. - Flags may then be used directly. If you're using the flags themselves, - they are all pointers; if you bind to variables, they're values. - fmt.Println("ip has value ", *ip) - fmt.Println("flagvar has value ", flagvar) +Flags may then be used directly. If you're using the flags themselves, +they are all pointers; if you bind to variables, they're values. + fmt.Println("ip has value ", *ip) + fmt.Println("flagvar has value ", flagvar) - After parsing, the arguments after the flag are available as the - slice flag.Args() or individually as flag.Arg(i). - The arguments are indexed from 0 through flag.NArg()-1. +After parsing, the arguments after the flag are available as the +slice flag.Args() or individually as flag.Arg(i). +The arguments are indexed from 0 through flag.NArg()-1. - The pflag package also defines some new functions that are not in flag, - that give one-letter shorthands for flags. You can use these by appending - 'P' to the name of any function that defines a flag. - var ip = flag.IntP("flagname", "f", 1234, "help message") - var flagvar bool - func init() { - flag.BoolVarP("boolname", "b", true, "help message") - } - flag.VarP(&flagVar, "varname", "v", 1234, "help message") - Shorthand letters can be used with single dashes on the command line. - Boolean shorthand flags can be combined with other shorthand flags. +The pflag package also defines some new functions that are not in flag, +that give one-letter shorthands for flags. You can use these by appending +'P' to the name of any function that defines a flag. + var ip = flag.IntP("flagname", "f", 1234, "help message") + var flagvar bool + func init() { + flag.BoolVarP("boolname", "b", true, "help message") + } + flag.VarP(&flagVar, "varname", "v", 1234, "help message") +Shorthand letters can be used with single dashes on the command line. +Boolean shorthand flags can be combined with other shorthand flags. - Command line flag syntax: - --flag // boolean flags only - --flag=x +Command line flag syntax: + --flag // boolean flags only + --flag=x - Unlike the flag package, a single dash before an option means something - different than a double dash. Single dashes signify a series of shorthand - letters for flags. All but the last shorthand letter must be boolean flags. - // boolean flags - -f - -abc - // non-boolean flags - -n 1234 - -Ifile - // mixed - -abcs "hello" - -abcn1234 +Unlike the flag package, a single dash before an option means something +different than a double dash. Single dashes signify a series of shorthand +letters for flags. All but the last shorthand letter must be boolean flags. + // boolean flags + -f + -abc + // non-boolean flags + -n 1234 + -Ifile + // mixed + -abcs "hello" + -abcn1234 - Flag parsing stops after the terminator "--". Unlike the flag package, - flags can be interspersed with arguments anywhere on the command line - before this terminator. +Flag parsing stops after the terminator "--". Unlike the flag package, +flags can be interspersed with arguments anywhere on the command line +before this terminator. - Integer flags accept 1234, 0664, 0x1234 and may be negative. - Boolean flags (in their long form) accept 1, 0, t, f, true, false, - TRUE, FALSE, True, False. - Duration flags accept any input valid for time.ParseDuration. +Integer flags accept 1234, 0664, 0x1234 and may be negative. +Boolean flags (in their long form) accept 1, 0, t, f, true, false, +TRUE, FALSE, True, False. +Duration flags accept any input valid for time.ParseDuration. - The default set of command-line flags is controlled by - top-level functions. The FlagSet type allows one to define - independent sets of flags, such as to implement subcommands - in a command-line interface. The methods of FlagSet are - analogous to the top-level functions for the command-line - flag set. +The default set of command-line flags is controlled by +top-level functions. The FlagSet type allows one to define +independent sets of flags, such as to implement subcommands +in a command-line interface. The methods of FlagSet are +analogous to the top-level functions for the command-line +flag set. */ package pflag import ( "bytes" "errors" + goflag "flag" "fmt" "io" "os" @@ -115,11 +116,20 @@ var ErrHelp = errors.New("pflag: help requested") type ErrorHandling int const ( + // ContinueOnError will return an err from Parse() if an error is found ContinueOnError ErrorHandling = iota + // ExitOnError will call os.Exit(2) if an error is found when parsing ExitOnError + // PanicOnError will panic() if an error is found when parsing flags PanicOnError ) +// ParseErrorsWhitelist defines the parsing errors that can be ignored +type ParseErrorsWhitelist struct { + // UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags + UnknownFlags bool +} + // NormalizedName is a flag name that has been normalized according to rules // for the FlagSet (e.g. making '-' and '_' equivalent). type NormalizedName string @@ -131,30 +141,45 @@ type FlagSet struct { // a custom error handler. Usage func() + // SortFlags is used to indicate, if user wants to have sorted flags in + // help/usage messages. + SortFlags bool + + // ParseErrorsWhitelist is used to configure a whitelist of errors + ParseErrorsWhitelist ParseErrorsWhitelist + name string parsed bool actual map[NormalizedName]*Flag + orderedActual []*Flag + sortedActual []*Flag formal map[NormalizedName]*Flag + orderedFormal []*Flag + sortedFormal []*Flag shorthands map[byte]*Flag args []string // arguments after flags - exitOnError bool // does the program exit if there's an error? + argsLenAtDash int // len(args) when a '--' was located when parsing, or -1 if no -- errorHandling ErrorHandling output io.Writer // nil means stderr; use out() accessor interspersed bool // allow interspersed option/non-option args normalizeNameFunc func(f *FlagSet, name string) NormalizedName + + addedGoFlagSets []*goflag.FlagSet } // A Flag represents the state of a flag. type Flag struct { - Name string // name as it appears on command line - Shorthand string // one-letter abbreviated flag - Usage string // help message - Value Value // value as set - DefValue string // default value (as text); for usage message - Changed bool // If the user set the value (or if left to default) - NoOptDefVal string //default value (as text); if the flag is on the command line without any options - Deprecated string // If this flag is deprecated, this string is the new or now thing to use - Annotations map[string][]string // used by cobra.Command bash autocomple code + Name string // name as it appears on command line + Shorthand string // one-letter abbreviated flag + Usage string // help message + Value Value // value as set + DefValue string // default value (as text); for usage message + Changed bool // If the user set the value (or if left to default) + NoOptDefVal string // default value (as text); if the flag is on the command line without any options + Deprecated string // If this flag is deprecated, this string is the new or now thing to use + Hidden bool // used by cobra.Command to allow flags to be hidden from help/usage text + ShorthandDeprecated string // If the shorthand of this flag is deprecated, this string is the new or now thing to use + Annotations map[string][]string // used by cobra.Command bash autocomple code } // Value is the interface to the dynamic value stored in a flag. @@ -181,16 +206,31 @@ func sortFlags(flags map[NormalizedName]*Flag) []*Flag { return result } +// SetNormalizeFunc allows you to add a function which can translate flag names. +// Flags added to the FlagSet will be translated and then when anything tries to +// look up the flag that will also be translated. So it would be possible to create +// a flag named "getURL" and have it translated to "geturl". A user could then pass +// "--getUrl" which may also be translated to "geturl" and everything will work. func (f *FlagSet) SetNormalizeFunc(n func(f *FlagSet, name string) NormalizedName) { f.normalizeNameFunc = n - for k, v := range f.formal { - delete(f.formal, k) - nname := f.normalizeFlagName(string(k)) - f.formal[nname] = v - v.Name = string(nname) + f.sortedFormal = f.sortedFormal[:0] + for fname, flag := range f.formal { + nname := f.normalizeFlagName(flag.Name) + if fname == nname { + continue + } + flag.Name = string(nname) + delete(f.formal, fname) + f.formal[nname] = flag + if _, set := f.actual[fname]; set { + delete(f.actual, fname) + f.actual[nname] = flag + } } } +// GetNormalizeFunc returns the previously set NormalizeFunc of a function which +// does no translation, if not set previously. func (f *FlagSet) GetNormalizeFunc() func(f *FlagSet, name string) NormalizedName { if f.normalizeNameFunc != nil { return f.normalizeNameFunc @@ -216,34 +256,78 @@ func (f *FlagSet) SetOutput(output io.Writer) { f.output = output } -// VisitAll visits the flags in lexicographical order, calling fn for each. +// VisitAll visits the flags in lexicographical order or +// in primordial order if f.SortFlags is false, calling fn for each. // It visits all flags, even those not set. func (f *FlagSet) VisitAll(fn func(*Flag)) { - for _, flag := range sortFlags(f.formal) { + if len(f.formal) == 0 { + return + } + + var flags []*Flag + if f.SortFlags { + if len(f.formal) != len(f.sortedFormal) { + f.sortedFormal = sortFlags(f.formal) + } + flags = f.sortedFormal + } else { + flags = f.orderedFormal + } + + for _, flag := range flags { fn(flag) } } +// HasFlags returns a bool to indicate if the FlagSet has any flags defined. func (f *FlagSet) HasFlags() bool { return len(f.formal) > 0 } -// VisitAll visits the command-line flags in lexicographical order, calling -// fn for each. It visits all flags, even those not set. +// HasAvailableFlags returns a bool to indicate if the FlagSet has any flags +// that are not hidden. +func (f *FlagSet) HasAvailableFlags() bool { + for _, flag := range f.formal { + if !flag.Hidden { + return true + } + } + return false +} + +// VisitAll visits the command-line flags in lexicographical order or +// in primordial order if f.SortFlags is false, calling fn for each. +// It visits all flags, even those not set. func VisitAll(fn func(*Flag)) { CommandLine.VisitAll(fn) } -// Visit visits the flags in lexicographical order, calling fn for each. +// Visit visits the flags in lexicographical order or +// in primordial order if f.SortFlags is false, calling fn for each. // It visits only those flags that have been set. func (f *FlagSet) Visit(fn func(*Flag)) { - for _, flag := range sortFlags(f.actual) { + if len(f.actual) == 0 { + return + } + + var flags []*Flag + if f.SortFlags { + if len(f.actual) != len(f.sortedActual) { + f.sortedActual = sortFlags(f.actual) + } + flags = f.sortedActual + } else { + flags = f.orderedActual + } + + for _, flag := range flags { fn(flag) } } -// Visit visits the command-line flags in lexicographical order, calling fn -// for each. It visits only those flags that have been set. +// Visit visits the command-line flags in lexicographical order or +// in primordial order if f.SortFlags is false, calling fn for each. +// It visits only those flags that have been set. func Visit(fn func(*Flag)) { CommandLine.Visit(fn) } @@ -253,6 +337,22 @@ func (f *FlagSet) Lookup(name string) *Flag { return f.lookup(f.normalizeFlagName(name)) } +// ShorthandLookup returns the Flag structure of the short handed flag, +// returning nil if none exists. +// It panics, if len(name) > 1. +func (f *FlagSet) ShorthandLookup(name string) *Flag { + if name == "" { + return nil + } + if len(name) > 1 { + msg := fmt.Sprintf("can not look up shorthand which is more than one ASCII character: %q", name) + fmt.Fprintf(f.out(), msg) + panic(msg) + } + c := name[0] + return f.shorthands[c] +} + // lookup returns the Flag structure of the named flag, returning nil if none exists. func (f *FlagSet) lookup(name NormalizedName) *Flag { return f.formal[name] @@ -279,13 +379,52 @@ func (f *FlagSet) getFlagType(name string, ftype string, convFunc func(sval stri return result, nil } -// Mark a flag deprecated in your program +// ArgsLenAtDash will return the length of f.Args at the moment when a -- was +// found during arg parsing. This allows your program to know which args were +// before the -- and which came after. +func (f *FlagSet) ArgsLenAtDash() int { + return f.argsLenAtDash +} + +// MarkDeprecated indicated that a flag is deprecated in your program. It will +// continue to function but will not show up in help or usage messages. Using +// this flag will also print the given usageMessage. func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error { flag := f.Lookup(name) if flag == nil { return fmt.Errorf("flag %q does not exist", name) } + if usageMessage == "" { + return fmt.Errorf("deprecated message for flag %q must be set", name) + } flag.Deprecated = usageMessage + flag.Hidden = true + return nil +} + +// MarkShorthandDeprecated will mark the shorthand of a flag deprecated in your +// program. It will continue to function but will not show up in help or usage +// messages. Using this flag will also print the given usageMessage. +func (f *FlagSet) MarkShorthandDeprecated(name string, usageMessage string) error { + flag := f.Lookup(name) + if flag == nil { + return fmt.Errorf("flag %q does not exist", name) + } + if usageMessage == "" { + return fmt.Errorf("deprecated message for flag %q must be set", name) + } + flag.ShorthandDeprecated = usageMessage + return nil +} + +// MarkHidden sets a flag to 'hidden' in your program. It will continue to +// function but will not show up in help or usage messages. +func (f *FlagSet) MarkHidden(name string) error { + flag := f.Lookup(name) + if flag == nil { + return fmt.Errorf("flag %q does not exist", name) + } + flag.Hidden = true return nil } @@ -295,6 +434,12 @@ func Lookup(name string) *Flag { return CommandLine.Lookup(name) } +// ShorthandLookup returns the Flag structure of the short handed flag, +// returning nil if none exists. +func ShorthandLookup(name string) *Flag { + return CommandLine.ShorthandLookup(name) +} + // Set sets the value of the named flag. func (f *FlagSet) Set(name, value string) error { normalName := f.normalizeFlagName(name) @@ -302,21 +447,37 @@ func (f *FlagSet) Set(name, value string) error { if !ok { return fmt.Errorf("no such flag -%v", name) } + err := flag.Value.Set(value) if err != nil { - return err + var flagName string + if flag.Shorthand != "" && flag.ShorthandDeprecated == "" { + flagName = fmt.Sprintf("-%s, --%s", flag.Shorthand, flag.Name) + } else { + flagName = fmt.Sprintf("--%s", flag.Name) + } + return fmt.Errorf("invalid argument %q for %q flag: %v", value, flagName, err) } - if f.actual == nil { - f.actual = make(map[NormalizedName]*Flag) + + if !flag.Changed { + if f.actual == nil { + f.actual = make(map[NormalizedName]*Flag) + } + f.actual[normalName] = flag + f.orderedActual = append(f.orderedActual, flag) + + flag.Changed = true } - f.actual[normalName] = flag - flag.Changed = true - if len(flag.Deprecated) > 0 { - fmt.Fprintf(os.Stderr, "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated) + + if flag.Deprecated != "" { + fmt.Fprintf(f.out(), "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated) } return nil } +// SetAnnotation allows one to set arbitrary annotations on a flag in the FlagSet. +// This is sometimes used by spf13/cobra programs which want to generate additional +// bash completion information. func (f *FlagSet) SetAnnotation(name, key string, values []string) error { normalName := f.normalizeFlagName(name) flag, ok := f.formal[normalName] @@ -330,6 +491,8 @@ func (f *FlagSet) SetAnnotation(name, key string, values []string) error { return nil } +// Changed returns true if the flag was explicitly set during Parse() and false +// otherwise func (f *FlagSet) Changed(name string) bool { flag := f.Lookup(name) // If a flag doesn't exist, it wasn't changed.... @@ -347,54 +510,233 @@ func Set(name, value string) error { // PrintDefaults prints, to standard error unless configured // otherwise, the default values of all defined flags in the set. func (f *FlagSet) PrintDefaults() { - f.VisitAll(func(flag *Flag) { - if len(flag.Deprecated) > 0 { - return - } - format := "" - // ex: w/ option string argument '-%s, --%s[=%q]: %s\n' - if len(flag.Shorthand) > 0 { - format = " -%s, --%s" - } else { - format = " %s --%s" - } - if len(flag.NoOptDefVal) > 0 { - format = format + "[" - } - if _, ok := flag.Value.(*stringValue); ok { - format = format + "=%q" - } else { - format = format + "=%s" - } - if len(flag.NoOptDefVal) > 0 { - format = format + "]" - } - format = format + ": %s\n" - fmt.Fprintf(f.out(), format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage) - }) + usages := f.FlagUsages() + fmt.Fprint(f.out(), usages) } -func (f *FlagSet) FlagUsages() string { - x := new(bytes.Buffer) +// defaultIsZeroValue returns true if the default value for this flag represents +// a zero value. +func (f *Flag) defaultIsZeroValue() bool { + switch f.Value.(type) { + case boolFlag: + return f.DefValue == "false" + case *durationValue: + // Beginning in Go 1.7, duration zero values are "0s" + return f.DefValue == "0" || f.DefValue == "0s" + case *intValue, *int8Value, *int32Value, *int64Value, *uintValue, *uint8Value, *uint16Value, *uint32Value, *uint64Value, *countValue, *float32Value, *float64Value: + return f.DefValue == "0" + case *stringValue: + return f.DefValue == "" + case *ipValue, *ipMaskValue, *ipNetValue: + return f.DefValue == "" + case *intSliceValue, *stringSliceValue, *stringArrayValue: + return f.DefValue == "[]" + default: + switch f.Value.String() { + case "false": + return true + case "": + return true + case "": + return true + case "0": + return true + } + return false + } +} +// UnquoteUsage extracts a back-quoted name from the usage +// string for a flag and returns it and the un-quoted usage. +// Given "a `name` to show" it returns ("name", "a name to show"). +// If there are no back quotes, the name is an educated guess of the +// type of the flag's value, or the empty string if the flag is boolean. +func UnquoteUsage(flag *Flag) (name string, usage string) { + // Look for a back-quoted name, but avoid the strings package. + usage = flag.Usage + for i := 0; i < len(usage); i++ { + if usage[i] == '`' { + for j := i + 1; j < len(usage); j++ { + if usage[j] == '`' { + name = usage[i+1 : j] + usage = usage[:i] + name + usage[j+1:] + return name, usage + } + } + break // Only one back quote; use type name. + } + } + + name = flag.Value.Type() + switch name { + case "bool": + name = "" + case "float64": + name = "float" + case "int64": + name = "int" + case "uint64": + name = "uint" + case "stringSlice": + name = "strings" + case "intSlice": + name = "ints" + case "uintSlice": + name = "uints" + case "boolSlice": + name = "bools" + } + + return +} + +// Splits the string `s` on whitespace into an initial substring up to +// `i` runes in length and the remainder. Will go `slop` over `i` if +// that encompasses the entire string (which allows the caller to +// avoid short orphan words on the final line). +func wrapN(i, slop int, s string) (string, string) { + if i+slop > len(s) { + return s, "" + } + + w := strings.LastIndexAny(s[:i], " \t\n") + if w <= 0 { + return s, "" + } + nlPos := strings.LastIndex(s[:i], "\n") + if nlPos > 0 && nlPos < w { + return s[:nlPos], s[nlPos+1:] + } + return s[:w], s[w+1:] +} + +// Wraps the string `s` to a maximum width `w` with leading indent +// `i`. The first line is not indented (this is assumed to be done by +// caller). Pass `w` == 0 to do no wrapping +func wrap(i, w int, s string) string { + if w == 0 { + return strings.Replace(s, "\n", "\n"+strings.Repeat(" ", i), -1) + } + + // space between indent i and end of line width w into which + // we should wrap the text. + wrap := w - i + + var r, l string + + // Not enough space for sensible wrapping. Wrap as a block on + // the next line instead. + if wrap < 24 { + i = 16 + wrap = w - i + r += "\n" + strings.Repeat(" ", i) + } + // If still not enough space then don't even try to wrap. + if wrap < 24 { + return strings.Replace(s, "\n", r, -1) + } + + // Try to avoid short orphan words on the final line, by + // allowing wrapN to go a bit over if that would fit in the + // remainder of the line. + slop := 5 + wrap = wrap - slop + + // Handle first line, which is indented by the caller (or the + // special case above) + l, s = wrapN(wrap, slop, s) + r = r + strings.Replace(l, "\n", "\n"+strings.Repeat(" ", i), -1) + + // Now wrap the rest + for s != "" { + var t string + + t, s = wrapN(wrap, slop, s) + r = r + "\n" + strings.Repeat(" ", i) + strings.Replace(t, "\n", "\n"+strings.Repeat(" ", i), -1) + } + + return r + +} + +// FlagUsagesWrapped returns a string containing the usage information +// for all flags in the FlagSet. Wrapped to `cols` columns (0 for no +// wrapping) +func (f *FlagSet) FlagUsagesWrapped(cols int) string { + buf := new(bytes.Buffer) + + lines := make([]string, 0, len(f.formal)) + + maxlen := 0 f.VisitAll(func(flag *Flag) { - if len(flag.Deprecated) > 0 { + if flag.Hidden { return } - format := "--%s=%s: %s\n" - if _, ok := flag.Value.(*stringValue); ok { - // put quotes on the value - format = "--%s=%q: %s\n" - } - if len(flag.Shorthand) > 0 { - format = " -%s, " + format + + line := "" + if flag.Shorthand != "" && flag.ShorthandDeprecated == "" { + line = fmt.Sprintf(" -%s, --%s", flag.Shorthand, flag.Name) } else { - format = " %s " + format + line = fmt.Sprintf(" --%s", flag.Name) } - fmt.Fprintf(x, format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage) + + varname, usage := UnquoteUsage(flag) + if varname != "" { + line += " " + varname + } + if flag.NoOptDefVal != "" { + switch flag.Value.Type() { + case "string": + line += fmt.Sprintf("[=\"%s\"]", flag.NoOptDefVal) + case "bool": + if flag.NoOptDefVal != "true" { + line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) + } + case "count": + if flag.NoOptDefVal != "+1" { + line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) + } + default: + line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) + } + } + + // This special character will be replaced with spacing once the + // correct alignment is calculated + line += "\x00" + if len(line) > maxlen { + maxlen = len(line) + } + + line += usage + if !flag.defaultIsZeroValue() { + if flag.Value.Type() == "string" { + line += fmt.Sprintf(" (default %q)", flag.DefValue) + } else { + line += fmt.Sprintf(" (default %s)", flag.DefValue) + } + } + if len(flag.Deprecated) != 0 { + line += fmt.Sprintf(" (DEPRECATED: %s)", flag.Deprecated) + } + + lines = append(lines, line) }) - return x.String() + for _, line := range lines { + sidx := strings.Index(line, "\x00") + spacing := strings.Repeat(" ", maxlen-sidx) + // maxlen + 2 comes from + 1 for the \x00 and + 1 for the (deliberate) off-by-one in maxlen-sidx + fmt.Fprintln(buf, line[:sidx], spacing, wrap(maxlen+2, cols, line[sidx+1:])) + } + + return buf.String() +} + +// FlagUsages returns a string containing the usage information for all flags in +// the FlagSet +func (f *FlagSet) FlagUsages() string { + return f.FlagUsagesWrapped(0) } // PrintDefaults prints to standard error the default values of all defined command-line flags. @@ -414,6 +756,8 @@ func defaultUsage(f *FlagSet) { // Usage prints to standard error a usage message documenting all defined command-line flags. // The function is a variable that may be changed to point to a custom function. +// By default it prints a simple header and calls PrintDefaults; for details about the +// format of the output and how to control it, see the documentation for PrintDefaults. var Usage = func() { fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) PrintDefaults() @@ -462,7 +806,7 @@ func (f *FlagSet) Var(value Value, name string, usage string) { f.VarP(value, name, "", usage) } -// Like VarP, but returns the flag created +// VarPF is like VarP, but returns the flag created func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag { // Remember the default value as a string; it won't change. flag := &Flag{ @@ -476,17 +820,17 @@ func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag { return flag } -// Like Var, but accepts a shorthand letter that can be used after a single dash. +// VarP is like Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) VarP(value Value, name, shorthand, usage string) { - _ = f.VarPF(value, name, shorthand, usage) + f.VarPF(value, name, shorthand, usage) } +// AddFlag will add the flag to the FlagSet func (f *FlagSet) AddFlag(flag *Flag) { - // Call normalizeFlagName function only once - var normalizedFlagName NormalizedName = f.normalizeFlagName(flag.Name) + normalizedFlagName := f.normalizeFlagName(flag.Name) - _, alreadythere := f.formal[normalizedFlagName] - if alreadythere { + _, alreadyThere := f.formal[normalizedFlagName] + if alreadyThere { msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name) fmt.Fprintln(f.out(), msg) panic(msg) // Happens only if flags are declared with identical names @@ -497,26 +841,42 @@ func (f *FlagSet) AddFlag(flag *Flag) { flag.Name = string(normalizedFlagName) f.formal[normalizedFlagName] = flag + f.orderedFormal = append(f.orderedFormal, flag) - if len(flag.Shorthand) == 0 { + if flag.Shorthand == "" { return } if len(flag.Shorthand) > 1 { - fmt.Fprintf(f.out(), "%s shorthand more than ASCII character: %s\n", f.name, flag.Shorthand) - panic("shorthand is more than one character") + msg := fmt.Sprintf("%q shorthand is more than one ASCII character", flag.Shorthand) + fmt.Fprintf(f.out(), msg) + panic(msg) } if f.shorthands == nil { f.shorthands = make(map[byte]*Flag) } c := flag.Shorthand[0] - old, alreadythere := f.shorthands[c] - if alreadythere { - fmt.Fprintf(f.out(), "%s shorthand reused: %q for %s already used for %s\n", f.name, c, flag.Name, old.Name) - panic("shorthand redefinition") + used, alreadyThere := f.shorthands[c] + if alreadyThere { + msg := fmt.Sprintf("unable to redefine %q shorthand in %q flagset: it's already used for %q flag", c, f.name, used.Name) + fmt.Fprintf(f.out(), msg) + panic(msg) } f.shorthands[c] = flag } +// AddFlagSet adds one FlagSet to another. If a flag is already present in f +// the flag from newSet will be ignored. +func (f *FlagSet) AddFlagSet(newSet *FlagSet) { + if newSet == nil { + return + } + newSet.VisitAll(func(flag *Flag) { + if f.Lookup(flag.Name) == nil { + f.AddFlag(flag) + } + }) +} + // Var defines a flag with the specified name and usage string. The type and // value of the flag are represented by the first argument, of type Value, which // typically holds a user-defined implementation of Value. For instance, the @@ -527,7 +887,7 @@ func Var(value Value, name string, usage string) { CommandLine.VarP(value, name, "", usage) } -// Like Var, but accepts a shorthand letter that can be used after a single dash. +// VarP is like Var, but accepts a shorthand letter that can be used after a single dash. func VarP(value Value, name, shorthand, usage string) { CommandLine.VarP(value, name, shorthand, usage) } @@ -536,8 +896,10 @@ func VarP(value Value, name, shorthand, usage string) { // returns the error. func (f *FlagSet) failf(format string, a ...interface{}) error { err := fmt.Errorf(format, a...) - fmt.Fprintln(f.out(), err) - f.usage() + if f.errorHandling != ContinueOnError { + fmt.Fprintln(f.out(), err) + f.usage() + } return err } @@ -553,45 +915,61 @@ func (f *FlagSet) usage() { } } -func (f *FlagSet) setFlag(flag *Flag, value string, origArg string) error { - if err := flag.Value.Set(value); err != nil { - return f.failf("invalid argument %q for %s: %v", value, origArg, err) +//--unknown (args will be empty) +//--unknown --next-flag ... (args will be --next-flag ...) +//--unknown arg ... (args will be arg ...) +func stripUnknownFlagValue(args []string) []string { + if len(args) == 0 { + //--unknown + return args } - // mark as visited for Visit() - if f.actual == nil { - f.actual = make(map[NormalizedName]*Flag) + + first := args[0] + if first[0] == '-' { + //--unknown --next-flag ... + return args } - f.actual[f.normalizeFlagName(flag.Name)] = flag - flag.Changed = true - if len(flag.Deprecated) > 0 { - fmt.Fprintf(os.Stderr, "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated) - } - return nil + + //--unknown arg ... (args will be arg ...) + return args[1:] } -func (f *FlagSet) parseLongArg(s string, args []string) (a []string, err error) { +func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) { a = args name := s[2:] if len(name) == 0 || name[0] == '-' || name[0] == '=' { err = f.failf("bad flag syntax: %s", s) return } + split := strings.SplitN(name, "=", 2) name = split[0] - flag, alreadythere := f.formal[f.normalizeFlagName(name)] - if !alreadythere { - if name == "help" { // special case for nice help message. + flag, exists := f.formal[f.normalizeFlagName(name)] + + if !exists { + switch { + case name == "help": f.usage() return a, ErrHelp + case f.ParseErrorsWhitelist.UnknownFlags: + // --unknown=unknownval arg ... + // we do not want to lose arg in this case + if len(split) >= 2 { + return a, nil + } + + return stripUnknownFlagValue(a), nil + default: + err = f.failf("unknown flag: --%s", name) + return } - err = f.failf("unknown flag: --%s", name) - return } + var value string if len(split) == 2 { // '--flag=arg' value = split[1] - } else if len(flag.NoOptDefVal) > 0 { + } else if flag.NoOptDefVal != "" { // '--flag' (arg was optional) value = flag.NoOptDefVal } else if len(a) > 0 { @@ -603,52 +981,86 @@ func (f *FlagSet) parseLongArg(s string, args []string) (a []string, err error) err = f.failf("flag needs an argument: %s", s) return } - err = f.setFlag(flag, value, s) + + err = fn(flag, value) + if err != nil { + f.failf(err.Error()) + } return } -func (f *FlagSet) parseSingleShortArg(shorthands string, args []string) (outShorts string, outArgs []string, err error) { +func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) { + if strings.HasPrefix(shorthands, "test.") { + return + } + outArgs = args outShorts = shorthands[1:] c := shorthands[0] - flag, alreadythere := f.shorthands[c] - if !alreadythere { - if c == 'h' { // special case for nice help message. + flag, exists := f.shorthands[c] + if !exists { + switch { + case c == 'h': f.usage() err = ErrHelp return + case f.ParseErrorsWhitelist.UnknownFlags: + // '-f=arg arg ...' + // we do not want to lose arg in this case + if len(shorthands) > 2 && shorthands[1] == '=' { + outShorts = "" + return + } + + outArgs = stripUnknownFlagValue(outArgs) + return + default: + err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands) + return } - //TODO continue on error - err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands) - return } + var value string if len(shorthands) > 2 && shorthands[1] == '=' { + // '-f=arg' value = shorthands[2:] outShorts = "" - } else if len(flag.NoOptDefVal) > 0 { + } else if flag.NoOptDefVal != "" { + // '-f' (arg was optional) value = flag.NoOptDefVal } else if len(shorthands) > 1 { + // '-farg' value = shorthands[1:] outShorts = "" } else if len(args) > 0 { + // '-f arg' value = args[0] outArgs = args[1:] } else { + // '-f' (arg was required) err = f.failf("flag needs an argument: %q in -%s", c, shorthands) return } - err = f.setFlag(flag, value, shorthands) + + if flag.ShorthandDeprecated != "" { + fmt.Fprintf(f.out(), "Flag shorthand -%s has been deprecated, %s\n", flag.Shorthand, flag.ShorthandDeprecated) + } + + err = fn(flag, value) + if err != nil { + f.failf(err.Error()) + } return } -func (f *FlagSet) parseShortArg(s string, args []string) (a []string, err error) { +func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []string, err error) { a = args shorthands := s[1:] + // "shorthands" can be a series of shorthand letters of flags (e.g. "-vvv"). for len(shorthands) > 0 { - shorthands, a, err = f.parseSingleShortArg(shorthands, args) + shorthands, a, err = f.parseSingleShortArg(shorthands, args, fn) if err != nil { return } @@ -657,7 +1069,7 @@ func (f *FlagSet) parseShortArg(s string, args []string) (a []string, err error) return } -func (f *FlagSet) parseArgs(args []string) (err error) { +func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) { for len(args) > 0 { s := args[0] args = args[1:] @@ -673,12 +1085,13 @@ func (f *FlagSet) parseArgs(args []string) (err error) { if s[1] == '-' { if len(s) == 2 { // "--" terminates the flags + f.argsLenAtDash = len(f.args) f.args = append(f.args, args...) break } - args, err = f.parseLongArg(s, args) + args, err = f.parseLongArg(s, args, fn) } else { - args, err = f.parseShortArg(s, args) + args, err = f.parseShortArg(s, args, fn) } if err != nil { return @@ -692,9 +1105,50 @@ func (f *FlagSet) parseArgs(args []string) (err error) { // are defined and before flags are accessed by the program. // The return value will be ErrHelp if -help was set but not defined. func (f *FlagSet) Parse(arguments []string) error { + if f.addedGoFlagSets != nil { + for _, goFlagSet := range f.addedGoFlagSets { + goFlagSet.Parse(nil) + } + } + f.parsed = true + + if len(arguments) < 0 { + return nil + } + + f.args = make([]string, 0, len(arguments)) + + set := func(flag *Flag, value string) error { + return f.Set(flag.Name, value) + } + + err := f.parseArgs(arguments, set) + if err != nil { + switch f.errorHandling { + case ContinueOnError: + return err + case ExitOnError: + fmt.Println(err) + os.Exit(2) + case PanicOnError: + panic(err) + } + } + return nil +} + +type parseFunc func(flag *Flag, value string) error + +// ParseAll parses flag definitions from the argument list, which should not +// include the command name. The arguments for fn are flag and value. Must be +// called after all flags in the FlagSet are defined and before flags are +// accessed by the program. The return value will be ErrHelp if -help was set +// but not defined. +func (f *FlagSet) ParseAll(arguments []string, fn func(flag *Flag, value string) error) error { f.parsed = true f.args = make([]string, 0, len(arguments)) - err := f.parseArgs(arguments) + + err := f.parseArgs(arguments, fn) if err != nil { switch f.errorHandling { case ContinueOnError: @@ -720,7 +1174,15 @@ func Parse() { CommandLine.Parse(os.Args[1:]) } -// Whether to support interspersed option/non-option arguments. +// ParseAll parses the command-line flags from os.Args[1:] and called fn for each. +// The arguments for fn are flag and value. Must be called after all flags are +// defined and before flags are accessed by the program. +func ParseAll(fn func(flag *Flag, value string) error) { + // Ignore errors; CommandLine is set for ExitOnError. + CommandLine.ParseAll(os.Args[1:], fn) +} + +// SetInterspersed sets whether to support interspersed option/non-option arguments. func SetInterspersed(interspersed bool) { CommandLine.SetInterspersed(interspersed) } @@ -730,21 +1192,23 @@ func Parsed() bool { return CommandLine.Parsed() } -// The default set of command-line flags, parsed from os.Args. +// CommandLine is the default set of command-line flags, parsed from os.Args. var CommandLine = NewFlagSet(os.Args[0], ExitOnError) -// NewFlagSet returns a new, empty flag set with the specified name and -// error handling property. +// NewFlagSet returns a new, empty flag set with the specified name, +// error handling property and SortFlags set to true. func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet { f := &FlagSet{ name: name, errorHandling: errorHandling, + argsLenAtDash: -1, interspersed: true, + SortFlags: true, } return f } -// Whether to support interspersed option/non-option arguments. +// SetInterspersed sets whether to support interspersed option/non-option arguments. func (f *FlagSet) SetInterspersed(interspersed bool) { f.interspersed = interspersed } @@ -755,4 +1219,5 @@ func (f *FlagSet) SetInterspersed(interspersed bool) { func (f *FlagSet) Init(name string, errorHandling ErrorHandling) { f.name = name f.errorHandling = errorHandling + f.argsLenAtDash = -1 } diff --git a/vendor/github.com/spf13/pflag/flag_test.go b/vendor/github.com/spf13/pflag/flag_test.go index e654553c..f600f0ae 100644 --- a/vendor/github.com/spf13/pflag/flag_test.go +++ b/vendor/github.com/spf13/pflag/flag_test.go @@ -13,21 +13,22 @@ import ( "os" "reflect" "sort" + "strconv" "strings" "testing" "time" ) var ( - test_bool = Bool("test_bool", false, "bool value") - test_int = Int("test_int", 0, "int value") - test_int64 = Int64("test_int64", 0, "int64 value") - test_uint = Uint("test_uint", 0, "uint value") - test_uint64 = Uint64("test_uint64", 0, "uint64 value") - test_string = String("test_string", "0", "string value") - test_float64 = Float64("test_float64", 0, "float64 value") - test_duration = Duration("test_duration", 0, "time.Duration value") - test_optional_int = Int("test_optional_int", 0, "optional int value") + testBool = Bool("test_bool", false, "bool value") + testInt = Int("test_int", 0, "int value") + testInt64 = Int64("test_int64", 0, "int64 value") + testUint = Uint("test_uint", 0, "uint value") + testUint64 = Uint64("test_uint64", 0, "uint64 value") + testString = String("test_string", "0", "string value") + testFloat = Float64("test_float64", 0, "float64 value") + testDuration = Duration("test_duration", 0, "time.Duration value") + testOptionalInt = Int("test_optional_int", 0, "optional int value") normalizeFlagNameInvocations = 0 ) @@ -105,8 +106,25 @@ func TestUsage(t *testing.T) { if GetCommandLine().Parse([]string{"--x"}) == nil { t.Error("parse did not fail for unknown flag") } - if !called { - t.Error("did not call Usage for unknown flag") + if called { + t.Error("did call Usage while using ContinueOnError") + } +} + +func TestAddFlagSet(t *testing.T) { + oldSet := NewFlagSet("old", ContinueOnError) + newSet := NewFlagSet("new", ContinueOnError) + + oldSet.String("flag1", "flag1", "flag1") + oldSet.String("flag2", "flag2", "flag2") + + newSet.String("flag2", "flag2", "flag2") + newSet.String("flag3", "flag3", "flag3") + + oldSet.AddFlagSet(newSet) + + if len(oldSet.formal) != 3 { + t.Errorf("Unexpected result adding a FlagSet to a FlagSet %v", oldSet) } } @@ -150,6 +168,7 @@ func testParse(f *FlagSet, t *testing.T) { bool3Flag := f.Bool("bool3", false, "bool3 value") intFlag := f.Int("int", 0, "int value") int8Flag := f.Int8("int8", 0, "int value") + int16Flag := f.Int16("int16", 0, "int value") int32Flag := f.Int32("int32", 0, "int value") int64Flag := f.Int64("int64", 0, "int64 value") uintFlag := f.Uint("uint", 0, "uint value") @@ -174,6 +193,7 @@ func testParse(f *FlagSet, t *testing.T) { "--bool3=false", "--int=22", "--int8=-8", + "--int16=-16", "--int32=-32", "--int64=0x23", "--uint", "24", @@ -218,9 +238,15 @@ func testParse(f *FlagSet, t *testing.T) { if *int8Flag != -8 { t.Error("int8 flag should be 0x23, is ", *int8Flag) } + if *int16Flag != -16 { + t.Error("int16 flag should be -16, is ", *int16Flag) + } if v, err := f.GetInt8("int8"); err != nil || v != *int8Flag { t.Error("GetInt8 does not work.") } + if v, err := f.GetInt16("int16"); err != nil || v != *int16Flag { + t.Error("GetInt16 does not work.") + } if *int32Flag != -32 { t.Error("int32 flag should be 0x23, is ", *int32Flag) } @@ -291,7 +317,7 @@ func testParse(f *FlagSet, t *testing.T) { t.Error("mask flag should be 255.255.255.0, is ", (*maskFlag).String()) } if v, err := f.GetIPv4Mask("mask"); err != nil || v.String() != (*maskFlag).String() { - t.Errorf("GetIP returned %v but maskFlag was %v", v, *maskFlag, err) + t.Errorf("GetIP returned %v maskFlag was %v error was %v", v, *maskFlag, err) } if *durationFlag != 2*time.Minute { t.Error("duration flag should be 2m, is ", *durationFlag) @@ -315,6 +341,130 @@ func testParse(f *FlagSet, t *testing.T) { } } +func testParseAll(f *FlagSet, t *testing.T) { + if f.Parsed() { + t.Error("f.Parse() = true before Parse") + } + f.BoolP("boola", "a", false, "bool value") + f.BoolP("boolb", "b", false, "bool2 value") + f.BoolP("boolc", "c", false, "bool3 value") + f.BoolP("boold", "d", false, "bool4 value") + f.StringP("stringa", "s", "0", "string value") + f.StringP("stringz", "z", "0", "string value") + f.StringP("stringx", "x", "0", "string value") + f.StringP("stringy", "y", "0", "string value") + f.Lookup("stringx").NoOptDefVal = "1" + args := []string{ + "-ab", + "-cs=xx", + "--stringz=something", + "-d=true", + "-x", + "-y", + "ee", + } + want := []string{ + "boola", "true", + "boolb", "true", + "boolc", "true", + "stringa", "xx", + "stringz", "something", + "boold", "true", + "stringx", "1", + "stringy", "ee", + } + got := []string{} + store := func(flag *Flag, value string) error { + got = append(got, flag.Name) + if len(value) > 0 { + got = append(got, value) + } + return nil + } + if err := f.ParseAll(args, store); err != nil { + t.Errorf("expected no error, got %s", err) + } + if !f.Parsed() { + t.Errorf("f.Parse() = false after Parse") + } + if !reflect.DeepEqual(got, want) { + t.Errorf("f.ParseAll() fail to restore the args") + t.Errorf("Got: %v", got) + t.Errorf("Want: %v", want) + } +} + +func testParseWithUnknownFlags(f *FlagSet, t *testing.T) { + if f.Parsed() { + t.Error("f.Parse() = true before Parse") + } + f.ParseErrorsWhitelist.UnknownFlags = true + + f.BoolP("boola", "a", false, "bool value") + f.BoolP("boolb", "b", false, "bool2 value") + f.BoolP("boolc", "c", false, "bool3 value") + f.BoolP("boold", "d", false, "bool4 value") + f.BoolP("boole", "e", false, "bool4 value") + f.StringP("stringa", "s", "0", "string value") + f.StringP("stringz", "z", "0", "string value") + f.StringP("stringx", "x", "0", "string value") + f.StringP("stringy", "y", "0", "string value") + f.StringP("stringo", "o", "0", "string value") + f.Lookup("stringx").NoOptDefVal = "1" + args := []string{ + "-ab", + "-cs=xx", + "--stringz=something", + "--unknown1", + "unknown1Value", + "-d=true", + "-x", + "--unknown2=unknown2Value", + "-u=unknown3Value", + "-p", + "unknown4Value", + "-q", //another unknown with bool value + "-y", + "ee", + "--unknown7=unknown7value", + "--stringo=ovalue", + "--unknown8=unknown8value", + "--boole", + "--unknown6", + } + want := []string{ + "boola", "true", + "boolb", "true", + "boolc", "true", + "stringa", "xx", + "stringz", "something", + "boold", "true", + "stringx", "1", + "stringy", "ee", + "stringo", "ovalue", + "boole", "true", + } + got := []string{} + store := func(flag *Flag, value string) error { + got = append(got, flag.Name) + if len(value) > 0 { + got = append(got, value) + } + return nil + } + if err := f.ParseAll(args, store); err != nil { + t.Errorf("expected no error, got %s", err) + } + if !f.Parsed() { + t.Errorf("f.Parse() = false after Parse") + } + if !reflect.DeepEqual(got, want) { + t.Errorf("f.ParseAll() fail to restore the args") + t.Errorf("Got: %v", got) + t.Errorf("Want: %v", want) + } +} + func TestShorthand(t *testing.T) { f := NewFlagSet("shorthand", ContinueOnError) if f.Parsed() { @@ -370,6 +520,45 @@ func TestShorthand(t *testing.T) { } else if f.Args()[1] != notaflag { t.Errorf("expected argument %q got %q", notaflag, f.Args()[1]) } + if f.ArgsLenAtDash() != 1 { + t.Errorf("expected argsLenAtDash %d got %d", f.ArgsLenAtDash(), 1) + } +} + +func TestShorthandLookup(t *testing.T) { + f := NewFlagSet("shorthand", ContinueOnError) + if f.Parsed() { + t.Error("f.Parse() = true before Parse") + } + f.BoolP("boola", "a", false, "bool value") + f.BoolP("boolb", "b", false, "bool2 value") + args := []string{ + "-ab", + } + f.SetOutput(ioutil.Discard) + if err := f.Parse(args); err != nil { + t.Error("expected no error, got ", err) + } + if !f.Parsed() { + t.Error("f.Parse() = false after Parse") + } + flag := f.ShorthandLookup("a") + if flag == nil { + t.Errorf("f.ShorthandLookup(\"a\") returned nil") + } + if flag.Name != "boola" { + t.Errorf("f.ShorthandLookup(\"a\") found %q instead of \"boola\"", flag.Name) + } + flag = f.ShorthandLookup("") + if flag != nil { + t.Errorf("f.ShorthandLookup(\"\") did not return nil") + } + defer func() { + recover() + }() + flag = f.ShorthandLookup("ab") + // should NEVER get here. lookup should panic. defer'd func should recover it. + t.Errorf("f.ShorthandLookup(\"ab\") did not panic") } func TestParse(t *testing.T) { @@ -377,16 +566,26 @@ func TestParse(t *testing.T) { testParse(GetCommandLine(), t) } +func TestParseAll(t *testing.T) { + ResetForTesting(func() { t.Error("bad parse") }) + testParseAll(GetCommandLine(), t) +} + +func TestIgnoreUnknownFlags(t *testing.T) { + ResetForTesting(func() { t.Error("bad parse") }) + testParseWithUnknownFlags(GetCommandLine(), t) +} + func TestFlagSetParse(t *testing.T) { testParse(NewFlagSet("test", ContinueOnError), t) } func TestChangedHelper(t *testing.T) { f := NewFlagSet("changedtest", ContinueOnError) - _ = f.Bool("changed", false, "changed bool") - _ = f.Bool("settrue", true, "true to true") - _ = f.Bool("setfalse", false, "false to false") - _ = f.Bool("unchanged", false, "unchanged bool") + f.Bool("changed", false, "changed bool") + f.Bool("settrue", true, "true to true") + f.Bool("setfalse", false, "false to false") + f.Bool("unchanged", false, "unchanged bool") args := []string{"--changed", "--settrue", "--setfalse=false"} if err := f.Parse(args); err != nil { @@ -407,6 +606,9 @@ func TestChangedHelper(t *testing.T) { if f.Changed("invalid") { t.Errorf("--invalid was changed!") } + if f.ArgsLenAtDash() != -1 { + t.Errorf("Expected argsLenAtDash: %d but got %d", -1, f.ArgsLenAtDash()) + } } func replaceSeparators(name string, from []string, to string) string { @@ -486,7 +688,6 @@ func aliasAndWordSepFlagNames(f *FlagSet, name string) NormalizedName { switch name { case oldName: name = newName - break } return NormalizedName(name) @@ -540,6 +741,70 @@ func TestNormalizationFuncShouldChangeFlagName(t *testing.T) { } } +// Related to https://github.com/spf13/cobra/issues/521. +func TestNormalizationSharedFlags(t *testing.T) { + f := NewFlagSet("set f", ContinueOnError) + g := NewFlagSet("set g", ContinueOnError) + nfunc := wordSepNormalizeFunc + testName := "valid_flag" + normName := nfunc(nil, testName) + if testName == string(normName) { + t.Error("TestNormalizationSharedFlags meaningless: the original and normalized flag names are identical:", testName) + } + + f.Bool(testName, false, "bool value") + g.AddFlagSet(f) + + f.SetNormalizeFunc(nfunc) + g.SetNormalizeFunc(nfunc) + + if len(f.formal) != 1 { + t.Error("Normalizing flags should not result in duplications in the flag set:", f.formal) + } + if f.orderedFormal[0].Name != string(normName) { + t.Error("Flag name not normalized") + } + for k := range f.formal { + if k != "valid.flag" { + t.Errorf("The key in the flag map should have been normalized: wanted \"%s\", got \"%s\" instead", normName, k) + } + } + + if !reflect.DeepEqual(f.formal, g.formal) || !reflect.DeepEqual(f.orderedFormal, g.orderedFormal) { + t.Error("Two flag sets sharing the same flags should stay consistent after being normalized. Original set:", f.formal, "Duplicate set:", g.formal) + } +} + +func TestNormalizationSetFlags(t *testing.T) { + f := NewFlagSet("normalized", ContinueOnError) + nfunc := wordSepNormalizeFunc + testName := "valid_flag" + normName := nfunc(nil, testName) + if testName == string(normName) { + t.Error("TestNormalizationSetFlags meaningless: the original and normalized flag names are identical:", testName) + } + + f.Bool(testName, false, "bool value") + f.Set(testName, "true") + f.SetNormalizeFunc(nfunc) + + if len(f.formal) != 1 { + t.Error("Normalizing flags should not result in duplications in the flag set:", f.formal) + } + if f.orderedFormal[0].Name != string(normName) { + t.Error("Flag name not normalized") + } + for k := range f.formal { + if k != "valid.flag" { + t.Errorf("The key in the flag map should have been normalized: wanted \"%s\", got \"%s\" instead", normName, k) + } + } + + if !reflect.DeepEqual(f.formal, f.actual) { + t.Error("The map of set flags should get normalized. Formal:", f.formal, "Actual:", f.actual) + } +} + // Declare a user-defined flag type. type flagVar []string @@ -696,12 +961,19 @@ func TestTermination(t *testing.T) { if f.Args()[1] != arg2 { t.Errorf("expected argument %q got %q", arg2, f.Args()[1]) } + if f.ArgsLenAtDash() != 0 { + t.Errorf("expected argsLenAtDash %d got %d", 0, f.ArgsLenAtDash()) + } } -func TestDeprecatedFlagInDocs(t *testing.T) { +func getDeprecatedFlagSet() *FlagSet { f := NewFlagSet("bob", ContinueOnError) f.Bool("badflag", true, "always true") f.MarkDeprecated("badflag", "use --good-flag instead") + return f +} +func TestDeprecatedFlagInDocs(t *testing.T) { + f := getDeprecatedFlagSet() out := new(bytes.Buffer) f.SetOutput(out) @@ -712,6 +984,42 @@ func TestDeprecatedFlagInDocs(t *testing.T) { } } +func TestUnHiddenDeprecatedFlagInDocs(t *testing.T) { + f := getDeprecatedFlagSet() + flg := f.Lookup("badflag") + if flg == nil { + t.Fatalf("Unable to lookup 'bob' in TestUnHiddenDeprecatedFlagInDocs") + } + flg.Hidden = false + + out := new(bytes.Buffer) + f.SetOutput(out) + f.PrintDefaults() + + defaults := out.String() + if !strings.Contains(defaults, "badflag") { + t.Errorf("Did not find deprecated flag in usage!") + } + if !strings.Contains(defaults, "use --good-flag instead") { + t.Errorf("Did not find 'use --good-flag instead' in defaults") + } +} + +func TestDeprecatedFlagShorthandInDocs(t *testing.T) { + f := NewFlagSet("bob", ContinueOnError) + name := "noshorthandflag" + f.BoolP(name, "n", true, "always true") + f.MarkShorthandDeprecated("noshorthandflag", fmt.Sprintf("use --%s instead", name)) + + out := new(bytes.Buffer) + f.SetOutput(out) + f.PrintDefaults() + + if strings.Contains(out.String(), "-n,") { + t.Errorf("found deprecated flag shorthand in usage!") + } +} + func parseReturnStderr(t *testing.T, f *FlagSet, args []string) (string, error) { oldStderr := os.Stderr r, w, _ := os.Pipe() @@ -751,6 +1059,24 @@ func TestDeprecatedFlagUsage(t *testing.T) { } } +func TestDeprecatedFlagShorthandUsage(t *testing.T) { + f := NewFlagSet("bob", ContinueOnError) + name := "noshorthandflag" + f.BoolP(name, "n", true, "always true") + usageMsg := fmt.Sprintf("use --%s instead", name) + f.MarkShorthandDeprecated(name, usageMsg) + + args := []string{"-n"} + out, err := parseReturnStderr(t, f, args) + if err != nil { + t.Fatal("expected no error; got ", err) + } + + if !strings.Contains(out, usageMsg) { + t.Errorf("usageMsg not printed when using a deprecated flag!") + } +} + func TestDeprecatedFlagUsageNormalized(t *testing.T) { f := NewFlagSet("bob", ContinueOnError) f.Bool("bad-double_flag", true, "always true") @@ -781,3 +1107,153 @@ func TestMultipleNormalizeFlagNameInvocations(t *testing.T) { t.Fatal("Expected normalizeFlagNameInvocations to be 1; got ", normalizeFlagNameInvocations) } } + +// +func TestHiddenFlagInUsage(t *testing.T) { + f := NewFlagSet("bob", ContinueOnError) + f.Bool("secretFlag", true, "shhh") + f.MarkHidden("secretFlag") + + out := new(bytes.Buffer) + f.SetOutput(out) + f.PrintDefaults() + + if strings.Contains(out.String(), "secretFlag") { + t.Errorf("found hidden flag in usage!") + } +} + +// +func TestHiddenFlagUsage(t *testing.T) { + f := NewFlagSet("bob", ContinueOnError) + f.Bool("secretFlag", true, "shhh") + f.MarkHidden("secretFlag") + + args := []string{"--secretFlag"} + out, err := parseReturnStderr(t, f, args) + if err != nil { + t.Fatal("expected no error; got ", err) + } + + if strings.Contains(out, "shhh") { + t.Errorf("usage message printed when using a hidden flag!") + } +} + +const defaultOutput = ` --A for bootstrapping, allow 'any' type + --Alongflagname disable bounds checking + -C, --CCC a boolean defaulting to true (default true) + --D path set relative path for local imports + -E, --EEE num[=1234] a num with NoOptDefVal (default 4321) + --F number a non-zero number (default 2.7) + --G float a float that defaults to zero + --IP ip IP address with no default + --IPMask ipMask Netmask address with no default + --IPNet ipNet IP network with no default + --Ints ints int slice with zero default + --N int a non-zero int (default 27) + --ND1 string[="bar"] a string with NoOptDefVal (default "foo") + --ND2 num[=4321] a num with NoOptDefVal (default 1234) + --StringArray stringArray string array with zero default + --StringSlice strings string slice with zero default + --Z int an int that defaults to zero + --custom custom custom Value implementation + --customP custom a VarP with default (default 10) + --maxT timeout set timeout for dial + -v, --verbose count verbosity +` + +// Custom value that satisfies the Value interface. +type customValue int + +func (cv *customValue) String() string { return fmt.Sprintf("%v", *cv) } + +func (cv *customValue) Set(s string) error { + v, err := strconv.ParseInt(s, 0, 64) + *cv = customValue(v) + return err +} + +func (cv *customValue) Type() string { return "custom" } + +func TestPrintDefaults(t *testing.T) { + fs := NewFlagSet("print defaults test", ContinueOnError) + var buf bytes.Buffer + fs.SetOutput(&buf) + fs.Bool("A", false, "for bootstrapping, allow 'any' type") + fs.Bool("Alongflagname", false, "disable bounds checking") + fs.BoolP("CCC", "C", true, "a boolean defaulting to true") + fs.String("D", "", "set relative `path` for local imports") + fs.Float64("F", 2.7, "a non-zero `number`") + fs.Float64("G", 0, "a float that defaults to zero") + fs.Int("N", 27, "a non-zero int") + fs.IntSlice("Ints", []int{}, "int slice with zero default") + fs.IP("IP", nil, "IP address with no default") + fs.IPMask("IPMask", nil, "Netmask address with no default") + fs.IPNet("IPNet", net.IPNet{}, "IP network with no default") + fs.Int("Z", 0, "an int that defaults to zero") + fs.Duration("maxT", 0, "set `timeout` for dial") + fs.String("ND1", "foo", "a string with NoOptDefVal") + fs.Lookup("ND1").NoOptDefVal = "bar" + fs.Int("ND2", 1234, "a `num` with NoOptDefVal") + fs.Lookup("ND2").NoOptDefVal = "4321" + fs.IntP("EEE", "E", 4321, "a `num` with NoOptDefVal") + fs.ShorthandLookup("E").NoOptDefVal = "1234" + fs.StringSlice("StringSlice", []string{}, "string slice with zero default") + fs.StringArray("StringArray", []string{}, "string array with zero default") + fs.CountP("verbose", "v", "verbosity") + + var cv customValue + fs.Var(&cv, "custom", "custom Value implementation") + + cv2 := customValue(10) + fs.VarP(&cv2, "customP", "", "a VarP with default") + + fs.PrintDefaults() + got := buf.String() + if got != defaultOutput { + fmt.Println("\n" + got) + fmt.Println("\n" + defaultOutput) + t.Errorf("got %q want %q\n", got, defaultOutput) + } +} + +func TestVisitAllFlagOrder(t *testing.T) { + fs := NewFlagSet("TestVisitAllFlagOrder", ContinueOnError) + fs.SortFlags = false + // https://github.com/spf13/pflag/issues/120 + fs.SetNormalizeFunc(func(f *FlagSet, name string) NormalizedName { + return NormalizedName(name) + }) + + names := []string{"C", "B", "A", "D"} + for _, name := range names { + fs.Bool(name, false, "") + } + + i := 0 + fs.VisitAll(func(f *Flag) { + if names[i] != f.Name { + t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name) + } + i++ + }) +} + +func TestVisitFlagOrder(t *testing.T) { + fs := NewFlagSet("TestVisitFlagOrder", ContinueOnError) + fs.SortFlags = false + names := []string{"C", "B", "A", "D"} + for _, name := range names { + fs.Bool(name, false, "") + fs.Set(name, "true") + } + + i := 0 + fs.Visit(func(f *Flag) { + if names[i] != f.Name { + t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name) + } + i++ + }) +} diff --git a/vendor/github.com/spf13/pflag/float32.go b/vendor/github.com/spf13/pflag/float32.go index 30174cb2..a243f81f 100644 --- a/vendor/github.com/spf13/pflag/float32.go +++ b/vendor/github.com/spf13/pflag/float32.go @@ -1,9 +1,6 @@ package pflag -import ( - "fmt" - "strconv" -) +import "strconv" // -- float32 Value type float32Value float32 @@ -23,7 +20,7 @@ func (f *float32Value) Type() string { return "float32" } -func (f *float32Value) String() string { return fmt.Sprintf("%v", *f) } +func (f *float32Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 32) } func float32Conv(sval string) (interface{}, error) { v, err := strconv.ParseFloat(sval, 32) @@ -48,7 +45,7 @@ func (f *FlagSet) Float32Var(p *float32, name string, value float32, usage strin f.VarP(newFloat32Value(value, p), name, "", usage) } -// Like Float32Var, but accepts a shorthand letter that can be used after a single dash. +// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Float32VarP(p *float32, name, shorthand string, value float32, usage string) { f.VarP(newFloat32Value(value, p), name, shorthand, usage) } @@ -59,7 +56,7 @@ func Float32Var(p *float32, name string, value float32, usage string) { CommandLine.VarP(newFloat32Value(value, p), name, "", usage) } -// Like Float32Var, but accepts a shorthand letter that can be used after a single dash. +// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash. func Float32VarP(p *float32, name, shorthand string, value float32, usage string) { CommandLine.VarP(newFloat32Value(value, p), name, shorthand, usage) } @@ -72,7 +69,7 @@ func (f *FlagSet) Float32(name string, value float32, usage string) *float32 { return p } -// Like Float32, but accepts a shorthand letter that can be used after a single dash. +// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Float32P(name, shorthand string, value float32, usage string) *float32 { p := new(float32) f.Float32VarP(p, name, shorthand, value, usage) @@ -85,7 +82,7 @@ func Float32(name string, value float32, usage string) *float32 { return CommandLine.Float32P(name, "", value, usage) } -// Like Float32, but accepts a shorthand letter that can be used after a single dash. +// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash. func Float32P(name, shorthand string, value float32, usage string) *float32 { return CommandLine.Float32P(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/float64.go b/vendor/github.com/spf13/pflag/float64.go index 10e17e4b..04b5492a 100644 --- a/vendor/github.com/spf13/pflag/float64.go +++ b/vendor/github.com/spf13/pflag/float64.go @@ -1,9 +1,6 @@ package pflag -import ( - "fmt" - "strconv" -) +import "strconv" // -- float64 Value type float64Value float64 @@ -23,7 +20,7 @@ func (f *float64Value) Type() string { return "float64" } -func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) } +func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 64) } func float64Conv(sval string) (interface{}, error) { return strconv.ParseFloat(sval, 64) @@ -44,7 +41,7 @@ func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage strin f.VarP(newFloat64Value(value, p), name, "", usage) } -// Like Float64Var, but accepts a shorthand letter that can be used after a single dash. +// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Float64VarP(p *float64, name, shorthand string, value float64, usage string) { f.VarP(newFloat64Value(value, p), name, shorthand, usage) } @@ -55,7 +52,7 @@ func Float64Var(p *float64, name string, value float64, usage string) { CommandLine.VarP(newFloat64Value(value, p), name, "", usage) } -// Like Float64Var, but accepts a shorthand letter that can be used after a single dash. +// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash. func Float64VarP(p *float64, name, shorthand string, value float64, usage string) { CommandLine.VarP(newFloat64Value(value, p), name, shorthand, usage) } @@ -68,7 +65,7 @@ func (f *FlagSet) Float64(name string, value float64, usage string) *float64 { return p } -// Like Float64, but accepts a shorthand letter that can be used after a single dash. +// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Float64P(name, shorthand string, value float64, usage string) *float64 { p := new(float64) f.Float64VarP(p, name, shorthand, value, usage) @@ -81,7 +78,7 @@ func Float64(name string, value float64, usage string) *float64 { return CommandLine.Float64P(name, "", value, usage) } -// Like Float64, but accepts a shorthand letter that can be used after a single dash. +// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash. func Float64P(name, shorthand string, value float64, usage string) *float64 { return CommandLine.Float64P(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/golangflag.go b/vendor/github.com/spf13/pflag/golangflag.go new file mode 100644 index 00000000..d3dd72b7 --- /dev/null +++ b/vendor/github.com/spf13/pflag/golangflag.go @@ -0,0 +1,105 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pflag + +import ( + goflag "flag" + "reflect" + "strings" +) + +// flagValueWrapper implements pflag.Value around a flag.Value. The main +// difference here is the addition of the Type method that returns a string +// name of the type. As this is generally unknown, we approximate that with +// reflection. +type flagValueWrapper struct { + inner goflag.Value + flagType string +} + +// We are just copying the boolFlag interface out of goflag as that is what +// they use to decide if a flag should get "true" when no arg is given. +type goBoolFlag interface { + goflag.Value + IsBoolFlag() bool +} + +func wrapFlagValue(v goflag.Value) Value { + // If the flag.Value happens to also be a pflag.Value, just use it directly. + if pv, ok := v.(Value); ok { + return pv + } + + pv := &flagValueWrapper{ + inner: v, + } + + t := reflect.TypeOf(v) + if t.Kind() == reflect.Interface || t.Kind() == reflect.Ptr { + t = t.Elem() + } + + pv.flagType = strings.TrimSuffix(t.Name(), "Value") + return pv +} + +func (v *flagValueWrapper) String() string { + return v.inner.String() +} + +func (v *flagValueWrapper) Set(s string) error { + return v.inner.Set(s) +} + +func (v *flagValueWrapper) Type() string { + return v.flagType +} + +// PFlagFromGoFlag will return a *pflag.Flag given a *flag.Flag +// If the *flag.Flag.Name was a single character (ex: `v`) it will be accessiblei +// with both `-v` and `--v` in flags. If the golang flag was more than a single +// character (ex: `verbose`) it will only be accessible via `--verbose` +func PFlagFromGoFlag(goflag *goflag.Flag) *Flag { + // Remember the default value as a string; it won't change. + flag := &Flag{ + Name: goflag.Name, + Usage: goflag.Usage, + Value: wrapFlagValue(goflag.Value), + // Looks like golang flags don't set DefValue correctly :-( + //DefValue: goflag.DefValue, + DefValue: goflag.Value.String(), + } + // Ex: if the golang flag was -v, allow both -v and --v to work + if len(flag.Name) == 1 { + flag.Shorthand = flag.Name + } + if fv, ok := goflag.Value.(goBoolFlag); ok && fv.IsBoolFlag() { + flag.NoOptDefVal = "true" + } + return flag +} + +// AddGoFlag will add the given *flag.Flag to the pflag.FlagSet +func (f *FlagSet) AddGoFlag(goflag *goflag.Flag) { + if f.Lookup(goflag.Name) != nil { + return + } + newflag := PFlagFromGoFlag(goflag) + f.AddFlag(newflag) +} + +// AddGoFlagSet will add the given *flag.FlagSet to the pflag.FlagSet +func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet) { + if newSet == nil { + return + } + newSet.VisitAll(func(goflag *goflag.Flag) { + f.AddGoFlag(goflag) + }) + if f.addedGoFlagSets == nil { + f.addedGoFlagSets = make([]*goflag.FlagSet, 0) + } + f.addedGoFlagSets = append(f.addedGoFlagSets, newSet) +} diff --git a/vendor/github.com/spf13/pflag/golangflag_test.go b/vendor/github.com/spf13/pflag/golangflag_test.go new file mode 100644 index 00000000..5bd831bf --- /dev/null +++ b/vendor/github.com/spf13/pflag/golangflag_test.go @@ -0,0 +1,47 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pflag + +import ( + goflag "flag" + "testing" +) + +func TestGoflags(t *testing.T) { + goflag.String("stringFlag", "stringFlag", "stringFlag") + goflag.Bool("boolFlag", false, "boolFlag") + + f := NewFlagSet("test", ContinueOnError) + + f.AddGoFlagSet(goflag.CommandLine) + err := f.Parse([]string{"--stringFlag=bob", "--boolFlag"}) + if err != nil { + t.Fatal("expected no error; get", err) + } + + getString, err := f.GetString("stringFlag") + if err != nil { + t.Fatal("expected no error; get", err) + } + if getString != "bob" { + t.Fatalf("expected getString=bob but got getString=%s", getString) + } + + getBool, err := f.GetBool("boolFlag") + if err != nil { + t.Fatal("expected no error; get", err) + } + if getBool != true { + t.Fatalf("expected getBool=true but got getBool=%v", getBool) + } + if !f.Parsed() { + t.Fatal("f.Parsed() return false after f.Parse() called") + } + + // in fact it is useless. because `go test` called flag.Parse() + if !goflag.CommandLine.Parsed() { + t.Fatal("goflag.CommandLine.Parsed() return false after f.Parse() called") + } +} diff --git a/vendor/github.com/spf13/pflag/int.go b/vendor/github.com/spf13/pflag/int.go index 23f70ddd..1474b89d 100644 --- a/vendor/github.com/spf13/pflag/int.go +++ b/vendor/github.com/spf13/pflag/int.go @@ -1,9 +1,6 @@ package pflag -import ( - "fmt" - "strconv" -) +import "strconv" // -- int Value type intValue int @@ -23,7 +20,7 @@ func (i *intValue) Type() string { return "int" } -func (i *intValue) String() string { return fmt.Sprintf("%v", *i) } +func (i *intValue) String() string { return strconv.Itoa(int(*i)) } func intConv(sval string) (interface{}, error) { return strconv.Atoi(sval) @@ -44,7 +41,7 @@ func (f *FlagSet) IntVar(p *int, name string, value int, usage string) { f.VarP(newIntValue(value, p), name, "", usage) } -// Like IntVar, but accepts a shorthand letter that can be used after a single dash. +// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IntVarP(p *int, name, shorthand string, value int, usage string) { f.VarP(newIntValue(value, p), name, shorthand, usage) } @@ -55,7 +52,7 @@ func IntVar(p *int, name string, value int, usage string) { CommandLine.VarP(newIntValue(value, p), name, "", usage) } -// Like IntVar, but accepts a shorthand letter that can be used after a single dash. +// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash. func IntVarP(p *int, name, shorthand string, value int, usage string) { CommandLine.VarP(newIntValue(value, p), name, shorthand, usage) } @@ -68,7 +65,7 @@ func (f *FlagSet) Int(name string, value int, usage string) *int { return p } -// Like Int, but accepts a shorthand letter that can be used after a single dash. +// IntP is like Int, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IntP(name, shorthand string, value int, usage string) *int { p := new(int) f.IntVarP(p, name, shorthand, value, usage) @@ -81,7 +78,7 @@ func Int(name string, value int, usage string) *int { return CommandLine.IntP(name, "", value, usage) } -// Like Int, but accepts a shorthand letter that can be used after a single dash. +// IntP is like Int, but accepts a shorthand letter that can be used after a single dash. func IntP(name, shorthand string, value int, usage string) *int { return CommandLine.IntP(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/int16.go b/vendor/github.com/spf13/pflag/int16.go new file mode 100644 index 00000000..f1a01d05 --- /dev/null +++ b/vendor/github.com/spf13/pflag/int16.go @@ -0,0 +1,88 @@ +package pflag + +import "strconv" + +// -- int16 Value +type int16Value int16 + +func newInt16Value(val int16, p *int16) *int16Value { + *p = val + return (*int16Value)(p) +} + +func (i *int16Value) Set(s string) error { + v, err := strconv.ParseInt(s, 0, 16) + *i = int16Value(v) + return err +} + +func (i *int16Value) Type() string { + return "int16" +} + +func (i *int16Value) String() string { return strconv.FormatInt(int64(*i), 10) } + +func int16Conv(sval string) (interface{}, error) { + v, err := strconv.ParseInt(sval, 0, 16) + if err != nil { + return 0, err + } + return int16(v), nil +} + +// GetInt16 returns the int16 value of a flag with the given name +func (f *FlagSet) GetInt16(name string) (int16, error) { + val, err := f.getFlagType(name, "int16", int16Conv) + if err != nil { + return 0, err + } + return val.(int16), nil +} + +// Int16Var defines an int16 flag with specified name, default value, and usage string. +// The argument p points to an int16 variable in which to store the value of the flag. +func (f *FlagSet) Int16Var(p *int16, name string, value int16, usage string) { + f.VarP(newInt16Value(value, p), name, "", usage) +} + +// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Int16VarP(p *int16, name, shorthand string, value int16, usage string) { + f.VarP(newInt16Value(value, p), name, shorthand, usage) +} + +// Int16Var defines an int16 flag with specified name, default value, and usage string. +// The argument p points to an int16 variable in which to store the value of the flag. +func Int16Var(p *int16, name string, value int16, usage string) { + CommandLine.VarP(newInt16Value(value, p), name, "", usage) +} + +// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash. +func Int16VarP(p *int16, name, shorthand string, value int16, usage string) { + CommandLine.VarP(newInt16Value(value, p), name, shorthand, usage) +} + +// Int16 defines an int16 flag with specified name, default value, and usage string. +// The return value is the address of an int16 variable that stores the value of the flag. +func (f *FlagSet) Int16(name string, value int16, usage string) *int16 { + p := new(int16) + f.Int16VarP(p, name, "", value, usage) + return p +} + +// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Int16P(name, shorthand string, value int16, usage string) *int16 { + p := new(int16) + f.Int16VarP(p, name, shorthand, value, usage) + return p +} + +// Int16 defines an int16 flag with specified name, default value, and usage string. +// The return value is the address of an int16 variable that stores the value of the flag. +func Int16(name string, value int16, usage string) *int16 { + return CommandLine.Int16P(name, "", value, usage) +} + +// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash. +func Int16P(name, shorthand string, value int16, usage string) *int16 { + return CommandLine.Int16P(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/int32.go b/vendor/github.com/spf13/pflag/int32.go index 515f90bb..9b95944f 100644 --- a/vendor/github.com/spf13/pflag/int32.go +++ b/vendor/github.com/spf13/pflag/int32.go @@ -1,9 +1,6 @@ package pflag -import ( - "fmt" - "strconv" -) +import "strconv" // -- int32 Value type int32Value int32 @@ -23,7 +20,7 @@ func (i *int32Value) Type() string { return "int32" } -func (i *int32Value) String() string { return fmt.Sprintf("%v", *i) } +func (i *int32Value) String() string { return strconv.FormatInt(int64(*i), 10) } func int32Conv(sval string) (interface{}, error) { v, err := strconv.ParseInt(sval, 0, 32) @@ -48,7 +45,7 @@ func (f *FlagSet) Int32Var(p *int32, name string, value int32, usage string) { f.VarP(newInt32Value(value, p), name, "", usage) } -// Like Int32Var, but accepts a shorthand letter that can be used after a single dash. +// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Int32VarP(p *int32, name, shorthand string, value int32, usage string) { f.VarP(newInt32Value(value, p), name, shorthand, usage) } @@ -59,7 +56,7 @@ func Int32Var(p *int32, name string, value int32, usage string) { CommandLine.VarP(newInt32Value(value, p), name, "", usage) } -// Like Int32Var, but accepts a shorthand letter that can be used after a single dash. +// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash. func Int32VarP(p *int32, name, shorthand string, value int32, usage string) { CommandLine.VarP(newInt32Value(value, p), name, shorthand, usage) } @@ -72,7 +69,7 @@ func (f *FlagSet) Int32(name string, value int32, usage string) *int32 { return p } -// Like Int32, but accepts a shorthand letter that can be used after a single dash. +// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Int32P(name, shorthand string, value int32, usage string) *int32 { p := new(int32) f.Int32VarP(p, name, shorthand, value, usage) @@ -85,7 +82,7 @@ func Int32(name string, value int32, usage string) *int32 { return CommandLine.Int32P(name, "", value, usage) } -// Like Int32, but accepts a shorthand letter that can be used after a single dash. +// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash. func Int32P(name, shorthand string, value int32, usage string) *int32 { return CommandLine.Int32P(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/int64.go b/vendor/github.com/spf13/pflag/int64.go index b77ade41..0026d781 100644 --- a/vendor/github.com/spf13/pflag/int64.go +++ b/vendor/github.com/spf13/pflag/int64.go @@ -1,9 +1,6 @@ package pflag -import ( - "fmt" - "strconv" -) +import "strconv" // -- int64 Value type int64Value int64 @@ -23,7 +20,7 @@ func (i *int64Value) Type() string { return "int64" } -func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) } +func (i *int64Value) String() string { return strconv.FormatInt(int64(*i), 10) } func int64Conv(sval string) (interface{}, error) { return strconv.ParseInt(sval, 0, 64) @@ -44,7 +41,7 @@ func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) { f.VarP(newInt64Value(value, p), name, "", usage) } -// Like Int64Var, but accepts a shorthand letter that can be used after a single dash. +// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Int64VarP(p *int64, name, shorthand string, value int64, usage string) { f.VarP(newInt64Value(value, p), name, shorthand, usage) } @@ -55,7 +52,7 @@ func Int64Var(p *int64, name string, value int64, usage string) { CommandLine.VarP(newInt64Value(value, p), name, "", usage) } -// Like Int64Var, but accepts a shorthand letter that can be used after a single dash. +// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash. func Int64VarP(p *int64, name, shorthand string, value int64, usage string) { CommandLine.VarP(newInt64Value(value, p), name, shorthand, usage) } @@ -68,7 +65,7 @@ func (f *FlagSet) Int64(name string, value int64, usage string) *int64 { return p } -// Like Int64, but accepts a shorthand letter that can be used after a single dash. +// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Int64P(name, shorthand string, value int64, usage string) *int64 { p := new(int64) f.Int64VarP(p, name, shorthand, value, usage) @@ -81,7 +78,7 @@ func Int64(name string, value int64, usage string) *int64 { return CommandLine.Int64P(name, "", value, usage) } -// Like Int64, but accepts a shorthand letter that can be used after a single dash. +// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash. func Int64P(name, shorthand string, value int64, usage string) *int64 { return CommandLine.Int64P(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/int8.go b/vendor/github.com/spf13/pflag/int8.go index c51cb4ff..4da92228 100644 --- a/vendor/github.com/spf13/pflag/int8.go +++ b/vendor/github.com/spf13/pflag/int8.go @@ -1,9 +1,6 @@ package pflag -import ( - "fmt" - "strconv" -) +import "strconv" // -- int8 Value type int8Value int8 @@ -23,7 +20,7 @@ func (i *int8Value) Type() string { return "int8" } -func (i *int8Value) String() string { return fmt.Sprintf("%v", *i) } +func (i *int8Value) String() string { return strconv.FormatInt(int64(*i), 10) } func int8Conv(sval string) (interface{}, error) { v, err := strconv.ParseInt(sval, 0, 8) @@ -48,7 +45,7 @@ func (f *FlagSet) Int8Var(p *int8, name string, value int8, usage string) { f.VarP(newInt8Value(value, p), name, "", usage) } -// Like Int8Var, but accepts a shorthand letter that can be used after a single dash. +// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Int8VarP(p *int8, name, shorthand string, value int8, usage string) { f.VarP(newInt8Value(value, p), name, shorthand, usage) } @@ -59,7 +56,7 @@ func Int8Var(p *int8, name string, value int8, usage string) { CommandLine.VarP(newInt8Value(value, p), name, "", usage) } -// Like Int8Var, but accepts a shorthand letter that can be used after a single dash. +// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash. func Int8VarP(p *int8, name, shorthand string, value int8, usage string) { CommandLine.VarP(newInt8Value(value, p), name, shorthand, usage) } @@ -72,7 +69,7 @@ func (f *FlagSet) Int8(name string, value int8, usage string) *int8 { return p } -// Like Int8, but accepts a shorthand letter that can be used after a single dash. +// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Int8P(name, shorthand string, value int8, usage string) *int8 { p := new(int8) f.Int8VarP(p, name, shorthand, value, usage) @@ -85,7 +82,7 @@ func Int8(name string, value int8, usage string) *int8 { return CommandLine.Int8P(name, "", value, usage) } -// Like Int8, but accepts a shorthand letter that can be used after a single dash. +// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash. func Int8P(name, shorthand string, value int8, usage string) *int8 { return CommandLine.Int8P(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/int_slice.go b/vendor/github.com/spf13/pflag/int_slice.go index 7c6ed79f..1e7c9edd 100644 --- a/vendor/github.com/spf13/pflag/int_slice.go +++ b/vendor/github.com/spf13/pflag/int_slice.go @@ -85,7 +85,7 @@ func (f *FlagSet) IntSliceVar(p *[]int, name string, value []int, usage string) f.VarP(newIntSliceValue(value, p), name, "", usage) } -// Like IntSliceVar, but accepts a shorthand letter that can be used after a single dash. +// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) { f.VarP(newIntSliceValue(value, p), name, shorthand, usage) } @@ -96,7 +96,7 @@ func IntSliceVar(p *[]int, name string, value []int, usage string) { CommandLine.VarP(newIntSliceValue(value, p), name, "", usage) } -// Like IntSliceVar, but accepts a shorthand letter that can be used after a single dash. +// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash. func IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) { CommandLine.VarP(newIntSliceValue(value, p), name, shorthand, usage) } @@ -104,14 +104,14 @@ func IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) { // IntSlice defines a []int flag with specified name, default value, and usage string. // The return value is the address of a []int variable that stores the value of the flag. func (f *FlagSet) IntSlice(name string, value []int, usage string) *[]int { - p := make([]int, 0) + p := []int{} f.IntSliceVarP(&p, name, "", value, usage) return &p } -// Like IntSlice, but accepts a shorthand letter that can be used after a single dash. +// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IntSliceP(name, shorthand string, value []int, usage string) *[]int { - p := make([]int, 0) + p := []int{} f.IntSliceVarP(&p, name, shorthand, value, usage) return &p } @@ -122,7 +122,7 @@ func IntSlice(name string, value []int, usage string) *[]int { return CommandLine.IntSliceP(name, "", value, usage) } -// Like IntSlice, but accepts a shorthand letter that can be used after a single dash. +// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash. func IntSliceP(name, shorthand string, value []int, usage string) *[]int { return CommandLine.IntSliceP(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/int_slice_test.go b/vendor/github.com/spf13/pflag/int_slice_test.go index 13a6551b..745aecb9 100644 --- a/vendor/github.com/spf13/pflag/int_slice_test.go +++ b/vendor/github.com/spf13/pflag/int_slice_test.go @@ -60,6 +60,9 @@ func TestIS(t *testing.T) { } } getIS, err := f.GetIntSlice("is") + if err != nil { + t.Fatalf("got error: %v", err) + } for i, v := range getIS { d, err := strconv.Atoi(vals[i]) if err != nil { @@ -87,7 +90,7 @@ func TestISDefault(t *testing.T) { t.Fatalf("got error: %v", err) } if d != v { - t.Fatalf("expected is[%d] to be %s but got: %s", i, d, v) + t.Fatalf("expected is[%d] to be %d but got: %d", i, d, v) } } @@ -101,7 +104,7 @@ func TestISDefault(t *testing.T) { t.Fatal("got an error from GetIntSlice():", err) } if d != v { - t.Fatalf("expected is[%d] to be %s from GetIntSlice but got: %s", i, d, v) + t.Fatalf("expected is[%d] to be %d from GetIntSlice but got: %d", i, d, v) } } } @@ -122,7 +125,7 @@ func TestISWithDefault(t *testing.T) { t.Fatalf("got error: %v", err) } if d != v { - t.Fatalf("expected is[%d] to be %s but got: %s", i, d, v) + t.Fatalf("expected is[%d] to be %d but got: %d", i, d, v) } } @@ -136,7 +139,7 @@ func TestISWithDefault(t *testing.T) { t.Fatalf("got error: %v", err) } if d != v { - t.Fatalf("expected is[%d] to be %s from GetIntSlice but got: %s", i, d, v) + t.Fatalf("expected is[%d] to be %d from GetIntSlice but got: %d", i, d, v) } } } @@ -156,7 +159,7 @@ func TestISCalledTwice(t *testing.T) { } for i, v := range is { if expected[i] != v { - t.Fatalf("expected is[%d] to be %s but got: %s", i, expected[i], v) + t.Fatalf("expected is[%d] to be %d but got: %d", i, expected[i], v) } } } diff --git a/vendor/github.com/spf13/pflag/ip.go b/vendor/github.com/spf13/pflag/ip.go index baa442b5..3d414ba6 100644 --- a/vendor/github.com/spf13/pflag/ip.go +++ b/vendor/github.com/spf13/pflag/ip.go @@ -6,8 +6,6 @@ import ( "strings" ) -var _ = strings.TrimSpace - // -- net.IP value type ipValue net.IP @@ -53,7 +51,7 @@ func (f *FlagSet) IPVar(p *net.IP, name string, value net.IP, usage string) { f.VarP(newIPValue(value, p), name, "", usage) } -// Like IPVar, but accepts a shorthand letter that can be used after a single dash. +// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) { f.VarP(newIPValue(value, p), name, shorthand, usage) } @@ -64,7 +62,7 @@ func IPVar(p *net.IP, name string, value net.IP, usage string) { CommandLine.VarP(newIPValue(value, p), name, "", usage) } -// Like IPVar, but accepts a shorthand letter that can be used after a single dash. +// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash. func IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) { CommandLine.VarP(newIPValue(value, p), name, shorthand, usage) } @@ -77,7 +75,7 @@ func (f *FlagSet) IP(name string, value net.IP, usage string) *net.IP { return p } -// Like IP, but accepts a shorthand letter that can be used after a single dash. +// IPP is like IP, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IPP(name, shorthand string, value net.IP, usage string) *net.IP { p := new(net.IP) f.IPVarP(p, name, shorthand, value, usage) @@ -90,7 +88,7 @@ func IP(name string, value net.IP, usage string) *net.IP { return CommandLine.IPP(name, "", value, usage) } -// Like IP, but accepts a shorthand letter that can be used after a single dash. +// IPP is like IP, but accepts a shorthand letter that can be used after a single dash. func IPP(name, shorthand string, value net.IP, usage string) *net.IP { return CommandLine.IPP(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/ip_slice.go b/vendor/github.com/spf13/pflag/ip_slice.go new file mode 100644 index 00000000..7dd196fe --- /dev/null +++ b/vendor/github.com/spf13/pflag/ip_slice.go @@ -0,0 +1,148 @@ +package pflag + +import ( + "fmt" + "io" + "net" + "strings" +) + +// -- ipSlice Value +type ipSliceValue struct { + value *[]net.IP + changed bool +} + +func newIPSliceValue(val []net.IP, p *[]net.IP) *ipSliceValue { + ipsv := new(ipSliceValue) + ipsv.value = p + *ipsv.value = val + return ipsv +} + +// Set converts, and assigns, the comma-separated IP argument string representation as the []net.IP value of this flag. +// If Set is called on a flag that already has a []net.IP assigned, the newly converted values will be appended. +func (s *ipSliceValue) Set(val string) error { + + // remove all quote characters + rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "") + + // read flag arguments with CSV parser + ipStrSlice, err := readAsCSV(rmQuote.Replace(val)) + if err != nil && err != io.EOF { + return err + } + + // parse ip values into slice + out := make([]net.IP, 0, len(ipStrSlice)) + for _, ipStr := range ipStrSlice { + ip := net.ParseIP(strings.TrimSpace(ipStr)) + if ip == nil { + return fmt.Errorf("invalid string being converted to IP address: %s", ipStr) + } + out = append(out, ip) + } + + if !s.changed { + *s.value = out + } else { + *s.value = append(*s.value, out...) + } + + s.changed = true + + return nil +} + +// Type returns a string that uniquely represents this flag's type. +func (s *ipSliceValue) Type() string { + return "ipSlice" +} + +// String defines a "native" format for this net.IP slice flag value. +func (s *ipSliceValue) String() string { + + ipStrSlice := make([]string, len(*s.value)) + for i, ip := range *s.value { + ipStrSlice[i] = ip.String() + } + + out, _ := writeAsCSV(ipStrSlice) + + return "[" + out + "]" +} + +func ipSliceConv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // Emtpy string would cause a slice with one (empty) entry + if len(val) == 0 { + return []net.IP{}, nil + } + ss := strings.Split(val, ",") + out := make([]net.IP, len(ss)) + for i, sval := range ss { + ip := net.ParseIP(strings.TrimSpace(sval)) + if ip == nil { + return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval) + } + out[i] = ip + } + return out, nil +} + +// GetIPSlice returns the []net.IP value of a flag with the given name +func (f *FlagSet) GetIPSlice(name string) ([]net.IP, error) { + val, err := f.getFlagType(name, "ipSlice", ipSliceConv) + if err != nil { + return []net.IP{}, err + } + return val.([]net.IP), nil +} + +// IPSliceVar defines a ipSlice flag with specified name, default value, and usage string. +// The argument p points to a []net.IP variable in which to store the value of the flag. +func (f *FlagSet) IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) { + f.VarP(newIPSliceValue(value, p), name, "", usage) +} + +// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) { + f.VarP(newIPSliceValue(value, p), name, shorthand, usage) +} + +// IPSliceVar defines a []net.IP flag with specified name, default value, and usage string. +// The argument p points to a []net.IP variable in which to store the value of the flag. +func IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) { + CommandLine.VarP(newIPSliceValue(value, p), name, "", usage) +} + +// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash. +func IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) { + CommandLine.VarP(newIPSliceValue(value, p), name, shorthand, usage) +} + +// IPSlice defines a []net.IP flag with specified name, default value, and usage string. +// The return value is the address of a []net.IP variable that stores the value of that flag. +func (f *FlagSet) IPSlice(name string, value []net.IP, usage string) *[]net.IP { + p := []net.IP{} + f.IPSliceVarP(&p, name, "", value, usage) + return &p +} + +// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP { + p := []net.IP{} + f.IPSliceVarP(&p, name, shorthand, value, usage) + return &p +} + +// IPSlice defines a []net.IP flag with specified name, default value, and usage string. +// The return value is the address of a []net.IP variable that stores the value of the flag. +func IPSlice(name string, value []net.IP, usage string) *[]net.IP { + return CommandLine.IPSliceP(name, "", value, usage) +} + +// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash. +func IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP { + return CommandLine.IPSliceP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/ip_slice_test.go b/vendor/github.com/spf13/pflag/ip_slice_test.go new file mode 100644 index 00000000..b0c681c5 --- /dev/null +++ b/vendor/github.com/spf13/pflag/ip_slice_test.go @@ -0,0 +1,222 @@ +package pflag + +import ( + "fmt" + "net" + "strings" + "testing" +) + +func setUpIPSFlagSet(ipsp *[]net.IP) *FlagSet { + f := NewFlagSet("test", ContinueOnError) + f.IPSliceVar(ipsp, "ips", []net.IP{}, "Command separated list!") + return f +} + +func setUpIPSFlagSetWithDefault(ipsp *[]net.IP) *FlagSet { + f := NewFlagSet("test", ContinueOnError) + f.IPSliceVar(ipsp, "ips", + []net.IP{ + net.ParseIP("192.168.1.1"), + net.ParseIP("0:0:0:0:0:0:0:1"), + }, + "Command separated list!") + return f +} + +func TestEmptyIP(t *testing.T) { + var ips []net.IP + f := setUpIPSFlagSet(&ips) + err := f.Parse([]string{}) + if err != nil { + t.Fatal("expected no error; got", err) + } + + getIPS, err := f.GetIPSlice("ips") + if err != nil { + t.Fatal("got an error from GetIPSlice():", err) + } + if len(getIPS) != 0 { + t.Fatalf("got ips %v with len=%d but expected length=0", getIPS, len(getIPS)) + } +} + +func TestIPS(t *testing.T) { + var ips []net.IP + f := setUpIPSFlagSet(&ips) + + vals := []string{"192.168.1.1", "10.0.0.1", "0:0:0:0:0:0:0:2"} + arg := fmt.Sprintf("--ips=%s", strings.Join(vals, ",")) + err := f.Parse([]string{arg}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range ips { + if ip := net.ParseIP(vals[i]); ip == nil { + t.Fatalf("invalid string being converted to IP address: %s", vals[i]) + } else if !ip.Equal(v) { + t.Fatalf("expected ips[%d] to be %s but got: %s from GetIPSlice", i, vals[i], v) + } + } +} + +func TestIPSDefault(t *testing.T) { + var ips []net.IP + f := setUpIPSFlagSetWithDefault(&ips) + + vals := []string{"192.168.1.1", "0:0:0:0:0:0:0:1"} + err := f.Parse([]string{}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range ips { + if ip := net.ParseIP(vals[i]); ip == nil { + t.Fatalf("invalid string being converted to IP address: %s", vals[i]) + } else if !ip.Equal(v) { + t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v) + } + } + + getIPS, err := f.GetIPSlice("ips") + if err != nil { + t.Fatal("got an error from GetIPSlice") + } + for i, v := range getIPS { + if ip := net.ParseIP(vals[i]); ip == nil { + t.Fatalf("invalid string being converted to IP address: %s", vals[i]) + } else if !ip.Equal(v) { + t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v) + } + } +} + +func TestIPSWithDefault(t *testing.T) { + var ips []net.IP + f := setUpIPSFlagSetWithDefault(&ips) + + vals := []string{"192.168.1.1", "0:0:0:0:0:0:0:1"} + arg := fmt.Sprintf("--ips=%s", strings.Join(vals, ",")) + err := f.Parse([]string{arg}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range ips { + if ip := net.ParseIP(vals[i]); ip == nil { + t.Fatalf("invalid string being converted to IP address: %s", vals[i]) + } else if !ip.Equal(v) { + t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v) + } + } + + getIPS, err := f.GetIPSlice("ips") + if err != nil { + t.Fatal("got an error from GetIPSlice") + } + for i, v := range getIPS { + if ip := net.ParseIP(vals[i]); ip == nil { + t.Fatalf("invalid string being converted to IP address: %s", vals[i]) + } else if !ip.Equal(v) { + t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v) + } + } +} + +func TestIPSCalledTwice(t *testing.T) { + var ips []net.IP + f := setUpIPSFlagSet(&ips) + + in := []string{"192.168.1.2,0:0:0:0:0:0:0:1", "10.0.0.1"} + expected := []net.IP{net.ParseIP("192.168.1.2"), net.ParseIP("0:0:0:0:0:0:0:1"), net.ParseIP("10.0.0.1")} + argfmt := "ips=%s" + arg1 := fmt.Sprintf(argfmt, in[0]) + arg2 := fmt.Sprintf(argfmt, in[1]) + err := f.Parse([]string{arg1, arg2}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range ips { + if !expected[i].Equal(v) { + t.Fatalf("expected ips[%d] to be %s but got: %s", i, expected[i], v) + } + } +} + +func TestIPSBadQuoting(t *testing.T) { + + tests := []struct { + Want []net.IP + FlagArg []string + }{ + { + Want: []net.IP{ + net.ParseIP("a4ab:61d:f03e:5d7d:fad7:d4c2:a1a5:568"), + net.ParseIP("203.107.49.208"), + net.ParseIP("14.57.204.90"), + }, + FlagArg: []string{ + "a4ab:61d:f03e:5d7d:fad7:d4c2:a1a5:568", + "203.107.49.208", + "14.57.204.90", + }, + }, + { + Want: []net.IP{ + net.ParseIP("204.228.73.195"), + net.ParseIP("86.141.15.94"), + }, + FlagArg: []string{ + "204.228.73.195", + "86.141.15.94", + }, + }, + { + Want: []net.IP{ + net.ParseIP("c70c:db36:3001:890f:c6ea:3f9b:7a39:cc3f"), + net.ParseIP("4d17:1d6e:e699:bd7a:88c5:5e7e:ac6a:4472"), + }, + FlagArg: []string{ + "c70c:db36:3001:890f:c6ea:3f9b:7a39:cc3f", + "4d17:1d6e:e699:bd7a:88c5:5e7e:ac6a:4472", + }, + }, + { + Want: []net.IP{ + net.ParseIP("5170:f971:cfac:7be3:512a:af37:952c:bc33"), + net.ParseIP("93.21.145.140"), + net.ParseIP("2cac:61d3:c5ff:6caf:73e0:1b1a:c336:c1ca"), + }, + FlagArg: []string{ + " 5170:f971:cfac:7be3:512a:af37:952c:bc33 , 93.21.145.140 ", + "2cac:61d3:c5ff:6caf:73e0:1b1a:c336:c1ca", + }, + }, + { + Want: []net.IP{ + net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"), + net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"), + net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"), + net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"), + }, + FlagArg: []string{ + `"2e5e:66b2:6441:848:5b74:76ea:574c:3a7b, 2e5e:66b2:6441:848:5b74:76ea:574c:3a7b,2e5e:66b2:6441:848:5b74:76ea:574c:3a7b "`, + " 2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"}, + }, + } + + for i, test := range tests { + + var ips []net.IP + f := setUpIPSFlagSet(&ips) + + if err := f.Parse([]string{fmt.Sprintf("--ips=%s", strings.Join(test.FlagArg, ","))}); err != nil { + t.Fatalf("flag parsing failed with error: %s\nparsing:\t%#v\nwant:\t\t%s", + err, test.FlagArg, test.Want[i]) + } + + for j, b := range ips { + if !b.Equal(test.Want[j]) { + t.Fatalf("bad value parsed for test %d on net.IP %d:\nwant:\t%s\ngot:\t%s", i, j, test.Want[j], b) + } + } + } +} diff --git a/vendor/github.com/spf13/pflag/ipmask.go b/vendor/github.com/spf13/pflag/ipmask.go index 1b10efb4..5bd44bd2 100644 --- a/vendor/github.com/spf13/pflag/ipmask.go +++ b/vendor/github.com/spf13/pflag/ipmask.go @@ -28,7 +28,7 @@ func (i *ipMaskValue) Type() string { return "ipMask" } -// Parse IPv4 netmask written in IP form (e.g. 255.255.255.0). +// ParseIPv4Mask written in IP form (e.g. 255.255.255.0). // This function should really belong to the net package. func ParseIPv4Mask(s string) net.IPMask { mask := net.ParseIP(s) @@ -79,7 +79,7 @@ func (f *FlagSet) IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage f.VarP(newIPMaskValue(value, p), name, "", usage) } -// Like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. +// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) { f.VarP(newIPMaskValue(value, p), name, shorthand, usage) } @@ -90,7 +90,7 @@ func IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) { CommandLine.VarP(newIPMaskValue(value, p), name, "", usage) } -// Like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. +// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. func IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) { CommandLine.VarP(newIPMaskValue(value, p), name, shorthand, usage) } @@ -103,7 +103,7 @@ func (f *FlagSet) IPMask(name string, value net.IPMask, usage string) *net.IPMas return p } -// Like IPMask, but accepts a shorthand letter that can be used after a single dash. +// IPMaskP is like IPMask, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask { p := new(net.IPMask) f.IPMaskVarP(p, name, shorthand, value, usage) @@ -116,7 +116,7 @@ func IPMask(name string, value net.IPMask, usage string) *net.IPMask { return CommandLine.IPMaskP(name, "", value, usage) } -// Like IP, but accepts a shorthand letter that can be used after a single dash. +// IPMaskP is like IP, but accepts a shorthand letter that can be used after a single dash. func IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask { return CommandLine.IPMaskP(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/ipnet.go b/vendor/github.com/spf13/pflag/ipnet.go index 23b7fd3c..e2c1b8bc 100644 --- a/vendor/github.com/spf13/pflag/ipnet.go +++ b/vendor/github.com/spf13/pflag/ipnet.go @@ -7,31 +7,29 @@ import ( ) // IPNet adapts net.IPNet for use as a flag. -type IPNetValue net.IPNet +type ipNetValue net.IPNet -func (ipnet IPNetValue) String() string { +func (ipnet ipNetValue) String() string { n := net.IPNet(ipnet) return n.String() } -func (ipnet *IPNetValue) Set(value string) error { +func (ipnet *ipNetValue) Set(value string) error { _, n, err := net.ParseCIDR(strings.TrimSpace(value)) if err != nil { return err } - *ipnet = IPNetValue(*n) + *ipnet = ipNetValue(*n) return nil } -func (*IPNetValue) Type() string { +func (*ipNetValue) Type() string { return "ipNet" } -var _ = strings.TrimSpace - -func newIPNetValue(val net.IPNet, p *net.IPNet) *IPNetValue { +func newIPNetValue(val net.IPNet, p *net.IPNet) *ipNetValue { *p = val - return (*IPNetValue)(p) + return (*ipNetValue)(p) } func ipNetConv(sval string) (interface{}, error) { @@ -57,7 +55,7 @@ func (f *FlagSet) IPNetVar(p *net.IPNet, name string, value net.IPNet, usage str f.VarP(newIPNetValue(value, p), name, "", usage) } -// Like IPNetVar, but accepts a shorthand letter that can be used after a single dash. +// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) { f.VarP(newIPNetValue(value, p), name, shorthand, usage) } @@ -68,7 +66,7 @@ func IPNetVar(p *net.IPNet, name string, value net.IPNet, usage string) { CommandLine.VarP(newIPNetValue(value, p), name, "", usage) } -// Like IPNetVar, but accepts a shorthand letter that can be used after a single dash. +// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash. func IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) { CommandLine.VarP(newIPNetValue(value, p), name, shorthand, usage) } @@ -81,7 +79,7 @@ func (f *FlagSet) IPNet(name string, value net.IPNet, usage string) *net.IPNet { return p } -// Like IPNet, but accepts a shorthand letter that can be used after a single dash. +// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet { p := new(net.IPNet) f.IPNetVarP(p, name, shorthand, value, usage) @@ -94,7 +92,7 @@ func IPNet(name string, value net.IPNet, usage string) *net.IPNet { return CommandLine.IPNetP(name, "", value, usage) } -// Like IPNet, but accepts a shorthand letter that can be used after a single dash. +// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash. func IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet { return CommandLine.IPNetP(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/printusage_test.go b/vendor/github.com/spf13/pflag/printusage_test.go new file mode 100644 index 00000000..df982aab --- /dev/null +++ b/vendor/github.com/spf13/pflag/printusage_test.go @@ -0,0 +1,74 @@ +package pflag + +import ( + "bytes" + "io" + "testing" +) + +const expectedOutput = ` --long-form Some description + --long-form2 Some description + with multiline + -s, --long-name Some description + -t, --long-name2 Some description with + multiline +` + +func setUpPFlagSet(buf io.Writer) *FlagSet { + f := NewFlagSet("test", ExitOnError) + f.Bool("long-form", false, "Some description") + f.Bool("long-form2", false, "Some description\n with multiline") + f.BoolP("long-name", "s", false, "Some description") + f.BoolP("long-name2", "t", false, "Some description with\n multiline") + f.SetOutput(buf) + return f +} + +func TestPrintUsage(t *testing.T) { + buf := bytes.Buffer{} + f := setUpPFlagSet(&buf) + f.PrintDefaults() + res := buf.String() + if res != expectedOutput { + t.Errorf("Expected \n%s \nActual \n%s", expectedOutput, res) + } +} + +func setUpPFlagSet2(buf io.Writer) *FlagSet { + f := NewFlagSet("test", ExitOnError) + f.Bool("long-form", false, "Some description") + f.Bool("long-form2", false, "Some description\n with multiline") + f.BoolP("long-name", "s", false, "Some description") + f.BoolP("long-name2", "t", false, "Some description with\n multiline") + f.StringP("some-very-long-arg", "l", "test", "Some very long description having break the limit") + f.StringP("other-very-long-arg", "o", "long-default-value", "Some very long description having break the limit") + f.String("some-very-long-arg2", "very long default value", "Some very long description\nwith line break\nmultiple") + f.SetOutput(buf) + return f +} + +const expectedOutput2 = ` --long-form Some description + --long-form2 Some description + with multiline + -s, --long-name Some description + -t, --long-name2 Some description with + multiline + -o, --other-very-long-arg string Some very long description having + break the limit (default + "long-default-value") + -l, --some-very-long-arg string Some very long description having + break the limit (default "test") + --some-very-long-arg2 string Some very long description + with line break + multiple (default "very long default + value") +` + +func TestPrintUsage_2(t *testing.T) { + buf := bytes.Buffer{} + f := setUpPFlagSet2(&buf) + res := f.FlagUsagesWrapped(80) + if res != expectedOutput2 { + t.Errorf("Expected \n%q \nActual \n%q", expectedOutput2, res) + } +} diff --git a/vendor/github.com/spf13/pflag/string.go b/vendor/github.com/spf13/pflag/string.go index f89ea8b5..04e0a26f 100644 --- a/vendor/github.com/spf13/pflag/string.go +++ b/vendor/github.com/spf13/pflag/string.go @@ -1,7 +1,5 @@ package pflag -import "fmt" - // -- string Value type stringValue string @@ -18,7 +16,7 @@ func (s *stringValue) Type() string { return "string" } -func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) } +func (s *stringValue) String() string { return string(*s) } func stringConv(sval string) (interface{}, error) { return sval, nil @@ -39,7 +37,7 @@ func (f *FlagSet) StringVar(p *string, name string, value string, usage string) f.VarP(newStringValue(value, p), name, "", usage) } -// Like StringVar, but accepts a shorthand letter that can be used after a single dash. +// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) StringVarP(p *string, name, shorthand string, value string, usage string) { f.VarP(newStringValue(value, p), name, shorthand, usage) } @@ -50,7 +48,7 @@ func StringVar(p *string, name string, value string, usage string) { CommandLine.VarP(newStringValue(value, p), name, "", usage) } -// Like StringVar, but accepts a shorthand letter that can be used after a single dash. +// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash. func StringVarP(p *string, name, shorthand string, value string, usage string) { CommandLine.VarP(newStringValue(value, p), name, shorthand, usage) } @@ -63,7 +61,7 @@ func (f *FlagSet) String(name string, value string, usage string) *string { return p } -// Like String, but accepts a shorthand letter that can be used after a single dash. +// StringP is like String, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) StringP(name, shorthand string, value string, usage string) *string { p := new(string) f.StringVarP(p, name, shorthand, value, usage) @@ -76,7 +74,7 @@ func String(name string, value string, usage string) *string { return CommandLine.StringP(name, "", value, usage) } -// Like String, but accepts a shorthand letter that can be used after a single dash. +// StringP is like String, but accepts a shorthand letter that can be used after a single dash. func StringP(name, shorthand string, value string, usage string) *string { return CommandLine.StringP(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/string_array.go b/vendor/github.com/spf13/pflag/string_array.go new file mode 100644 index 00000000..fa7bc601 --- /dev/null +++ b/vendor/github.com/spf13/pflag/string_array.go @@ -0,0 +1,103 @@ +package pflag + +// -- stringArray Value +type stringArrayValue struct { + value *[]string + changed bool +} + +func newStringArrayValue(val []string, p *[]string) *stringArrayValue { + ssv := new(stringArrayValue) + ssv.value = p + *ssv.value = val + return ssv +} + +func (s *stringArrayValue) Set(val string) error { + if !s.changed { + *s.value = []string{val} + s.changed = true + } else { + *s.value = append(*s.value, val) + } + return nil +} + +func (s *stringArrayValue) Type() string { + return "stringArray" +} + +func (s *stringArrayValue) String() string { + str, _ := writeAsCSV(*s.value) + return "[" + str + "]" +} + +func stringArrayConv(sval string) (interface{}, error) { + sval = sval[1 : len(sval)-1] + // An empty string would cause a array with one (empty) string + if len(sval) == 0 { + return []string{}, nil + } + return readAsCSV(sval) +} + +// GetStringArray return the []string value of a flag with the given name +func (f *FlagSet) GetStringArray(name string) ([]string, error) { + val, err := f.getFlagType(name, "stringArray", stringArrayConv) + if err != nil { + return []string{}, err + } + return val.([]string), nil +} + +// StringArrayVar defines a string flag with specified name, default value, and usage string. +// The argument p points to a []string variable in which to store the values of the multiple flags. +// The value of each argument will not try to be separated by comma. Use a StringSlice for that. +func (f *FlagSet) StringArrayVar(p *[]string, name string, value []string, usage string) { + f.VarP(newStringArrayValue(value, p), name, "", usage) +} + +// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) { + f.VarP(newStringArrayValue(value, p), name, shorthand, usage) +} + +// StringArrayVar defines a string flag with specified name, default value, and usage string. +// The argument p points to a []string variable in which to store the value of the flag. +// The value of each argument will not try to be separated by comma. Use a StringSlice for that. +func StringArrayVar(p *[]string, name string, value []string, usage string) { + CommandLine.VarP(newStringArrayValue(value, p), name, "", usage) +} + +// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash. +func StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) { + CommandLine.VarP(newStringArrayValue(value, p), name, shorthand, usage) +} + +// StringArray defines a string flag with specified name, default value, and usage string. +// The return value is the address of a []string variable that stores the value of the flag. +// The value of each argument will not try to be separated by comma. Use a StringSlice for that. +func (f *FlagSet) StringArray(name string, value []string, usage string) *[]string { + p := []string{} + f.StringArrayVarP(&p, name, "", value, usage) + return &p +} + +// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) StringArrayP(name, shorthand string, value []string, usage string) *[]string { + p := []string{} + f.StringArrayVarP(&p, name, shorthand, value, usage) + return &p +} + +// StringArray defines a string flag with specified name, default value, and usage string. +// The return value is the address of a []string variable that stores the value of the flag. +// The value of each argument will not try to be separated by comma. Use a StringSlice for that. +func StringArray(name string, value []string, usage string) *[]string { + return CommandLine.StringArrayP(name, "", value, usage) +} + +// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash. +func StringArrayP(name, shorthand string, value []string, usage string) *[]string { + return CommandLine.StringArrayP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/string_array_test.go b/vendor/github.com/spf13/pflag/string_array_test.go new file mode 100644 index 00000000..1ceac8c6 --- /dev/null +++ b/vendor/github.com/spf13/pflag/string_array_test.go @@ -0,0 +1,233 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pflag + +import ( + "fmt" + "testing" +) + +func setUpSAFlagSet(sap *[]string) *FlagSet { + f := NewFlagSet("test", ContinueOnError) + f.StringArrayVar(sap, "sa", []string{}, "Command separated list!") + return f +} + +func setUpSAFlagSetWithDefault(sap *[]string) *FlagSet { + f := NewFlagSet("test", ContinueOnError) + f.StringArrayVar(sap, "sa", []string{"default", "values"}, "Command separated list!") + return f +} + +func TestEmptySA(t *testing.T) { + var sa []string + f := setUpSAFlagSet(&sa) + err := f.Parse([]string{}) + if err != nil { + t.Fatal("expected no error; got", err) + } + + getSA, err := f.GetStringArray("sa") + if err != nil { + t.Fatal("got an error from GetStringArray():", err) + } + if len(getSA) != 0 { + t.Fatalf("got sa %v with len=%d but expected length=0", getSA, len(getSA)) + } +} + +func TestEmptySAValue(t *testing.T) { + var sa []string + f := setUpSAFlagSet(&sa) + err := f.Parse([]string{"--sa="}) + if err != nil { + t.Fatal("expected no error; got", err) + } + + getSA, err := f.GetStringArray("sa") + if err != nil { + t.Fatal("got an error from GetStringArray():", err) + } + if len(getSA) != 0 { + t.Fatalf("got sa %v with len=%d but expected length=0", getSA, len(getSA)) + } +} + +func TestSADefault(t *testing.T) { + var sa []string + f := setUpSAFlagSetWithDefault(&sa) + + vals := []string{"default", "values"} + + err := f.Parse([]string{}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range sa { + if vals[i] != v { + t.Fatalf("expected sa[%d] to be %s but got: %s", i, vals[i], v) + } + } + + getSA, err := f.GetStringArray("sa") + if err != nil { + t.Fatal("got an error from GetStringArray():", err) + } + for i, v := range getSA { + if vals[i] != v { + t.Fatalf("expected sa[%d] to be %s from GetStringArray but got: %s", i, vals[i], v) + } + } +} + +func TestSAWithDefault(t *testing.T) { + var sa []string + f := setUpSAFlagSetWithDefault(&sa) + + val := "one" + arg := fmt.Sprintf("--sa=%s", val) + err := f.Parse([]string{arg}) + if err != nil { + t.Fatal("expected no error; got", err) + } + + if len(sa) != 1 { + t.Fatalf("expected number of values to be %d but %d", 1, len(sa)) + } + + if sa[0] != val { + t.Fatalf("expected value to be %s but got: %s", sa[0], val) + } + + getSA, err := f.GetStringArray("sa") + if err != nil { + t.Fatal("got an error from GetStringArray():", err) + } + + if len(getSA) != 1 { + t.Fatalf("expected number of values to be %d but %d", 1, len(getSA)) + } + + if getSA[0] != val { + t.Fatalf("expected value to be %s but got: %s", getSA[0], val) + } +} + +func TestSACalledTwice(t *testing.T) { + var sa []string + f := setUpSAFlagSet(&sa) + + in := []string{"one", "two"} + expected := []string{"one", "two"} + argfmt := "--sa=%s" + arg1 := fmt.Sprintf(argfmt, in[0]) + arg2 := fmt.Sprintf(argfmt, in[1]) + err := f.Parse([]string{arg1, arg2}) + if err != nil { + t.Fatal("expected no error; got", err) + } + + if len(expected) != len(sa) { + t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa)) + } + for i, v := range sa { + if expected[i] != v { + t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v) + } + } + + values, err := f.GetStringArray("sa") + if err != nil { + t.Fatal("expected no error; got", err) + } + + if len(expected) != len(values) { + t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(sa)) + } + for i, v := range values { + if expected[i] != v { + t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v) + } + } +} + +func TestSAWithSpecialChar(t *testing.T) { + var sa []string + f := setUpSAFlagSet(&sa) + + in := []string{"one,two", `"three"`, `"four,five",six`, "seven eight"} + expected := []string{"one,two", `"three"`, `"four,five",six`, "seven eight"} + argfmt := "--sa=%s" + arg1 := fmt.Sprintf(argfmt, in[0]) + arg2 := fmt.Sprintf(argfmt, in[1]) + arg3 := fmt.Sprintf(argfmt, in[2]) + arg4 := fmt.Sprintf(argfmt, in[3]) + err := f.Parse([]string{arg1, arg2, arg3, arg4}) + if err != nil { + t.Fatal("expected no error; got", err) + } + + if len(expected) != len(sa) { + t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa)) + } + for i, v := range sa { + if expected[i] != v { + t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v) + } + } + + values, err := f.GetStringArray("sa") + if err != nil { + t.Fatal("expected no error; got", err) + } + + if len(expected) != len(values) { + t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values)) + } + for i, v := range values { + if expected[i] != v { + t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v) + } + } +} + +func TestSAWithSquareBrackets(t *testing.T) { + var sa []string + f := setUpSAFlagSet(&sa) + + in := []string{"][]-[", "[a-z]", "[a-z]+"} + expected := []string{"][]-[", "[a-z]", "[a-z]+"} + argfmt := "--sa=%s" + arg1 := fmt.Sprintf(argfmt, in[0]) + arg2 := fmt.Sprintf(argfmt, in[1]) + arg3 := fmt.Sprintf(argfmt, in[2]) + err := f.Parse([]string{arg1, arg2, arg3}) + if err != nil { + t.Fatal("expected no error; got", err) + } + + if len(expected) != len(sa) { + t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa)) + } + for i, v := range sa { + if expected[i] != v { + t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v) + } + } + + values, err := f.GetStringArray("sa") + if err != nil { + t.Fatal("expected no error; got", err) + } + + if len(expected) != len(values) { + t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values)) + } + for i, v := range values { + if expected[i] != v { + t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v) + } + } +} diff --git a/vendor/github.com/spf13/pflag/string_slice.go b/vendor/github.com/spf13/pflag/string_slice.go index 848bea89..0cd3ccc0 100644 --- a/vendor/github.com/spf13/pflag/string_slice.go +++ b/vendor/github.com/spf13/pflag/string_slice.go @@ -1,12 +1,11 @@ package pflag import ( - "fmt" + "bytes" + "encoding/csv" "strings" ) -var _ = fmt.Fprint - // -- stringSlice Value type stringSliceValue struct { value *[]string @@ -20,8 +19,31 @@ func newStringSliceValue(val []string, p *[]string) *stringSliceValue { return ssv } +func readAsCSV(val string) ([]string, error) { + if val == "" { + return []string{}, nil + } + stringReader := strings.NewReader(val) + csvReader := csv.NewReader(stringReader) + return csvReader.Read() +} + +func writeAsCSV(vals []string) (string, error) { + b := &bytes.Buffer{} + w := csv.NewWriter(b) + err := w.Write(vals) + if err != nil { + return "", err + } + w.Flush() + return strings.TrimSuffix(b.String(), "\n"), nil +} + func (s *stringSliceValue) Set(val string) error { - v := strings.Split(val, ",") + v, err := readAsCSV(val) + if err != nil { + return err + } if !s.changed { *s.value = v } else { @@ -35,16 +57,18 @@ func (s *stringSliceValue) Type() string { return "stringSlice" } -func (s *stringSliceValue) String() string { return "[" + strings.Join(*s.value, ",") + "]" } +func (s *stringSliceValue) String() string { + str, _ := writeAsCSV(*s.value) + return "[" + str + "]" +} func stringSliceConv(sval string) (interface{}, error) { - sval = strings.Trim(sval, "[]") + sval = sval[1 : len(sval)-1] // An empty string would cause a slice with one (empty) string if len(sval) == 0 { return []string{}, nil } - v := strings.Split(sval, ",") - return v, nil + return readAsCSV(sval) } // GetStringSlice return the []string value of a flag with the given name @@ -58,48 +82,68 @@ func (f *FlagSet) GetStringSlice(name string) ([]string, error) { // StringSliceVar defines a string flag with specified name, default value, and usage string. // The argument p points to a []string variable in which to store the value of the flag. +// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. +// For example: +// --ss="v1,v2" -ss="v3" +// will result in +// []string{"v1", "v2", "v3"} func (f *FlagSet) StringSliceVar(p *[]string, name string, value []string, usage string) { f.VarP(newStringSliceValue(value, p), name, "", usage) } -// Like StringSliceVar, but accepts a shorthand letter that can be used after a single dash. +// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) { f.VarP(newStringSliceValue(value, p), name, shorthand, usage) } // StringSliceVar defines a string flag with specified name, default value, and usage string. // The argument p points to a []string variable in which to store the value of the flag. +// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. +// For example: +// --ss="v1,v2" -ss="v3" +// will result in +// []string{"v1", "v2", "v3"} func StringSliceVar(p *[]string, name string, value []string, usage string) { CommandLine.VarP(newStringSliceValue(value, p), name, "", usage) } -// Like StringSliceVar, but accepts a shorthand letter that can be used after a single dash. +// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash. func StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) { CommandLine.VarP(newStringSliceValue(value, p), name, shorthand, usage) } // StringSlice defines a string flag with specified name, default value, and usage string. // The return value is the address of a []string variable that stores the value of the flag. +// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. +// For example: +// --ss="v1,v2" -ss="v3" +// will result in +// []string{"v1", "v2", "v3"} func (f *FlagSet) StringSlice(name string, value []string, usage string) *[]string { - p := make([]string, 0) + p := []string{} f.StringSliceVarP(&p, name, "", value, usage) return &p } -// Like StringSlice, but accepts a shorthand letter that can be used after a single dash. +// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) StringSliceP(name, shorthand string, value []string, usage string) *[]string { - p := make([]string, 0) + p := []string{} f.StringSliceVarP(&p, name, shorthand, value, usage) return &p } // StringSlice defines a string flag with specified name, default value, and usage string. // The return value is the address of a []string variable that stores the value of the flag. +// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. +// For example: +// --ss="v1,v2" -ss="v3" +// will result in +// []string{"v1", "v2", "v3"} func StringSlice(name string, value []string, usage string) *[]string { return CommandLine.StringSliceP(name, "", value, usage) } -// Like StringSlice, but accepts a shorthand letter that can be used after a single dash. +// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash. func StringSliceP(name, shorthand string, value []string, usage string) *[]string { return CommandLine.StringSliceP(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/string_slice_test.go b/vendor/github.com/spf13/pflag/string_slice_test.go index 97602de5..c41f3bd6 100644 --- a/vendor/github.com/spf13/pflag/string_slice_test.go +++ b/vendor/github.com/spf13/pflag/string_slice_test.go @@ -39,6 +39,23 @@ func TestEmptySS(t *testing.T) { } } +func TestEmptySSValue(t *testing.T) { + var ss []string + f := setUpSSFlagSet(&ss) + err := f.Parse([]string{"--ss="}) + if err != nil { + t.Fatal("expected no error; got", err) + } + + getSS, err := f.GetStringSlice("ss") + if err != nil { + t.Fatal("got an error from GetStringSlice():", err) + } + if len(getSS) != 0 { + t.Fatalf("got ss %v with len=%d but expected length=0", getSS, len(getSS)) + } +} + func TestSS(t *testing.T) { var ss []string f := setUpSSFlagSet(&ss) @@ -133,9 +150,104 @@ func TestSSCalledTwice(t *testing.T) { if err != nil { t.Fatal("expected no error; got", err) } + + if len(expected) != len(ss) { + t.Fatalf("expected number of ss to be %d but got: %d", len(expected), len(ss)) + } for i, v := range ss { if expected[i] != v { t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v) } } + + values, err := f.GetStringSlice("ss") + if err != nil { + t.Fatal("expected no error; got", err) + } + + if len(expected) != len(values) { + t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(ss)) + } + for i, v := range values { + if expected[i] != v { + t.Fatalf("expected got ss[%d] to be %s but got: %s", i, expected[i], v) + } + } +} + +func TestSSWithComma(t *testing.T) { + var ss []string + f := setUpSSFlagSet(&ss) + + in := []string{`"one,two"`, `"three"`, `"four,five",six`} + expected := []string{"one,two", "three", "four,five", "six"} + argfmt := "--ss=%s" + arg1 := fmt.Sprintf(argfmt, in[0]) + arg2 := fmt.Sprintf(argfmt, in[1]) + arg3 := fmt.Sprintf(argfmt, in[2]) + err := f.Parse([]string{arg1, arg2, arg3}) + if err != nil { + t.Fatal("expected no error; got", err) + } + + if len(expected) != len(ss) { + t.Fatalf("expected number of ss to be %d but got: %d", len(expected), len(ss)) + } + for i, v := range ss { + if expected[i] != v { + t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v) + } + } + + values, err := f.GetStringSlice("ss") + if err != nil { + t.Fatal("expected no error; got", err) + } + + if len(expected) != len(values) { + t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values)) + } + for i, v := range values { + if expected[i] != v { + t.Fatalf("expected got ss[%d] to be %s but got: %s", i, expected[i], v) + } + } +} + +func TestSSWithSquareBrackets(t *testing.T) { + var ss []string + f := setUpSSFlagSet(&ss) + + in := []string{`"[a-z]"`, `"[a-z]+"`} + expected := []string{"[a-z]", "[a-z]+"} + argfmt := "--ss=%s" + arg1 := fmt.Sprintf(argfmt, in[0]) + arg2 := fmt.Sprintf(argfmt, in[1]) + err := f.Parse([]string{arg1, arg2}) + if err != nil { + t.Fatal("expected no error; got", err) + } + + if len(expected) != len(ss) { + t.Fatalf("expected number of ss to be %d but got: %d", len(expected), len(ss)) + } + for i, v := range ss { + if expected[i] != v { + t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v) + } + } + + values, err := f.GetStringSlice("ss") + if err != nil { + t.Fatal("expected no error; got", err) + } + + if len(expected) != len(values) { + t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values)) + } + for i, v := range values { + if expected[i] != v { + t.Fatalf("expected got ss[%d] to be %s but got: %s", i, expected[i], v) + } + } } diff --git a/vendor/github.com/spf13/pflag/uint.go b/vendor/github.com/spf13/pflag/uint.go index d6f8e5be..dcbc2b75 100644 --- a/vendor/github.com/spf13/pflag/uint.go +++ b/vendor/github.com/spf13/pflag/uint.go @@ -1,9 +1,6 @@ package pflag -import ( - "fmt" - "strconv" -) +import "strconv" // -- uint Value type uintValue uint @@ -23,7 +20,7 @@ func (i *uintValue) Type() string { return "uint" } -func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) } +func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i), 10) } func uintConv(sval string) (interface{}, error) { v, err := strconv.ParseUint(sval, 0, 0) @@ -48,7 +45,7 @@ func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) { f.VarP(newUintValue(value, p), name, "", usage) } -// Like UintVar, but accepts a shorthand letter that can be used after a single dash. +// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) UintVarP(p *uint, name, shorthand string, value uint, usage string) { f.VarP(newUintValue(value, p), name, shorthand, usage) } @@ -59,7 +56,7 @@ func UintVar(p *uint, name string, value uint, usage string) { CommandLine.VarP(newUintValue(value, p), name, "", usage) } -// Like UintVar, but accepts a shorthand letter that can be used after a single dash. +// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash. func UintVarP(p *uint, name, shorthand string, value uint, usage string) { CommandLine.VarP(newUintValue(value, p), name, shorthand, usage) } @@ -72,7 +69,7 @@ func (f *FlagSet) Uint(name string, value uint, usage string) *uint { return p } -// Like Uint, but accepts a shorthand letter that can be used after a single dash. +// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) UintP(name, shorthand string, value uint, usage string) *uint { p := new(uint) f.UintVarP(p, name, shorthand, value, usage) @@ -85,7 +82,7 @@ func Uint(name string, value uint, usage string) *uint { return CommandLine.UintP(name, "", value, usage) } -// Like Uint, but accepts a shorthand letter that can be used after a single dash. +// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash. func UintP(name, shorthand string, value uint, usage string) *uint { return CommandLine.UintP(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/uint16.go b/vendor/github.com/spf13/pflag/uint16.go index 1cdc3dfb..7e9914ed 100644 --- a/vendor/github.com/spf13/pflag/uint16.go +++ b/vendor/github.com/spf13/pflag/uint16.go @@ -1,9 +1,6 @@ package pflag -import ( - "fmt" - "strconv" -) +import "strconv" // -- uint16 value type uint16Value uint16 @@ -12,7 +9,7 @@ func newUint16Value(val uint16, p *uint16) *uint16Value { *p = val return (*uint16Value)(p) } -func (i *uint16Value) String() string { return fmt.Sprintf("%d", *i) } + func (i *uint16Value) Set(s string) error { v, err := strconv.ParseUint(s, 0, 16) *i = uint16Value(v) @@ -23,6 +20,8 @@ func (i *uint16Value) Type() string { return "uint16" } +func (i *uint16Value) String() string { return strconv.FormatUint(uint64(*i), 10) } + func uint16Conv(sval string) (interface{}, error) { v, err := strconv.ParseUint(sval, 0, 16) if err != nil { @@ -46,7 +45,7 @@ func (f *FlagSet) Uint16Var(p *uint16, name string, value uint16, usage string) f.VarP(newUint16Value(value, p), name, "", usage) } -// Like Uint16Var, but accepts a shorthand letter that can be used after a single dash. +// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) { f.VarP(newUint16Value(value, p), name, shorthand, usage) } @@ -57,7 +56,7 @@ func Uint16Var(p *uint16, name string, value uint16, usage string) { CommandLine.VarP(newUint16Value(value, p), name, "", usage) } -// Like Uint16Var, but accepts a shorthand letter that can be used after a single dash. +// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash. func Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) { CommandLine.VarP(newUint16Value(value, p), name, shorthand, usage) } @@ -70,7 +69,7 @@ func (f *FlagSet) Uint16(name string, value uint16, usage string) *uint16 { return p } -// Like Uint16, but accepts a shorthand letter that can be used after a single dash. +// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Uint16P(name, shorthand string, value uint16, usage string) *uint16 { p := new(uint16) f.Uint16VarP(p, name, shorthand, value, usage) @@ -83,7 +82,7 @@ func Uint16(name string, value uint16, usage string) *uint16 { return CommandLine.Uint16P(name, "", value, usage) } -// Like Uint16, but accepts a shorthand letter that can be used after a single dash. +// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash. func Uint16P(name, shorthand string, value uint16, usage string) *uint16 { return CommandLine.Uint16P(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/uint32.go b/vendor/github.com/spf13/pflag/uint32.go index 1326e4ab..d8024539 100644 --- a/vendor/github.com/spf13/pflag/uint32.go +++ b/vendor/github.com/spf13/pflag/uint32.go @@ -1,18 +1,15 @@ package pflag -import ( - "fmt" - "strconv" -) +import "strconv" -// -- uint16 value +// -- uint32 value type uint32Value uint32 func newUint32Value(val uint32, p *uint32) *uint32Value { *p = val return (*uint32Value)(p) } -func (i *uint32Value) String() string { return fmt.Sprintf("%d", *i) } + func (i *uint32Value) Set(s string) error { v, err := strconv.ParseUint(s, 0, 32) *i = uint32Value(v) @@ -23,6 +20,8 @@ func (i *uint32Value) Type() string { return "uint32" } +func (i *uint32Value) String() string { return strconv.FormatUint(uint64(*i), 10) } + func uint32Conv(sval string) (interface{}, error) { v, err := strconv.ParseUint(sval, 0, 32) if err != nil { @@ -46,7 +45,7 @@ func (f *FlagSet) Uint32Var(p *uint32, name string, value uint32, usage string) f.VarP(newUint32Value(value, p), name, "", usage) } -// Like Uint32Var, but accepts a shorthand letter that can be used after a single dash. +// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) { f.VarP(newUint32Value(value, p), name, shorthand, usage) } @@ -57,7 +56,7 @@ func Uint32Var(p *uint32, name string, value uint32, usage string) { CommandLine.VarP(newUint32Value(value, p), name, "", usage) } -// Like Uint32Var, but accepts a shorthand letter that can be used after a single dash. +// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash. func Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) { CommandLine.VarP(newUint32Value(value, p), name, shorthand, usage) } @@ -70,7 +69,7 @@ func (f *FlagSet) Uint32(name string, value uint32, usage string) *uint32 { return p } -// Like Uint32, but accepts a shorthand letter that can be used after a single dash. +// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Uint32P(name, shorthand string, value uint32, usage string) *uint32 { p := new(uint32) f.Uint32VarP(p, name, shorthand, value, usage) @@ -83,7 +82,7 @@ func Uint32(name string, value uint32, usage string) *uint32 { return CommandLine.Uint32P(name, "", value, usage) } -// Like Uint32, but accepts a shorthand letter that can be used after a single dash. +// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash. func Uint32P(name, shorthand string, value uint32, usage string) *uint32 { return CommandLine.Uint32P(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/uint64.go b/vendor/github.com/spf13/pflag/uint64.go index 6788bbf8..f62240f2 100644 --- a/vendor/github.com/spf13/pflag/uint64.go +++ b/vendor/github.com/spf13/pflag/uint64.go @@ -1,9 +1,6 @@ package pflag -import ( - "fmt" - "strconv" -) +import "strconv" // -- uint64 Value type uint64Value uint64 @@ -23,7 +20,7 @@ func (i *uint64Value) Type() string { return "uint64" } -func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) } +func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i), 10) } func uint64Conv(sval string) (interface{}, error) { v, err := strconv.ParseUint(sval, 0, 64) @@ -48,7 +45,7 @@ func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) f.VarP(newUint64Value(value, p), name, "", usage) } -// Like Uint64Var, but accepts a shorthand letter that can be used after a single dash. +// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) { f.VarP(newUint64Value(value, p), name, shorthand, usage) } @@ -59,7 +56,7 @@ func Uint64Var(p *uint64, name string, value uint64, usage string) { CommandLine.VarP(newUint64Value(value, p), name, "", usage) } -// Like Uint64Var, but accepts a shorthand letter that can be used after a single dash. +// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash. func Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) { CommandLine.VarP(newUint64Value(value, p), name, shorthand, usage) } @@ -72,7 +69,7 @@ func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 { return p } -// Like Uint64, but accepts a shorthand letter that can be used after a single dash. +// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Uint64P(name, shorthand string, value uint64, usage string) *uint64 { p := new(uint64) f.Uint64VarP(p, name, shorthand, value, usage) @@ -85,7 +82,7 @@ func Uint64(name string, value uint64, usage string) *uint64 { return CommandLine.Uint64P(name, "", value, usage) } -// Like Uint64, but accepts a shorthand letter that can be used after a single dash. +// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash. func Uint64P(name, shorthand string, value uint64, usage string) *uint64 { return CommandLine.Uint64P(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/uint8.go b/vendor/github.com/spf13/pflag/uint8.go index 560c569b..bb0e83c1 100644 --- a/vendor/github.com/spf13/pflag/uint8.go +++ b/vendor/github.com/spf13/pflag/uint8.go @@ -1,9 +1,6 @@ package pflag -import ( - "fmt" - "strconv" -) +import "strconv" // -- uint8 Value type uint8Value uint8 @@ -23,7 +20,7 @@ func (i *uint8Value) Type() string { return "uint8" } -func (i *uint8Value) String() string { return fmt.Sprintf("%v", *i) } +func (i *uint8Value) String() string { return strconv.FormatUint(uint64(*i), 10) } func uint8Conv(sval string) (interface{}, error) { v, err := strconv.ParseUint(sval, 0, 8) @@ -48,7 +45,7 @@ func (f *FlagSet) Uint8Var(p *uint8, name string, value uint8, usage string) { f.VarP(newUint8Value(value, p), name, "", usage) } -// Like Uint8Var, but accepts a shorthand letter that can be used after a single dash. +// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) { f.VarP(newUint8Value(value, p), name, shorthand, usage) } @@ -59,7 +56,7 @@ func Uint8Var(p *uint8, name string, value uint8, usage string) { CommandLine.VarP(newUint8Value(value, p), name, "", usage) } -// Like Uint8Var, but accepts a shorthand letter that can be used after a single dash. +// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash. func Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) { CommandLine.VarP(newUint8Value(value, p), name, shorthand, usage) } @@ -72,7 +69,7 @@ func (f *FlagSet) Uint8(name string, value uint8, usage string) *uint8 { return p } -// Like Uint8, but accepts a shorthand letter that can be used after a single dash. +// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Uint8P(name, shorthand string, value uint8, usage string) *uint8 { p := new(uint8) f.Uint8VarP(p, name, shorthand, value, usage) @@ -85,7 +82,7 @@ func Uint8(name string, value uint8, usage string) *uint8 { return CommandLine.Uint8P(name, "", value, usage) } -// Like Uint8, but accepts a shorthand letter that can be used after a single dash. +// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash. func Uint8P(name, shorthand string, value uint8, usage string) *uint8 { return CommandLine.Uint8P(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/uint_slice.go b/vendor/github.com/spf13/pflag/uint_slice.go new file mode 100644 index 00000000..edd94c60 --- /dev/null +++ b/vendor/github.com/spf13/pflag/uint_slice.go @@ -0,0 +1,126 @@ +package pflag + +import ( + "fmt" + "strconv" + "strings" +) + +// -- uintSlice Value +type uintSliceValue struct { + value *[]uint + changed bool +} + +func newUintSliceValue(val []uint, p *[]uint) *uintSliceValue { + uisv := new(uintSliceValue) + uisv.value = p + *uisv.value = val + return uisv +} + +func (s *uintSliceValue) Set(val string) error { + ss := strings.Split(val, ",") + out := make([]uint, len(ss)) + for i, d := range ss { + u, err := strconv.ParseUint(d, 10, 0) + if err != nil { + return err + } + out[i] = uint(u) + } + if !s.changed { + *s.value = out + } else { + *s.value = append(*s.value, out...) + } + s.changed = true + return nil +} + +func (s *uintSliceValue) Type() string { + return "uintSlice" +} + +func (s *uintSliceValue) String() string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = fmt.Sprintf("%d", d) + } + return "[" + strings.Join(out, ",") + "]" +} + +func uintSliceConv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // Empty string would cause a slice with one (empty) entry + if len(val) == 0 { + return []uint{}, nil + } + ss := strings.Split(val, ",") + out := make([]uint, len(ss)) + for i, d := range ss { + u, err := strconv.ParseUint(d, 10, 0) + if err != nil { + return nil, err + } + out[i] = uint(u) + } + return out, nil +} + +// GetUintSlice returns the []uint value of a flag with the given name. +func (f *FlagSet) GetUintSlice(name string) ([]uint, error) { + val, err := f.getFlagType(name, "uintSlice", uintSliceConv) + if err != nil { + return []uint{}, err + } + return val.([]uint), nil +} + +// UintSliceVar defines a uintSlice flag with specified name, default value, and usage string. +// The argument p points to a []uint variable in which to store the value of the flag. +func (f *FlagSet) UintSliceVar(p *[]uint, name string, value []uint, usage string) { + f.VarP(newUintSliceValue(value, p), name, "", usage) +} + +// UintSliceVarP is like UintSliceVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) { + f.VarP(newUintSliceValue(value, p), name, shorthand, usage) +} + +// UintSliceVar defines a uint[] flag with specified name, default value, and usage string. +// The argument p points to a uint[] variable in which to store the value of the flag. +func UintSliceVar(p *[]uint, name string, value []uint, usage string) { + CommandLine.VarP(newUintSliceValue(value, p), name, "", usage) +} + +// UintSliceVarP is like the UintSliceVar, but accepts a shorthand letter that can be used after a single dash. +func UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) { + CommandLine.VarP(newUintSliceValue(value, p), name, shorthand, usage) +} + +// UintSlice defines a []uint flag with specified name, default value, and usage string. +// The return value is the address of a []uint variable that stores the value of the flag. +func (f *FlagSet) UintSlice(name string, value []uint, usage string) *[]uint { + p := []uint{} + f.UintSliceVarP(&p, name, "", value, usage) + return &p +} + +// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) UintSliceP(name, shorthand string, value []uint, usage string) *[]uint { + p := []uint{} + f.UintSliceVarP(&p, name, shorthand, value, usage) + return &p +} + +// UintSlice defines a []uint flag with specified name, default value, and usage string. +// The return value is the address of a []uint variable that stores the value of the flag. +func UintSlice(name string, value []uint, usage string) *[]uint { + return CommandLine.UintSliceP(name, "", value, usage) +} + +// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash. +func UintSliceP(name, shorthand string, value []uint, usage string) *[]uint { + return CommandLine.UintSliceP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/uint_slice_test.go b/vendor/github.com/spf13/pflag/uint_slice_test.go new file mode 100644 index 00000000..db1a19dc --- /dev/null +++ b/vendor/github.com/spf13/pflag/uint_slice_test.go @@ -0,0 +1,161 @@ +package pflag + +import ( + "fmt" + "strconv" + "strings" + "testing" +) + +func setUpUISFlagSet(uisp *[]uint) *FlagSet { + f := NewFlagSet("test", ContinueOnError) + f.UintSliceVar(uisp, "uis", []uint{}, "Command separated list!") + return f +} + +func setUpUISFlagSetWithDefault(uisp *[]uint) *FlagSet { + f := NewFlagSet("test", ContinueOnError) + f.UintSliceVar(uisp, "uis", []uint{0, 1}, "Command separated list!") + return f +} + +func TestEmptyUIS(t *testing.T) { + var uis []uint + f := setUpUISFlagSet(&uis) + err := f.Parse([]string{}) + if err != nil { + t.Fatal("expected no error; got", err) + } + + getUIS, err := f.GetUintSlice("uis") + if err != nil { + t.Fatal("got an error from GetUintSlice():", err) + } + if len(getUIS) != 0 { + t.Fatalf("got is %v with len=%d but expected length=0", getUIS, len(getUIS)) + } +} + +func TestUIS(t *testing.T) { + var uis []uint + f := setUpUISFlagSet(&uis) + + vals := []string{"1", "2", "4", "3"} + arg := fmt.Sprintf("--uis=%s", strings.Join(vals, ",")) + err := f.Parse([]string{arg}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range uis { + u, err := strconv.ParseUint(vals[i], 10, 0) + if err != nil { + t.Fatalf("got error: %v", err) + } + if uint(u) != v { + t.Fatalf("expected uis[%d] to be %s but got %d", i, vals[i], v) + } + } + getUIS, err := f.GetUintSlice("uis") + if err != nil { + t.Fatalf("got error: %v", err) + } + for i, v := range getUIS { + u, err := strconv.ParseUint(vals[i], 10, 0) + if err != nil { + t.Fatalf("got error: %v", err) + } + if uint(u) != v { + t.Fatalf("expected uis[%d] to be %s but got: %d from GetUintSlice", i, vals[i], v) + } + } +} + +func TestUISDefault(t *testing.T) { + var uis []uint + f := setUpUISFlagSetWithDefault(&uis) + + vals := []string{"0", "1"} + + err := f.Parse([]string{}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range uis { + u, err := strconv.ParseUint(vals[i], 10, 0) + if err != nil { + t.Fatalf("got error: %v", err) + } + if uint(u) != v { + t.Fatalf("expect uis[%d] to be %d but got: %d", i, u, v) + } + } + + getUIS, err := f.GetUintSlice("uis") + if err != nil { + t.Fatal("got an error from GetUintSlice():", err) + } + for i, v := range getUIS { + u, err := strconv.ParseUint(vals[i], 10, 0) + if err != nil { + t.Fatal("got an error from GetIntSlice():", err) + } + if uint(u) != v { + t.Fatalf("expected uis[%d] to be %d from GetUintSlice but got: %d", i, u, v) + } + } +} + +func TestUISWithDefault(t *testing.T) { + var uis []uint + f := setUpUISFlagSetWithDefault(&uis) + + vals := []string{"1", "2"} + arg := fmt.Sprintf("--uis=%s", strings.Join(vals, ",")) + err := f.Parse([]string{arg}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range uis { + u, err := strconv.ParseUint(vals[i], 10, 0) + if err != nil { + t.Fatalf("got error: %v", err) + } + if uint(u) != v { + t.Fatalf("expected uis[%d] to be %d from GetUintSlice but got: %d", i, u, v) + } + } + + getUIS, err := f.GetUintSlice("uis") + if err != nil { + t.Fatal("got an error from GetUintSlice():", err) + } + for i, v := range getUIS { + u, err := strconv.ParseUint(vals[i], 10, 0) + if err != nil { + t.Fatalf("got error: %v", err) + } + if uint(u) != v { + t.Fatalf("expected uis[%d] to be %d from GetUintSlice but got: %d", i, u, v) + } + } +} + +func TestUISCalledTwice(t *testing.T) { + var uis []uint + f := setUpUISFlagSet(&uis) + + in := []string{"1,2", "3"} + expected := []int{1, 2, 3} + argfmt := "--uis=%s" + arg1 := fmt.Sprintf(argfmt, in[0]) + arg2 := fmt.Sprintf(argfmt, in[1]) + err := f.Parse([]string{arg1, arg2}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range uis { + if uint(expected[i]) != v { + t.Fatalf("expected uis[%d] to be %d but got: %d", i, expected[i], v) + } + } +} diff --git a/vendor/github.com/spf13/pflag/verify/all.sh b/vendor/github.com/spf13/pflag/verify/all.sh new file mode 100755 index 00000000..739f89c0 --- /dev/null +++ b/vendor/github.com/spf13/pflag/verify/all.sh @@ -0,0 +1,69 @@ +#!/bin/bash + +set -o errexit +set -o nounset +set -o pipefail + +ROOT=$(dirname "${BASH_SOURCE}")/.. + +# Some useful colors. +if [[ -z "${color_start-}" ]]; then + declare -r color_start="\033[" + declare -r color_red="${color_start}0;31m" + declare -r color_yellow="${color_start}0;33m" + declare -r color_green="${color_start}0;32m" + declare -r color_norm="${color_start}0m" +fi + +SILENT=true + +function is-excluded { + for e in $EXCLUDE; do + if [[ $1 -ef ${BASH_SOURCE} ]]; then + return + fi + if [[ $1 -ef "$ROOT/hack/$e" ]]; then + return + fi + done + return 1 +} + +while getopts ":v" opt; do + case $opt in + v) + SILENT=false + ;; + \?) + echo "Invalid flag: -$OPTARG" >&2 + exit 1 + ;; + esac +done + +if $SILENT ; then + echo "Running in the silent mode, run with -v if you want to see script logs." +fi + +EXCLUDE="all.sh" + +ret=0 +for t in `ls $ROOT/verify/*.sh` +do + if is-excluded $t ; then + echo "Skipping $t" + continue + fi + if $SILENT ; then + echo -e "Verifying $t" + if bash "$t" &> /dev/null; then + echo -e "${color_green}SUCCESS${color_norm}" + else + echo -e "${color_red}FAILED${color_norm}" + ret=1 + fi + else + bash "$t" || ret=1 + fi +done +exit $ret diff --git a/vendor/github.com/spf13/pflag/verify/gofmt.sh b/vendor/github.com/spf13/pflag/verify/gofmt.sh new file mode 100755 index 00000000..f66acf80 --- /dev/null +++ b/vendor/github.com/spf13/pflag/verify/gofmt.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +set -o errexit +set -o nounset +set -o pipefail + +ROOT=$(dirname "${BASH_SOURCE}")/.. + +pushd "${ROOT}" > /dev/null + +GOFMT=${GOFMT:-"gofmt"} +bad_files=$(find . -name '*.go' | xargs $GOFMT -s -l) +if [[ -n "${bad_files}" ]]; then + echo "!!! '$GOFMT' needs to be run on the following files: " + echo "${bad_files}" + exit 1 +fi + +# ex: ts=2 sw=2 et filetype=sh diff --git a/vendor/github.com/spf13/pflag/verify/golint.sh b/vendor/github.com/spf13/pflag/verify/golint.sh new file mode 100755 index 00000000..685c1778 --- /dev/null +++ b/vendor/github.com/spf13/pflag/verify/golint.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +ROOT=$(dirname "${BASH_SOURCE}")/.. +GOLINT=${GOLINT:-"golint"} + +pushd "${ROOT}" > /dev/null + bad_files=$($GOLINT -min_confidence=0.9 ./...) + if [[ -n "${bad_files}" ]]; then + echo "!!! '$GOLINT' problems: " + echo "${bad_files}" + exit 1 + fi +popd > /dev/null + +# ex: ts=2 sw=2 et filetype=sh From f04650163ccc6057c659e1c216e76153d56c660c Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Thu, 12 Apr 2018 11:45:40 -0700 Subject: [PATCH 27/94] glide.yaml: update github.com/spf13/cobra --- glide.lock | 6 +- glide.yaml | 2 +- .../spf13/cobra/.circleci/config.yml | 38 + vendor/github.com/spf13/cobra/.gitignore | 12 + vendor/github.com/spf13/cobra/.mailmap | 3 + vendor/github.com/spf13/cobra/.travis.yml | 23 +- vendor/github.com/spf13/cobra/README.md | 879 +++++---- vendor/github.com/spf13/cobra/args.go | 89 + vendor/github.com/spf13/cobra/args_test.go | 241 +++ .../spf13/cobra/bash_completions.go | 420 +++-- .../spf13/cobra/bash_completions.md | 88 +- .../spf13/cobra/bash_completions_test.go | 220 ++- vendor/github.com/spf13/cobra/cobra.go | 130 +- vendor/github.com/spf13/cobra/cobra/README.md | 94 + .../github.com/spf13/cobra/cobra/cmd/add.go | 179 ++ .../spf13/cobra/cobra/cmd/add_test.go | 109 ++ .../spf13/cobra/cobra/cmd/golden_test.go | 77 + .../spf13/cobra/cobra/cmd/helpers.go | 168 ++ .../github.com/spf13/cobra/cobra/cmd/init.go | 234 +++ .../spf13/cobra/cobra/cmd/init_test.go | 83 + .../spf13/cobra/cobra/cmd/license_agpl.go | 683 +++++++ .../spf13/cobra/cobra/cmd/license_apache_2.go | 238 +++ .../cobra/cobra/cmd/license_bsd_clause_2.go | 71 + .../cobra/cobra/cmd/license_bsd_clause_3.go | 78 + .../spf13/cobra/cobra/cmd/license_gpl_2.go | 376 ++++ .../spf13/cobra/cobra/cmd/license_gpl_3.go | 711 ++++++++ .../spf13/cobra/cobra/cmd/license_lgpl.go | 186 ++ .../spf13/cobra/cobra/cmd/license_mit.go | 63 + .../spf13/cobra/cobra/cmd/licenses.go | 118 ++ .../spf13/cobra/cobra/cmd/project.go | 200 +++ .../spf13/cobra/cobra/cmd/project_test.go | 24 + .../github.com/spf13/cobra/cobra/cmd/root.go | 79 + .../cobra/cobra/cmd/testdata/LICENSE.golden | 202 +++ .../cobra/cobra/cmd/testdata/main.go.golden | 21 + .../cobra/cobra/cmd/testdata/root.go.golden | 89 + .../cobra/cobra/cmd/testdata/test.go.golden | 50 + vendor/github.com/spf13/cobra/cobra/main.go | 20 + vendor/github.com/spf13/cobra/cobra_test.go | 967 +--------- vendor/github.com/spf13/cobra/command.go | 1334 +++++++++----- .../github.com/spf13/cobra/command_notwin.go | 5 + vendor/github.com/spf13/cobra/command_test.go | 1590 ++++++++++++++++- vendor/github.com/spf13/cobra/command_win.go | 20 + vendor/github.com/spf13/cobra/doc/cmd_test.go | 86 + vendor/github.com/spf13/cobra/doc/man_docs.go | 236 +++ vendor/github.com/spf13/cobra/doc/man_docs.md | 31 + .../spf13/cobra/doc/man_docs_test.go | 177 ++ .../spf13/cobra/doc/man_examples_test.go | 35 + vendor/github.com/spf13/cobra/doc/md_docs.go | 159 ++ .../spf13/cobra/{ => doc}/md_docs.md | 54 +- .../spf13/cobra/doc/md_docs_test.go | 74 + .../github.com/spf13/cobra/doc/rest_docs.go | 185 ++ .../github.com/spf13/cobra/doc/rest_docs.md | 114 ++ .../spf13/cobra/doc/rest_docs_test.go | 76 + vendor/github.com/spf13/cobra/doc/util.go | 51 + .../github.com/spf13/cobra/doc/yaml_docs.go | 169 ++ .../github.com/spf13/cobra/doc/yaml_docs.md | 112 ++ .../spf13/cobra/doc/yaml_docs_test.go | 74 + vendor/github.com/spf13/cobra/md_docs.go | 138 -- vendor/github.com/spf13/cobra/md_docs_test.go | 67 - .../github.com/spf13/cobra/zsh_completions.go | 126 ++ .../spf13/cobra/zsh_completions_test.go | 89 + 61 files changed, 10128 insertions(+), 2145 deletions(-) create mode 100644 vendor/github.com/spf13/cobra/.circleci/config.yml create mode 100644 vendor/github.com/spf13/cobra/.mailmap create mode 100644 vendor/github.com/spf13/cobra/args.go create mode 100644 vendor/github.com/spf13/cobra/args_test.go create mode 100644 vendor/github.com/spf13/cobra/cobra/README.md create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/add.go create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/add_test.go create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/golden_test.go create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/helpers.go create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/init.go create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/init_test.go create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_agpl.go create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_apache_2.go create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_2.go create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_3.go create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_2.go create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_3.go create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_lgpl.go create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_mit.go create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/licenses.go create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/project.go create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/project_test.go create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/root.go create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/testdata/LICENSE.golden create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/testdata/main.go.golden create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden create mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/testdata/test.go.golden create mode 100644 vendor/github.com/spf13/cobra/cobra/main.go create mode 100644 vendor/github.com/spf13/cobra/command_notwin.go create mode 100644 vendor/github.com/spf13/cobra/command_win.go create mode 100644 vendor/github.com/spf13/cobra/doc/cmd_test.go create mode 100644 vendor/github.com/spf13/cobra/doc/man_docs.go create mode 100644 vendor/github.com/spf13/cobra/doc/man_docs.md create mode 100644 vendor/github.com/spf13/cobra/doc/man_docs_test.go create mode 100644 vendor/github.com/spf13/cobra/doc/man_examples_test.go create mode 100644 vendor/github.com/spf13/cobra/doc/md_docs.go rename vendor/github.com/spf13/cobra/{ => doc}/md_docs.md (69%) create mode 100644 vendor/github.com/spf13/cobra/doc/md_docs_test.go create mode 100644 vendor/github.com/spf13/cobra/doc/rest_docs.go create mode 100644 vendor/github.com/spf13/cobra/doc/rest_docs.md create mode 100644 vendor/github.com/spf13/cobra/doc/rest_docs_test.go create mode 100644 vendor/github.com/spf13/cobra/doc/util.go create mode 100644 vendor/github.com/spf13/cobra/doc/yaml_docs.go create mode 100644 vendor/github.com/spf13/cobra/doc/yaml_docs.md create mode 100644 vendor/github.com/spf13/cobra/doc/yaml_docs_test.go delete mode 100644 vendor/github.com/spf13/cobra/md_docs.go delete mode 100644 vendor/github.com/spf13/cobra/md_docs_test.go create mode 100644 vendor/github.com/spf13/cobra/zsh_completions.go create mode 100644 vendor/github.com/spf13/cobra/zsh_completions_test.go diff --git a/glide.lock b/glide.lock index 326fe58d..02260093 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ -hash: 4d534cebec7c429b863d7e5dbe03b3b6d92ac662e2c106cd6cf0534882c65c7b -updated: 2018-04-12T11:44:32.221586-07:00 +hash: 64732f6923719298bded0fd2aa6be97f2028aec75dd989a64021702474894849 +updated: 2018-04-12T11:45:29.473389-07:00 imports: - name: github.com/alexbrainman/sspi version: 4729b3d4d8581b2db83864d1018926e4154f9406 @@ -30,7 +30,7 @@ imports: - name: github.com/rubyist/tracerx version: 787959303086f44a8c361240dfac53d3e9d53ed2 - name: github.com/spf13/cobra - version: c55cdf33856a08e4822738728b41783292812889 + version: a1f051bc3eba734da4772d60e2d677f47cf93ef4 - name: github.com/spf13/pflag version: 583c0c0531f06d5278b7d917446061adc344b5cd - name: github.com/stretchr/testify diff --git a/glide.yaml b/glide.yaml index be0fc82a..d2686c8c 100644 --- a/glide.yaml +++ b/glide.yaml @@ -13,7 +13,7 @@ import: - package: github.com/rubyist/tracerx version: 787959303086f44a8c361240dfac53d3e9d53ed2 - package: github.com/spf13/cobra - version: c55cdf33856a08e4822738728b41783292812889 + version: a1f051bc3eba734da4772d60e2d677f47cf93ef4 - package: github.com/spf13/pflag version: 583c0c0531f06d5278b7d917446061adc344b5cd - package: github.com/stretchr/testify diff --git a/vendor/github.com/spf13/cobra/.circleci/config.yml b/vendor/github.com/spf13/cobra/.circleci/config.yml new file mode 100644 index 00000000..bbba32b7 --- /dev/null +++ b/vendor/github.com/spf13/cobra/.circleci/config.yml @@ -0,0 +1,38 @@ +workflows: + version: 2 + main: + jobs: + - go-current + - go-previous + - go-latest +base: &base + working_directory: /go/src/github.com/spf13/cobra + steps: + - checkout + - run: + name: "All Commands" + command: | + mkdir -p bin + curl -Lso bin/shellcheck https://github.com/caarlos0/shellcheck-docker/releases/download/v0.4.3/shellcheck + chmod +x bin/shellcheck + go get -t -v ./... + PATH=$PATH:$PWD/bin go test -v ./... + go build + diff -u <(echo -n) <(gofmt -d -s .) + if [ -z $NOVET ]; then + diff -u <(echo -n) <(go tool vet . 2>&1 | grep -vE 'ExampleCommand|bash_completions.*Fprint'); + fi +version: 2 +jobs: + go-current: + docker: + - image: circleci/golang:1.10.0 + <<: *base + go-previous: + docker: + - image: circleci/golang:1.9.4 + <<: *base + go-latest: + docker: + - image: circleci/golang:latest + <<: *base diff --git a/vendor/github.com/spf13/cobra/.gitignore b/vendor/github.com/spf13/cobra/.gitignore index 36d1a84d..1b8c7c26 100644 --- a/vendor/github.com/spf13/cobra/.gitignore +++ b/vendor/github.com/spf13/cobra/.gitignore @@ -19,6 +19,18 @@ _cgo_export.* _testmain.go +# Vim files https://github.com/github/gitignore/blob/master/Global/Vim.gitignore +# swap +[._]*.s[a-w][a-z] +[._]s[a-w][a-z] +# session +Session.vim +# temporary +.netrwhist +*~ +# auto-generated tag files +tags + *.exe cobra.test diff --git a/vendor/github.com/spf13/cobra/.mailmap b/vendor/github.com/spf13/cobra/.mailmap new file mode 100644 index 00000000..94ec5306 --- /dev/null +++ b/vendor/github.com/spf13/cobra/.mailmap @@ -0,0 +1,3 @@ +Steve Francia +Bjørn Erik Pedersen +Fabiano Franz diff --git a/vendor/github.com/spf13/cobra/.travis.yml b/vendor/github.com/spf13/cobra/.travis.yml index dc43afd6..5afcb209 100644 --- a/vendor/github.com/spf13/cobra/.travis.yml +++ b/vendor/github.com/spf13/cobra/.travis.yml @@ -1,8 +1,21 @@ language: go -go: - - 1.3 - - 1.4.2 - - tip + +matrix: + include: + - go: 1.9.4 + - go: 1.10.0 + - go: tip + allow_failures: + - go: tip + +before_install: + - mkdir -p bin + - curl -Lso bin/shellcheck https://github.com/caarlos0/shellcheck-docker/releases/download/v0.4.3/shellcheck + - chmod +x bin/shellcheck script: - - go test ./... + - PATH=$PATH:$PWD/bin go test -v ./... - go build + - diff -u <(echo -n) <(gofmt -d -s .) + - if [ -z $NOVET ]; then + diff -u <(echo -n) <(go tool vet . 2>&1 | grep -vE 'ExampleCommand|bash_completions.*Fprint'); + fi diff --git a/vendor/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md index b1fb0889..851fcc08 100644 --- a/vendor/github.com/spf13/cobra/README.md +++ b/vendor/github.com/spf13/cobra/README.md @@ -1,122 +1,315 @@ -# Cobra +![cobra logo](https://cloud.githubusercontent.com/assets/173412/10886352/ad566232-814f-11e5-9cd0-aa101788c117.png) -A Commander for modern go CLI interactions +Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files. -[![Build Status](https://travis-ci.org/spf13/cobra.svg)](https://travis-ci.org/spf13/cobra) +Many of the most widely used Go projects are built using Cobra including: -## Overview +* [Kubernetes](http://kubernetes.io/) +* [Hugo](http://gohugo.io) +* [rkt](https://github.com/coreos/rkt) +* [etcd](https://github.com/coreos/etcd) +* [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) +* [GopherJS](http://www.gopherjs.org/) +* [CockroachDB](http://www.cockroachlabs.com/) +* [Bleve](http://www.blevesearch.com/) +* [ProjectAtomic (enterprise)](http://www.projectatomic.io/) +* [GiantSwarm's swarm](https://github.com/giantswarm/cli) +* [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack) +* [rclone](http://rclone.org/) +* [nehm](https://github.com/bogem/nehm) +* [Pouch](https://github.com/alibaba/pouch) -Cobra is a commander providing a simple interface to create powerful modern CLI -interfaces similar to git & go tools. In addition to providing an interface, Cobra -simultaneously provides a controller to organize your application code. +[![Build Status](https://travis-ci.org/spf13/cobra.svg "Travis CI status")](https://travis-ci.org/spf13/cobra) +[![CircleCI status](https://circleci.com/gh/spf13/cobra.png?circle-token=:circle-token "CircleCI status")](https://circleci.com/gh/spf13/cobra) +[![GoDoc](https://godoc.org/github.com/spf13/cobra?status.svg)](https://godoc.org/github.com/spf13/cobra) -Inspired by go, go-Commander, gh and subcommand, Cobra improves on these by -providing **fully posix compliant flags** (including short & long versions), -**nesting commands**, and the ability to **define your own help and usage** for any or -all commands. +# Table of Contents -Cobra has an exceptionally clean interface and simple design without needless -constructors or initialization methods. +- [Overview](#overview) +- [Concepts](#concepts) + * [Commands](#commands) + * [Flags](#flags) +- [Installing](#installing) +- [Getting Started](#getting-started) + * [Using the Cobra Generator](#using-the-cobra-generator) + * [Using the Cobra Library](#using-the-cobra-library) + * [Working with Flags](#working-with-flags) + * [Positional and Custom Arguments](#positional-and-custom-arguments) + * [Example](#example) + * [Help Command](#help-command) + * [Usage Message](#usage-message) + * [PreRun and PostRun Hooks](#prerun-and-postrun-hooks) + * [Suggestions when "unknown command" happens](#suggestions-when-unknown-command-happens) + * [Generating documentation for your command](#generating-documentation-for-your-command) + * [Generating bash completions](#generating-bash-completions) +- [Contributing](#contributing) +- [License](#license) -Applications built with Cobra commands are designed to be as user friendly as -possible. Flags can be placed before or after the command (as long as a -confusing space isn’t provided). Both short and long flags can be used. A -command need not even be fully typed. The shortest unambiguous string will -suffice. Help is automatically generated and available for the application or -for a specific command using either the help command or the --help flag. +# Overview -## Concepts +Cobra is a library providing a simple interface to create powerful modern CLI +interfaces similar to git & go tools. -Cobra is built on a structure of commands & flags. +Cobra is also an application that will generate your application scaffolding to rapidly +develop a Cobra-based application. -**Commands** represent actions and **Flags** are modifiers for those actions. +Cobra provides: +* Easy subcommand-based CLIs: `app server`, `app fetch`, etc. +* Fully POSIX-compliant flags (including short & long versions) +* Nested subcommands +* Global, local and cascading flags +* Easy generation of applications & commands with `cobra init appname` & `cobra add cmdname` +* Intelligent suggestions (`app srver`... did you mean `app server`?) +* Automatic help generation for commands and flags +* Automatic help flag recognition of `-h`, `--help`, etc. +* 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 flexibility to define your own help, usage, etc. +* Optional tight integration with [viper](http://github.com/spf13/viper) for 12-factor apps -In the following example 'server' is a command and 'port' is a flag. +# Concepts + +Cobra is built on a structure of commands, arguments & flags. + +**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions. + +The best applications will read like sentences when used. Users will know how +to use the application because they will natively understand how to use it. + +The pattern to follow is +`APPNAME VERB NOUN --ADJECTIVE.` + or +`APPNAME COMMAND ARG --FLAG` + +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 -### Commands +In this command we are telling Git to clone the url bare. + + git clone URL --bare + +## Commands Command is the central point of the application. Each interaction that the application supports will be contained in a Command. A command can have children commands and optionally run an action. -In the example above 'server' is the command +In the example above, 'server' is the command. -A Command has the following structure: +[More about cobra.Command](https://godoc.org/github.com/spf13/cobra#Command) - type Command struct { - Use string // The one-line usage message. - Short string // The short description shown in the 'help' output. - Long string // The long message shown in the 'help ' output. - Run func(cmd *Command, args []string) // Run runs the command. - } +## Flags -### Flags - -A Flag is a way to modify the behavior of an command. Cobra supports -fully posix compliant flags as well as the go flag package. +A flag is a way to modify the behavior of a command. Cobra supports +fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/). A Cobra command can define flags that persist through to children commands and flags that are only available to that command. -In the example above 'port' is the flag. +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 -which maintains the same interface while adding posix compliance. +library](https://github.com/spf13/pflag), a fork of the flag standard library +which maintains the same interface while adding POSIX compliance. -## Usage +# Installing +Using Cobra is easy. First, use `go get` to install the latest version +of the library. This command will install the `cobra` generator executable +along with the library and its dependencies: -Cobra works by creating a set of commands and then organizing them into a tree. -The tree defines the structure of the application. + go get -u github.com/spf13/cobra/cobra -Once each command is defined with it's corresponding flags, then the -tree is assigned to the commander which is finally executed. +Next, include Cobra in your application: -### Installing -Using Cobra is easy. First use go get to install the latest version -of the library. +```go +import "github.com/spf13/cobra" +``` - $ go get github.com/spf13/cobra +# Getting Started -Next include cobra in your application. +While you are welcome to provide your own organization, typically a Cobra-based +application will follow the following organizational structure: - import "github.com/spf13/cobra" +``` + ▾ appName/ + ▾ cmd/ + add.go + your.go + commands.go + here.go + main.go +``` -### Create the root command +In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra. -The root command represents your binary itself. +```go +package main + +import ( + "fmt" + "os" + + "{pathToYourApp}/cmd" +) + +func main() { + cmd.Execute() +} +``` + +## Using the Cobra Generator + +Cobra provides its own program that will create your application and add any +commands you want. It's the easiest way to incorporate Cobra into your application. + +[Here](https://github.com/spf13/cobra/blob/master/cobra/README.md) you can find more information about it. + +## Using the Cobra Library + +To manually implement Cobra you need to create a bare main.go file and a rootCmd file. +You will optionally provide additional commands as you see fit. + +### Create rootCmd Cobra doesn't require any special constructors. Simply create your commands. - var HugoCmd = &cobra.Command{ - Use: "hugo", - Short: "Hugo is a very fast static site generator", - Long: `A Fast and Flexible Static Site Generator built with +Ideally you place this in app/cmd/root.go: + +```go +var rootCmd = &cobra.Command{ + Use: "hugo", + Short: "Hugo is a very fast static site generator", + Long: `A Fast and Flexible Static Site Generator built with love by spf13 and friends in Go. Complete documentation is available at http://hugo.spf13.com`, - Run: func(cmd *cobra.Command, args []string) { - // Do Stuff Here - }, + Run: func(cmd *cobra.Command, args []string) { + // Do Stuff Here + }, +} + +func Execute() { + if err := rootCmd.Execute(); err != nil { + fmt.Println(err) + os.Exit(1) + } +} +``` + +You will additionally define flags and handle configuration in your init() function. + +For example cmd/root.go: + +```go +import ( + "fmt" + "os" + + homedir "github.com/mitchellh/go-homedir" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +func init() { + cobra.OnInitialize(initConfig) + rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") + rootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory eg. 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 `licensetext` 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 ") + viper.SetDefault("license", "apache") +} + +func initConfig() { + // Don't forget to read config either from cfgFile or from home directory! + if cfgFile != "" { + // Use config file from the flag. + viper.SetConfigFile(cfgFile) + } else { + // Find home directory. + home, err := homedir.Dir() + if err != nil { + fmt.Println(err) + os.Exit(1) } + // Search config in home directory with name ".cobra" (without extension). + viper.AddConfigPath(home) + viper.SetConfigName(".cobra") + } + + if err := viper.ReadInConfig(); err != nil { + fmt.Println("Can't read config:", err) + os.Exit(1) + } +} +``` + +### Create your main.go + +With the root command you need to have your main function execute it. +Execute should be run on the root for clarity, though it can be called on any command. + +In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra. + +```go +package main + +import ( + "fmt" + "os" + + "{pathToYourApp}/cmd" +) + +func main() { + cmd.Execute() +} +``` + ### Create additional commands -Additional commands can be defined. +Additional commands can be defined and typically are each given their own file +inside of the cmd/ directory. - var versionCmd = &cobra.Command{ - Use: "version", - Short: "Print the version number of Hugo", - Long: `All software has versions. This is Hugo's`, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hugo Static Site Generator v0.9 -- HEAD") - }, - } +If you wanted to create a version command you would create cmd/version.go and +populate it with the following: -### Attach command to its parent -In this example we are attaching it to the root, but commands can be attached at any level. +```go +package cmd - HugoCmd.AddCommand(versionCmd) +import ( + "fmt" + + "github.com/spf13/cobra" +) + +func init() { + rootCmd.AddCommand(versionCmd) +} + +var versionCmd = &cobra.Command{ + Use: "version", + Short: "Print the version number of Hugo", + Long: `All software has versions. This is Hugo's`, + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("Hugo Static Site Generator v0.9 -- HEAD") + }, +} +``` + +## Working with Flags + +Flags provide modifiers to control how the action command operates. ### Assign flags to a command @@ -124,43 +317,109 @@ Since the flags are defined and used in different locations, we need to define a variable outside with the correct scope to assign the flag to work with. - var Verbose bool - var Source string +```go +var Verbose bool +var Source string +``` There are two different approaches to assign a flag. -#### Persistent Flags +### Persistent Flags A flag can be 'persistent' meaning that this flag will be available to the command it's assigned to as well as every command under that command. For -global flags assign a flag as a persistent flag on the root. +global flags, assign a flag as a persistent flag on the root. - HugoCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") +```go +rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") +``` -#### Local Flags +### Local Flags A flag can also be assigned locally which will only apply to that specific command. - HugoCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from") +```go +rootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from") +``` -### Remove a command from its parent +### Local Flag on Parent Commands -Removing a command is not a common action in simple programs but it allows 3rd parties to customize an existing command tree. +By default Cobra only parses local flags on the target command, any local flags on +parent commands are ignored. By enabling `Command.TraverseChildren` Cobra will +parse local flags on each command before executing the target command. -In this example, we remove the existing `VersionCmd` command of an existing root command, and we replace it by our own version. +```go +command := cobra.Command{ + Use: "print [OPTIONS] [COMMANDS]", + TraverseChildren: true, +} +``` - mainlib.RootCmd.RemoveCommand(mainlib.VersionCmd) - mainlib.RootCmd.AddCommand(versionCmd) +### Bind Flags with Config -### Once all commands and flags are defined, Execute the commands +You can also bind your flags with [viper](https://github.com/spf13/viper): +```go +var author string -Execute should be run on the root for clarity, though it can be called on any command. +func init() { + rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution") + viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) +} +``` - HugoCmd.Execute() +In this example the persistent flag `author` is bound with `viper`. +**Note**, that the variable `author` will not be set to the value from config, +when the `--author` flag is not provided by user. + +More in [viper documentation](https://github.com/spf13/viper#working-with-flags). + +### Required flags + +Flags are optional by default. If instead you wish your command to report an error +when a flag has not been set, mark it as required: +```go +rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)") +rootCmd.MarkFlagRequired("region") +``` + +## Positional and Custom Arguments + +Validation of positional arguments can be specified using the `Args` field +of `Command`. + +The following validators are built in: + +- `NoArgs` - the command will report an error if there are any positional args. +- `ArbitraryArgs` - the command will accept any args. +- `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the `ValidArgs` field of `Command`. +- `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args. +- `MaximumNArgs(int)` - the command will report an error if there are more than N positional args. +- `ExactArgs(int)` - the command will report an error if there are not exactly N positional args. +- `RangeArgs(min, max)` - the command will report an error if the number of args is not between the minimum and maximum number of expected args. + +An example of setting the custom validator: + +```go +var cmd = &cobra.Command{ + Short: "hello", + Args: func(cmd *cobra.Command, args []string) error { + if len(args) < 1 { + return errors.New("requires at least one arg") + } + if myapp.IsValidColor(args[0]) { + return nil + } + return fmt.Errorf("invalid color specified: %s", args[0]) + }, + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("Hello, World!") + }, +} +``` ## Example -In the example below we have defined three commands. Two are at the top level +In the example below, we have defined three commands. Two are at the top level and one (cmdTimes) is a child of one of the top commands. In this case the root is not executable meaning that a subcommand is required. This is accomplished by not providing a 'Run' for the 'rootCmd'. @@ -169,317 +428,309 @@ We have only defined one flag for a single command. More documentation about flags is available at https://github.com/spf13/pflag - import( - "github.com/spf13/cobra" - "fmt" - "strings" - ) +```go +package main - func main() { +import ( + "fmt" + "strings" - var echoTimes int + "github.com/spf13/cobra" +) - var cmdPrint = &cobra.Command{ - Use: "print [string to print]", - Short: "Print anything to the screen", - Long: `print is for printing anything back to the screen. - For many years people have printed back to the screen. - `, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Print: " + strings.Join(args, " ")) - }, - } +func main() { + var echoTimes int - var cmdEcho = &cobra.Command{ - Use: "echo [string to echo]", - Short: "Echo anything to the screen", - Long: `echo is for echoing anything back. - Echo works a lot like print, except it has a child command. - `, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Print: " + strings.Join(args, " ")) - }, - } + var cmdPrint = &cobra.Command{ + Use: "print [string to print]", + Short: "Print anything to the screen", + Long: `print is for printing anything back to the screen. +For many years people have printed back to the screen.`, + Args: cobra.MinimumNArgs(1), + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("Print: " + strings.Join(args, " ")) + }, + } - var cmdTimes = &cobra.Command{ - Use: "times [# times] [string to echo]", - Short: "Echo anything to the screen more times", - Long: `echo things multiple times back to the user by providing - a count and a string.`, - Run: func(cmd *cobra.Command, args []string) { - for i:=0; i < echoTimes; i++ { - fmt.Println("Echo: " + strings.Join(args, " ")) - } - }, - } + var cmdEcho = &cobra.Command{ + Use: "echo [string to echo]", + Short: "Echo anything to the screen", + Long: `echo is for echoing anything back. +Echo works a lot like print, except it has a child command.`, + Args: cobra.MinimumNArgs(1), + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("Print: " + strings.Join(args, " ")) + }, + } - cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") + var cmdTimes = &cobra.Command{ + Use: "times [# times] [string to echo]", + Short: "Echo anything to the screen more times", + Long: `echo things multiple times back to the user by providing +a count and a string.`, + Args: cobra.MinimumNArgs(1), + Run: func(cmd *cobra.Command, args []string) { + for i := 0; i < echoTimes; i++ { + fmt.Println("Echo: " + strings.Join(args, " ")) + } + }, + } - var rootCmd = &cobra.Command{Use: "app"} - rootCmd.AddCommand(cmdPrint, cmdEcho) - cmdEcho.AddCommand(cmdTimes) - rootCmd.Execute() - } + cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") -For a more complete example of a larger application, please checkout [Hugo](http://hugo.spf13.com) + var rootCmd = &cobra.Command{Use: "app"} + rootCmd.AddCommand(cmdPrint, cmdEcho) + cmdEcho.AddCommand(cmdTimes) + rootCmd.Execute() +} +``` -## The Help Command +For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/). + +## Help Command Cobra automatically adds a help command to your application when you have subcommands. -This will be called when a user runs 'app help'. Additionally help will also -support all other commands as input. Say for instance you have a command called -'create' without any additional configuration cobra will work when 'app help +This will be called when a user runs 'app help'. Additionally, help will also +support all other commands as input. Say, for instance, you have a command called +'create' without any additional configuration; Cobra will work when 'app help create' is called. Every command will automatically have the '--help' flag added. ### Example -The following output is automatically generated by cobra. Nothing beyond the +The following output is automatically generated by Cobra. Nothing beyond the command and flag definitions are needed. - > hugo help + $ cobra help - A Fast and Flexible Static Site Generator built with - love by spf13 and friends in Go. - - Complete documentation is available at http://hugo.spf13.com + 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. Usage: - hugo [flags] - hugo [command] + cobra [command] Available Commands: - server :: Hugo runs it's own a webserver to render the files - version :: Print the version number of Hugo - check :: Check content in the source directory - benchmark :: Benchmark hugo by building a site a number of times - help [command] :: Help about any command + add Add a command to a Cobra Application + help Help about any command + init Initialize a Cobra Application - Available Flags: - -b, --base-url="": hostname (and path) to the root eg. http://spf13.com/ - -D, --build-drafts=false: include content marked as draft - --config="": config file (default is path/config.yaml|json|toml) - -d, --destination="": filesystem path to write files to - -s, --source="": filesystem path to read files relative from - --stepAnalysis=false: display memory and timing of different steps of the program - --uglyurls=false: if true, use /filename.html instead of /filename/ - -v, --verbose=false: verbose output - -w, --watch=false: watch filesystem for changes and recreate as needed - - Use "hugo help [command]" for more information about that command. + Flags: + -a, --author string author name for copyright attribution (default "YOUR NAME") + --config string config file (default is $HOME/.cobra.yaml) + -h, --help help for cobra + -l, --license string name of license for the project + --viper use Viper for configuration (default true) + Use "cobra [command] --help" for more information about a command. Help is just a command like any other. There is no special logic or behavior -around it. In fact you can provide your own if you want. +around it. In fact, you can provide your own if you want. ### Defining your own help -You can provide your own Help command or you own template for the default command to use. +You can provide your own Help command or your own template for the default command to use +with following functions: -The default help command is - - func (c *Command) initHelp() { - if c.helpCommand == nil { - 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.`, - Run: c.HelpFunc(), - } - } - c.AddCommand(c.helpCommand) - } - -You can provide your own command, function or template through the following methods. - - command.SetHelpCommand(cmd *Command) - - command.SetHelpFunc(f func(*Command, []string)) - - command.SetHelpTemplate(s string) +```go +cmd.SetHelpCommand(cmd *Command) +cmd.SetHelpFunc(f func(*Command, []string)) +cmd.SetHelpTemplate(s string) +``` The latter two will also apply to any children commands. -## Usage +## Usage Message -When the user provides an invalid flag or invalid command Cobra responds by -showing the user the 'usage' +When the user provides an invalid flag or invalid command, Cobra responds by +showing the user the 'usage'. ### Example You may recognize this from the help above. That's because the default help -embeds the usage as part of it's output. +embeds the usage as part of its output. + $ cobra --invalid + Error: unknown flag: --invalid Usage: - hugo [flags] - hugo [command] + cobra [command] Available Commands: - server Hugo runs it's own a webserver to render the files - version Print the version number of Hugo - check Check content in the source directory - benchmark Benchmark hugo by building a site a number of times - help [command] Help about any command + add Add a command to a Cobra Application + help Help about any command + init Initialize a Cobra Application - Available Flags: - -b, --base-url="": hostname (and path) to the root eg. http://spf13.com/ - -D, --build-drafts=false: include content marked as draft - --config="": config file (default is path/config.yaml|json|toml) - -d, --destination="": filesystem path to write files to - -s, --source="": filesystem path to read files relative from - --stepAnalysis=false: display memory and timing of different steps of the program - --uglyurls=false: if true, use /filename.html instead of /filename/ - -v, --verbose=false: verbose output - -w, --watch=false: watch filesystem for changes and recreate as needed + Flags: + -a, --author string author name for copyright attribution (default "YOUR NAME") + --config string config file (default is $HOME/.cobra.yaml) + -h, --help help for cobra + -l, --license string name of license for the project + --viper use Viper for configuration (default true) + + Use "cobra [command] --help" for more information about a command. ### Defining your own usage -You can provide your own usage function or template for cobra to use. +You can provide your own usage function or template for Cobra to use. +Like help, the function and template are overridable through public methods: -The default usage function is +```go +cmd.SetUsageFunc(f func(*Command) error) +cmd.SetUsageTemplate(s string) +``` - return func(c *Command) error { - err := tmpl(c.Out(), c.UsageTemplate(), c) - return err - } +## Version Flag -Like help the function and template are over ridable through public methods. +Cobra adds a top-level '--version' flag if the Version field is set on the root command. +Running an application with the '--version' flag will print the version to stdout using +the version template. The template can be customized using the +`cmd.SetVersionTemplate(s string)` function. - command.SetUsageFunc(f func(*Command) error) +## PreRun and PostRun Hooks - command.SetUsageTemplate(s string) - -## PreRun or PostRun Hooks - -It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistendPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherrited by children if they do not declare their own. These function are run in the following order: +It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order: - `PersistentPreRun` - `PreRun` - `Run` - `PostRun` -- `PersistenPostRun` +- `PersistentPostRun` -And example of two commands which use all of these features is below. When the subcommand in executed it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun` +An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`: ```go package main import ( - "fmt" + "fmt" - "github.com/spf13/cobra" + "github.com/spf13/cobra" ) func main() { - var rootCmd = &cobra.Command{ - Use: "root [sub]", - Short: "My root command", - PersistentPreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args) - }, - PreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PreRun with args: %v\n", args) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd Run with args: %v\n", args) - }, - PostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PostRun with args: %v\n", args) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args) - }, - } + var rootCmd = &cobra.Command{ + Use: "root [sub]", + Short: "My root command", + PersistentPreRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args) + }, + PreRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside rootCmd PreRun with args: %v\n", args) + }, + Run: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside rootCmd Run with args: %v\n", args) + }, + PostRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside rootCmd PostRun with args: %v\n", args) + }, + PersistentPostRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args) + }, + } - var subCmd = &cobra.Command{ - Use: "sub [no options!]", - Short: "My sub command", - PreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PreRun with args: %v\n", args) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd Run with args: %v\n", args) - }, - PostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PostRun with args: %v\n", args) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args) - }, - } + var subCmd = &cobra.Command{ + Use: "sub [no options!]", + Short: "My subcommand", + PreRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside subCmd PreRun with args: %v\n", args) + }, + Run: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside subCmd Run with args: %v\n", args) + }, + PostRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside subCmd PostRun with args: %v\n", args) + }, + PersistentPostRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args) + }, + } - rootCmd.AddCommand(subCmd) + rootCmd.AddCommand(subCmd) - rootCmd.SetArgs([]string{""}) - _ = rootCmd.Execute() - fmt.Print("\n") - rootCmd.SetArgs([]string{"sub", "arg1", "arg2"}) - _ = rootCmd.Execute() + rootCmd.SetArgs([]string{""}) + rootCmd.Execute() + fmt.Println() + rootCmd.SetArgs([]string{"sub", "arg1", "arg2"}) + rootCmd.Execute() } ``` -## Generating markdown formatted documentation for your command +Output: +``` +Inside rootCmd PersistentPreRun with args: [] +Inside rootCmd PreRun with args: [] +Inside rootCmd Run with args: [] +Inside rootCmd PostRun with args: [] +Inside rootCmd PersistentPostRun with args: [] -Cobra can generate a markdown formatted document based on the subcommands, flags, etc. A simple example of how to do this for your command can be found in [Markdown Docs](md_docs.md) +Inside rootCmd PersistentPreRun with args: [arg1 arg2] +Inside subCmd PreRun with args: [arg1 arg2] +Inside subCmd Run with args: [arg1 arg2] +Inside subCmd PostRun with args: [arg1 arg2] +Inside subCmd PersistentPostRun with args: [arg1 arg2] +``` -## Generating bash completions for your command +## Suggestions when "unknown command" happens -Cobra can generate a bash completions file. If you add more information to your command these completions can be amazingly powerful and flexible. Read more about [Bash Completions](bash_completions.md) +Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example: -## Debugging +``` +$ hugo srever +Error: unknown command "srever" for "hugo" -Cobra provides a ‘DebugFlags’ method on a command which when called will print -out everything Cobra knows about the flags for each command +Did you mean this? + server -### Example +Run 'hugo --help' for usage. +``` - command.DebugFlags() +Suggestions are automatic based on every subcommand registered and use an implementation of [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion. -## 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 +If you need to disable suggestions or tweak the string distance in your command, use: -## ToDo -* Launch proper documentation site +```go +command.DisableSuggestions = true +``` -## Contributing +or + +```go +command.SuggestionsMinimumDistance = 1 +``` + +You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but makes sense in your set of commands and for some which you don't want aliases. Example: + +``` +$ kubectl remove +Error: unknown command "remove" for "kubectl" + +Did you mean this? + delete + +Run 'kubectl help' for usage. +``` + +## Generating documentation for your command + +Cobra can generate documentation based on subcommands, flags, etc. in the following formats: + +- [Markdown](doc/md_docs.md) +- [ReStructured Text](doc/rest_docs.md) +- [Man Page](doc/man_docs.md) + +## Generating bash completions + +Cobra can generate a bash-completion file. If you add more information to your command, these completions can be amazingly powerful and flexible. Read more about it in [Bash Completions](bash_completions.md). + +# Contributing 1. Fork it -2. Create your feature branch (`git checkout -b my-new-feature`) -3. Commit your changes (`git commit -am 'Add some feature'`) -4. Push to the branch (`git push origin my-new-feature`) -5. Create new Pull Request +2. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`) +3. Create your feature branch (`git checkout -b my-new-feature`) +4. Make changes and add them (`git add .`) +5. Commit your changes (`git commit -m 'Add some feature'`) +6. Push to the branch (`git push origin my-new-feature`) +7. Create new pull request -## Contributors - -Names in no particular order: - -* [spf13](https://github.com/spf13) - -## License +# 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/vendor/github.com/spf13/cobra/args.go b/vendor/github.com/spf13/cobra/args.go new file mode 100644 index 00000000..a5d8a927 --- /dev/null +++ b/vendor/github.com/spf13/cobra/args.go @@ -0,0 +1,89 @@ +package cobra + +import ( + "fmt" +) + +type PositionalArgs func(cmd *Command, args []string) error + +// Legacy arg validation has the following behaviour: +// - root commands with no subcommands can take arbitrary arguments +// - root commands with subcommands will do subcommand validity checking +// - subcommands will always accept arbitrary arguments +func legacyArgs(cmd *Command, args []string) error { + // no subcommand, always take args + if !cmd.HasSubCommands() { + return nil + } + + // root command with subcommands, do subcommand checking. + if !cmd.HasParent() && len(args) > 0 { + return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0])) + } + return nil +} + +// NoArgs returns an error if any args are included. +func NoArgs(cmd *Command, args []string) error { + if len(args) > 0 { + return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath()) + } + return nil +} + +// OnlyValidArgs returns an error if any args are not in the list of ValidArgs. +func OnlyValidArgs(cmd *Command, args []string) error { + if len(cmd.ValidArgs) > 0 { + for _, v := range args { + if !stringInSlice(v, cmd.ValidArgs) { + return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0])) + } + } + } + return nil +} + +// ArbitraryArgs never returns an error. +func ArbitraryArgs(cmd *Command, args []string) error { + return nil +} + +// MinimumNArgs returns an error if there is not at least N args. +func MinimumNArgs(n int) PositionalArgs { + return func(cmd *Command, args []string) error { + if len(args) < n { + return fmt.Errorf("requires at least %d arg(s), only received %d", n, len(args)) + } + return nil + } +} + +// MaximumNArgs returns an error if there are more than N args. +func MaximumNArgs(n int) PositionalArgs { + return func(cmd *Command, args []string) error { + if len(args) > n { + return fmt.Errorf("accepts at most %d arg(s), received %d", n, len(args)) + } + return nil + } +} + +// ExactArgs returns an error if there are not exactly n args. +func ExactArgs(n int) PositionalArgs { + return func(cmd *Command, args []string) error { + if len(args) != n { + return fmt.Errorf("accepts %d arg(s), received %d", n, len(args)) + } + return nil + } +} + +// RangeArgs returns an error if the number of args is not within the expected range. +func RangeArgs(min int, max int) PositionalArgs { + return func(cmd *Command, args []string) error { + if len(args) < min || len(args) > max { + return fmt.Errorf("accepts between %d and %d arg(s), received %d", min, max, len(args)) + } + return nil + } +} diff --git a/vendor/github.com/spf13/cobra/args_test.go b/vendor/github.com/spf13/cobra/args_test.go new file mode 100644 index 00000000..d797b6f5 --- /dev/null +++ b/vendor/github.com/spf13/cobra/args_test.go @@ -0,0 +1,241 @@ +package cobra + +import ( + "strings" + "testing" +) + +func TestNoArgs(t *testing.T) { + c := &Command{Use: "c", Args: NoArgs, Run: emptyRun} + + output, err := executeCommand(c) + if output != "" { + t.Errorf("Unexpected string: %v", output) + } + if err != nil { + t.Fatalf("Unexpected error: %v", err) + } +} + +func TestNoArgsWithArgs(t *testing.T) { + c := &Command{Use: "c", Args: NoArgs, Run: emptyRun} + + _, err := executeCommand(c, "illegal") + if err == nil { + t.Fatal("Expected an error") + } + + got := err.Error() + expected := `unknown command "illegal" for "c"` + if got != expected { + t.Errorf("Expected: %q, got: %q", expected, got) + } +} + +func TestOnlyValidArgs(t *testing.T) { + c := &Command{ + Use: "c", + Args: OnlyValidArgs, + ValidArgs: []string{"one", "two"}, + Run: emptyRun, + } + + output, err := executeCommand(c, "one", "two") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Fatalf("Unexpected error: %v", err) + } +} + +func TestOnlyValidArgsWithInvalidArgs(t *testing.T) { + c := &Command{ + Use: "c", + Args: OnlyValidArgs, + ValidArgs: []string{"one", "two"}, + Run: emptyRun, + } + + _, err := executeCommand(c, "three") + if err == nil { + t.Fatal("Expected an error") + } + + got := err.Error() + expected := `invalid argument "three" for "c"` + if got != expected { + t.Errorf("Expected: %q, got: %q", expected, got) + } +} + +func TestArbitraryArgs(t *testing.T) { + c := &Command{Use: "c", Args: ArbitraryArgs, Run: emptyRun} + output, err := executeCommand(c, "a", "b") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } +} + +func TestMinimumNArgs(t *testing.T) { + c := &Command{Use: "c", Args: MinimumNArgs(2), Run: emptyRun} + output, err := executeCommand(c, "a", "b", "c") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } +} + +func TestMinimumNArgsWithLessArgs(t *testing.T) { + c := &Command{Use: "c", Args: MinimumNArgs(2), Run: emptyRun} + _, err := executeCommand(c, "a") + + if err == nil { + t.Fatal("Expected an error") + } + + got := err.Error() + expected := "requires at least 2 arg(s), only received 1" + if got != expected { + t.Fatalf("Expected %q, got %q", expected, got) + } +} + +func TestMaximumNArgs(t *testing.T) { + c := &Command{Use: "c", Args: MaximumNArgs(3), Run: emptyRun} + output, err := executeCommand(c, "a", "b") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } +} + +func TestMaximumNArgsWithMoreArgs(t *testing.T) { + c := &Command{Use: "c", Args: MaximumNArgs(2), Run: emptyRun} + _, err := executeCommand(c, "a", "b", "c") + + if err == nil { + t.Fatal("Expected an error") + } + + got := err.Error() + expected := "accepts at most 2 arg(s), received 3" + if got != expected { + t.Fatalf("Expected %q, got %q", expected, got) + } +} + +func TestExactArgs(t *testing.T) { + c := &Command{Use: "c", Args: ExactArgs(3), Run: emptyRun} + output, err := executeCommand(c, "a", "b", "c") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } +} + +func TestExactArgsWithInvalidCount(t *testing.T) { + c := &Command{Use: "c", Args: ExactArgs(2), Run: emptyRun} + _, err := executeCommand(c, "a", "b", "c") + + if err == nil { + t.Fatal("Expected an error") + } + + got := err.Error() + expected := "accepts 2 arg(s), received 3" + if got != expected { + t.Fatalf("Expected %q, got %q", expected, got) + } +} + +func TestRangeArgs(t *testing.T) { + c := &Command{Use: "c", Args: RangeArgs(2, 4), Run: emptyRun} + output, err := executeCommand(c, "a", "b", "c") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } +} + +func TestRangeArgsWithInvalidCount(t *testing.T) { + c := &Command{Use: "c", Args: RangeArgs(2, 4), Run: emptyRun} + _, err := executeCommand(c, "a") + + if err == nil { + t.Fatal("Expected an error") + } + + got := err.Error() + expected := "accepts between 2 and 4 arg(s), received 1" + if got != expected { + t.Fatalf("Expected %q, got %q", expected, got) + } +} + +func TestRootTakesNoArgs(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + childCmd := &Command{Use: "child", Run: emptyRun} + rootCmd.AddCommand(childCmd) + + _, err := executeCommand(rootCmd, "illegal", "args") + if err == nil { + t.Fatal("Expected an error") + } + + got := err.Error() + expected := `unknown command "illegal" for "root"` + if !strings.Contains(got, expected) { + t.Errorf("expected %q, got %q", expected, got) + } +} + +func TestRootTakesArgs(t *testing.T) { + rootCmd := &Command{Use: "root", Args: ArbitraryArgs, Run: emptyRun} + childCmd := &Command{Use: "child", Run: emptyRun} + rootCmd.AddCommand(childCmd) + + _, err := executeCommand(rootCmd, "legal", "args") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } +} + +func TestChildTakesNoArgs(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + childCmd := &Command{Use: "child", Args: NoArgs, Run: emptyRun} + rootCmd.AddCommand(childCmd) + + _, err := executeCommand(rootCmd, "child", "illegal", "args") + if err == nil { + t.Fatal("Expected an error") + } + + got := err.Error() + expected := `unknown command "illegal" for "root child"` + if !strings.Contains(got, expected) { + t.Errorf("expected %q, got %q", expected, got) + } +} + +func TestChildTakesArgs(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + childCmd := &Command{Use: "child", Args: ArbitraryArgs, Run: emptyRun} + rootCmd.AddCommand(childCmd) + + _, err := executeCommand(rootCmd, "child", "legal", "args") + if err != nil { + t.Fatalf("Unexpected error: %v", err) + } +} diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go index 82c4274a..291eae7d 100644 --- a/vendor/github.com/spf13/cobra/bash_completions.go +++ b/vendor/github.com/spf13/cobra/bash_completions.go @@ -3,6 +3,7 @@ package cobra import ( "bytes" "fmt" + "io" "os" "sort" "strings" @@ -10,24 +11,33 @@ import ( "github.com/spf13/pflag" ) +// Annotations for Bash completion. const ( - BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extentions" + BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extensions" + BashCompCustom = "cobra_annotation_bash_completion_custom" BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag" BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir" ) -func preamble(out *bytes.Buffer) { - fmt.Fprintf(out, `#!/bin/bash - - -__debug() +func writePreamble(buf *bytes.Buffer, name string) { + buf.WriteString(fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name)) + buf.WriteString(fmt.Sprintf(` +__%[1]s_debug() { if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then echo "$*" >> "${BASH_COMP_DEBUG_FILE}" fi } -__index_of_word() +# Homebrew on Macs have version 1.3 of bash-completion which doesn't include +# _init_completion. This is a very minimal version of that function. +__%[1]s_init_completion() +{ + COMPREPLY=() + _get_comp_words_by_ref "$@" cur prev words cword +} + +__%[1]s_index_of_word() { local w word=$1 shift @@ -39,7 +49,7 @@ __index_of_word() index=-1 } -__contains_word() +__%[1]s_contains_word() { local w word=$1; shift for w in "$@"; do @@ -48,12 +58,14 @@ __contains_word() return 1 } -__handle_reply() +__%[1]s_handle_reply() { - __debug "${FUNCNAME}" + __%[1]s_debug "${FUNCNAME[0]}" case $cur in -*) - compopt -o nospace + if [[ $(type -t compopt) = "builtin" ]]; then + compopt -o nospace + fi local allflags if [ ${#must_have_one_flag[@]} -ne 0 ]; then allflags=("${must_have_one_flag[@]}") @@ -61,14 +73,37 @@ __handle_reply() allflags=("${flags[*]} ${two_word_flags[*]}") fi COMPREPLY=( $(compgen -W "${allflags[*]}" -- "$cur") ) - [[ $COMPREPLY == *= ]] || compopt +o nospace + if [[ $(type -t compopt) = "builtin" ]]; then + [[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace + fi + + # complete after --flag=abc + if [[ $cur == *=* ]]; then + if [[ $(type -t compopt) = "builtin" ]]; then + compopt +o nospace + fi + + local index flag + flag="${cur%%=*}" + __%[1]s_index_of_word "${flag}" "${flags_with_completion[@]}" + COMPREPLY=() + if [[ ${index} -ge 0 ]]; then + PREFIX="" + cur="${cur#*=}" + ${flags_completion[${index}]} + if [ -n "${ZSH_VERSION}" ]; then + # zsh completion needs --flag= prefix + eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )" + fi + fi + fi return 0; ;; esac # check if we are handling a flag with special work handling local index - __index_of_word "${prev}" "${flags_with_completion[@]}" + __%[1]s_index_of_word "${prev}" "${flags_with_completion[@]}" if [[ ${index} -ge 0 ]]; then ${flags_completion[${index}]} return @@ -80,51 +115,85 @@ __handle_reply() fi local completions - if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then - completions=("${must_have_one_flag[@]}") - elif [[ ${#must_have_one_noun[@]} -ne 0 ]]; then + completions=("${commands[@]}") + if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then completions=("${must_have_one_noun[@]}") - else - completions=("${commands[@]}") + fi + if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then + completions+=("${must_have_one_flag[@]}") fi COMPREPLY=( $(compgen -W "${completions[*]}" -- "$cur") ) + if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then + COMPREPLY=( $(compgen -W "${noun_aliases[*]}" -- "$cur") ) + fi + if [[ ${#COMPREPLY[@]} -eq 0 ]]; then declare -F __custom_func >/dev/null && __custom_func fi + + # available in bash-completion >= 2, not always present on macOS + if declare -F __ltrim_colon_completions >/dev/null; then + __ltrim_colon_completions "$cur" + fi + + # If there is only 1 completion and it is a flag with an = it will be completed + # but we don't want a space after the = + if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then + compopt -o nospace + fi } # The arguments should be in the form "ext1|ext2|extn" -__handle_filename_extension_flag() +__%[1]s_handle_filename_extension_flag() { local ext="$1" _filedir "@(${ext})" } -__handle_subdirs_in_dir_flag() +__%[1]s_handle_subdirs_in_dir_flag() { local dir="$1" pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 } -__handle_flag() +__%[1]s_handle_flag() { - __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}" + __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" # if a command required a flag, and we found it, unset must_have_one_flag() local flagname=${words[c]} + local flagvalue # if the word contained an = if [[ ${words[c]} == *"="* ]]; then + flagvalue=${flagname#*=} # take in as flagvalue after the = flagname=${flagname%%=*} # strip everything after the = flagname="${flagname}=" # but put the = back fi - __debug "${FUNCNAME}: looking for ${flagname}" - if __contains_word "${flagname}" "${must_have_one_flag[@]}"; then + __%[1]s_debug "${FUNCNAME[0]}: looking for ${flagname}" + if __%[1]s_contains_word "${flagname}" "${must_have_one_flag[@]}"; then must_have_one_flag=() fi + # if you set a flag which only applies to this command, don't show subcommands + if __%[1]s_contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then + commands=() + fi + + # keep flag value with flagname as flaghash + # flaghash variable is an associative array which is only supported in bash > 3. + if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then + if [ -n "${flagvalue}" ] ; then + flaghash[${flagname}]=${flagvalue} + elif [ -n "${words[ $((c+1)) ]}" ] ; then + flaghash[${flagname}]=${words[ $((c+1)) ]} + else + flaghash[${flagname}]="true" # pad "true" for bool flag + fi + fi + # skip the argument to a two word flag - if __contains_word "${words[c]}" "${two_word_flags[@]}"; then + if __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then c=$((c+1)) # if we are looking for a flags value, don't show commands if [[ $c -eq $cword ]]; then @@ -132,16 +201,17 @@ __handle_flag() fi fi - # skip the flag itself c=$((c+1)) } -__handle_noun() +__%[1]s_handle_noun() { - __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}" + __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - if __contains_word "${words[c]}" "${must_have_one_noun[@]}"; then + if __%[1]s_contains_word "${words[c]}" "${must_have_one_noun[@]}"; then + must_have_one_noun=() + elif __%[1]s_contains_word "${words[c]}" "${noun_aliases[@]}"; then must_have_one_noun=() fi @@ -149,235 +219,327 @@ __handle_noun() c=$((c+1)) } -__handle_command() +__%[1]s_handle_command() { - __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}" + __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" local next_command if [[ -n ${last_command} ]]; then - next_command="_${last_command}_${words[c]}" + next_command="_${last_command}_${words[c]//:/__}" else - next_command="_${words[c]}" + if [[ $c -eq 0 ]]; then + next_command="_%[1]s_root_command" + else + next_command="_${words[c]//:/__}" + fi fi c=$((c+1)) - __debug "${FUNCNAME}: looking for ${next_command}" - declare -F $next_command >/dev/null && $next_command + __%[1]s_debug "${FUNCNAME[0]}: looking for ${next_command}" + declare -F "$next_command" >/dev/null && $next_command } -__handle_word() +__%[1]s_handle_word() { if [[ $c -ge $cword ]]; then - __handle_reply - return + __%[1]s_handle_reply + return fi - __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}" + __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" if [[ "${words[c]}" == -* ]]; then - __handle_flag - elif __contains_word "${words[c]}" "${commands[@]}"; then - __handle_command + __%[1]s_handle_flag + elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then + __%[1]s_handle_command + elif [[ $c -eq 0 ]]; then + __%[1]s_handle_command else - __handle_noun + __%[1]s_handle_noun fi - __handle_word + __%[1]s_handle_word } -`) +`, name)) } -func postscript(out *bytes.Buffer, name string) { - fmt.Fprintf(out, "__start_%s()\n", name) - fmt.Fprintf(out, `{ +func writePostscript(buf *bytes.Buffer, name string) { + name = strings.Replace(name, ":", "__", -1) + buf.WriteString(fmt.Sprintf("__start_%s()\n", name)) + buf.WriteString(fmt.Sprintf(`{ local cur prev words cword - _init_completion -s || return + declare -A flaghash 2>/dev/null || : + if declare -F _init_completion >/dev/null 2>&1; then + _init_completion -s || return + else + __%[1]s_init_completion -n "=" || return + fi local c=0 local flags=() local two_word_flags=() + local local_nonpersistent_flags=() local flags_with_completion=() local flags_completion=() - local commands=("%s") + local commands=("%[1]s") local must_have_one_flag=() local must_have_one_noun=() local last_command local nouns=() - __handle_word + __%[1]s_handle_word } -`, name) - fmt.Fprintf(out, "complete -F __start_%s %s\n", name, name) - fmt.Fprintf(out, "# ex: ts=4 sw=4 et filetype=sh\n") +`, 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)) + buf.WriteString("# ex: ts=4 sw=4 et filetype=sh\n") } -func writeCommands(cmd *Command, out *bytes.Buffer) { - fmt.Fprintf(out, " commands=()\n") +func writeCommands(buf *bytes.Buffer, cmd *Command) { + buf.WriteString(" commands=()\n") for _, c := range cmd.Commands() { - if len(c.Deprecated) > 0 { + if !c.IsAvailableCommand() || c == cmd.helpCommand { continue } - fmt.Fprintf(out, " commands+=(%q)\n", c.Name()) + buf.WriteString(fmt.Sprintf(" commands+=(%q)\n", c.Name())) } - fmt.Fprintf(out, "\n") + buf.WriteString("\n") } -func writeFlagHandler(name string, annotations map[string][]string, out *bytes.Buffer) { +func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]string, cmd *Command) { for key, value := range annotations { switch key { case BashCompFilenameExt: - fmt.Fprintf(out, " flags_with_completion+=(%q)\n", name) + 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, "|") - fmt.Fprintf(out, " flags_completion+=(%q)\n", ext) + ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Root().Name()) + strings.Join(value, "|") } else { - ext := "_filedir" - fmt.Fprintf(out, " flags_completion+=(%q)\n", ext) + ext = "_filedir" + } + buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext)) + case BashCompCustom: + buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) + if len(value) > 0 { + handlers := strings.Join(value, "; ") + buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", handlers)) + } else { + buf.WriteString(" flags_completion+=(:)\n") } case BashCompSubdirsInDir: - fmt.Fprintf(out, " 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] - fmt.Fprintf(out, " flags_completion+=(%q)\n", ext) + ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Root().Name()) + value[0] } else { - ext := "_filedir -d" - fmt.Fprintf(out, " flags_completion+=(%q)\n", ext) + ext = "_filedir -d" } + buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext)) } } } -func writeShortFlag(flag *pflag.Flag, out *bytes.Buffer) { - b := (flag.Value.Type() == "bool") +func writeShortFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) { name := flag.Shorthand format := " " - if !b { + if len(flag.NoOptDefVal) == 0 { format += "two_word_" } format += "flags+=(\"-%s\")\n" - fmt.Fprintf(out, format, name) - writeFlagHandler("-"+name, flag.Annotations, out) + buf.WriteString(fmt.Sprintf(format, name)) + writeFlagHandler(buf, "-"+name, flag.Annotations, cmd) } -func writeFlag(flag *pflag.Flag, out *bytes.Buffer) { - b := (flag.Value.Type() == "bool") +func writeFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) { name := flag.Name format := " flags+=(\"--%s" - if !b { + if len(flag.NoOptDefVal) == 0 { format += "=" } format += "\")\n" - fmt.Fprintf(out, format, name) - writeFlagHandler("--"+name, flag.Annotations, out) + buf.WriteString(fmt.Sprintf(format, name)) + writeFlagHandler(buf, "--"+name, flag.Annotations, cmd) } -func writeFlags(cmd *Command, out *bytes.Buffer) { - fmt.Fprintf(out, ` flags=() +func writeLocalNonPersistentFlag(buf *bytes.Buffer, flag *pflag.Flag) { + name := flag.Name + format := " local_nonpersistent_flags+=(\"--%s" + if len(flag.NoOptDefVal) == 0 { + format += "=" + } + format += "\")\n" + buf.WriteString(fmt.Sprintf(format, name)) +} + +func writeFlags(buf *bytes.Buffer, cmd *Command) { + buf.WriteString(` flags=() two_word_flags=() + local_nonpersistent_flags=() flags_with_completion=() flags_completion=() `) + localNonPersistentFlags := cmd.LocalNonPersistentFlags() cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { - writeFlag(flag, out) + if nonCompletableFlag(flag) { + return + } + writeFlag(buf, flag, cmd) if len(flag.Shorthand) > 0 { - writeShortFlag(flag, out) + writeShortFlag(buf, flag, cmd) + } + if localNonPersistentFlags.Lookup(flag.Name) != nil { + writeLocalNonPersistentFlag(buf, flag) + } + }) + cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { + if nonCompletableFlag(flag) { + return + } + writeFlag(buf, flag, cmd) + if len(flag.Shorthand) > 0 { + writeShortFlag(buf, flag, cmd) } }) - fmt.Fprintf(out, "\n") + buf.WriteString("\n") } -func writeRequiredFlag(cmd *Command, out *bytes.Buffer) { - fmt.Fprintf(out, " must_have_one_flag=()\n") +func writeRequiredFlag(buf *bytes.Buffer, cmd *Command) { + buf.WriteString(" must_have_one_flag=()\n") flags := cmd.NonInheritedFlags() flags.VisitAll(func(flag *pflag.Flag) { - for key, _ := range flag.Annotations { + if nonCompletableFlag(flag) { + return + } + for key := range flag.Annotations { 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" - fmt.Fprintf(out, format, flag.Name) + buf.WriteString(fmt.Sprintf(format, flag.Name)) if len(flag.Shorthand) > 0 { - fmt.Fprintf(out, " must_have_one_flag+=(\"-%s\")\n", flag.Shorthand) + buf.WriteString(fmt.Sprintf(" must_have_one_flag+=(\"-%s\")\n", flag.Shorthand)) } } } }) } -func writeRequiredNoun(cmd *Command, out *bytes.Buffer) { - fmt.Fprintf(out, " must_have_one_noun=()\n") +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 { - fmt.Fprintf(out, " must_have_one_noun+=(%q)\n", value) + buf.WriteString(fmt.Sprintf(" must_have_one_noun+=(%q)\n", value)) } } -func gen(cmd *Command, out *bytes.Buffer) { +func writeArgAliases(buf *bytes.Buffer, cmd *Command) { + buf.WriteString(" noun_aliases=()\n") + sort.Sort(sort.StringSlice(cmd.ArgAliases)) + for _, value := range cmd.ArgAliases { + buf.WriteString(fmt.Sprintf(" noun_aliases+=(%q)\n", value)) + } +} + +func gen(buf *bytes.Buffer, cmd *Command) { for _, c := range cmd.Commands() { - if len(c.Deprecated) > 0 { + if !c.IsAvailableCommand() || c == cmd.helpCommand { continue } - gen(c, out) + gen(buf, c) } commandName := cmd.CommandPath() commandName = strings.Replace(commandName, " ", "_", -1) - fmt.Fprintf(out, "_%s()\n{\n", commandName) - fmt.Fprintf(out, " last_command=%q\n", commandName) - writeCommands(cmd, out) - writeFlags(cmd, out) - writeRequiredFlag(cmd, out) - writeRequiredNoun(cmd, out) - fmt.Fprintf(out, "}\n\n") -} + commandName = strings.Replace(commandName, ":", "__", -1) -func (cmd *Command) GenBashCompletion(out *bytes.Buffer) { - preamble(out) - if len(cmd.BashCompletionFunction) > 0 { - fmt.Fprintf(out, "%s\n", cmd.BashCompletionFunction) + if cmd.Root() == cmd { + buf.WriteString(fmt.Sprintf("_%s_root_command()\n{\n", commandName)) + } else { + buf.WriteString(fmt.Sprintf("_%s()\n{\n", commandName)) } - gen(cmd, out) - postscript(out, cmd.Name()) + + 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") } -func (cmd *Command) GenBashCompletionFile(filename string) error { - out := new(bytes.Buffer) +// GenBashCompletion generates bash completion file and writes to the passed writer. +func (c *Command) GenBashCompletion(w io.Writer) error { + buf := new(bytes.Buffer) + writePreamble(buf, c.Name()) + if len(c.BashCompletionFunction) > 0 { + buf.WriteString(c.BashCompletionFunction + "\n") + } + gen(buf, c) + writePostscript(buf, c.Name()) - cmd.GenBashCompletion(out) + _, err := buf.WriteTo(w) + return err +} +func nonCompletableFlag(flag *pflag.Flag) bool { + return flag.Hidden || len(flag.Deprecated) > 0 +} + +// GenBashCompletionFile generates bash completion file. +func (c *Command) GenBashCompletionFile(filename string) error { outFile, err := os.Create(filename) if err != nil { return err } defer outFile.Close() - _, err = outFile.Write(out.Bytes()) - if err != nil { - return err - } - return nil + return c.GenBashCompletion(outFile) } -// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag, if it exists. -func (cmd *Command) MarkFlagRequired(name string) error { - return MarkFlagRequired(cmd.Flags(), name) +// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag if it exists, +// and causes your command to report an error if invoked without the flag. +func (c *Command) MarkFlagRequired(name string) error { + return MarkFlagRequired(c.Flags(), name) } -// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag in the flag set, if it exists. +// MarkPersistentFlagRequired adds the BashCompOneRequiredFlag annotation to the named persistent flag if it exists, +// and causes your command to report an error if invoked without the flag. +func (c *Command) MarkPersistentFlagRequired(name string) error { + return MarkFlagRequired(c.PersistentFlags(), name) +} + +// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag if it exists, +// and causes your command to report an error if invoked without the flag. func MarkFlagRequired(flags *pflag.FlagSet, name string) error { return flags.SetAnnotation(name, BashCompOneRequiredFlag, []string{"true"}) } // MarkFlagFilename adds the BashCompFilenameExt annotation to the named flag, if it exists. // Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided. -func (cmd *Command) MarkFlagFilename(name string, extensions ...string) error { - return MarkFlagFilename(cmd.Flags(), name, extensions...) +func (c *Command) MarkFlagFilename(name string, extensions ...string) error { + return MarkFlagFilename(c.Flags(), name, extensions...) +} + +// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. +// Generated bash autocompletion will call the bash function f for the flag. +func (c *Command) MarkFlagCustom(name string, f string) error { + return MarkFlagCustom(c.Flags(), name, f) +} + +// MarkPersistentFlagFilename adds the BashCompFilenameExt annotation to the named persistent flag, if it exists. +// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided. +func (c *Command) MarkPersistentFlagFilename(name string, extensions ...string) error { + return MarkFlagFilename(c.PersistentFlags(), name, extensions...) } // MarkFlagFilename adds the BashCompFilenameExt annotation to the named flag in the flag set, if it exists. @@ -385,3 +547,9 @@ func (cmd *Command) MarkFlagFilename(name string, extensions ...string) error { func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error { return flags.SetAnnotation(name, BashCompFilenameExt, extensions) } + +// MarkFlagCustom adds the BashCompCustom annotation to the named flag in the flag set, if it exists. +// Generated bash autocompletion will call the bash function f for the flag. +func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error { + return flags.SetAnnotation(name, BashCompCustom, []string{f}) +} diff --git a/vendor/github.com/spf13/cobra/bash_completions.md b/vendor/github.com/spf13/cobra/bash_completions.md index 204704ef..8d01f456 100644 --- a/vendor/github.com/spf13/cobra/bash_completions.md +++ b/vendor/github.com/spf13/cobra/bash_completions.md @@ -6,19 +6,20 @@ Generating bash completions from a cobra command is incredibly easy. An actual p package main import ( - "io/ioutil" - "os" + "io/ioutil" + "os" - "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd" + "k8s.io/kubernetes/pkg/kubectl/cmd" + "k8s.io/kubernetes/pkg/kubectl/cmd/util" ) func main() { - kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard) - kubectl.GenBashCompletionFile("out.sh") + kubectl := cmd.NewKubectlCommand(util.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard) + kubectl.GenBashCompletionFile("out.sh") } ``` -That will get you completions of subcommands and flags. If you make additional annotations to your code, you can get even more intelligent and flexible behavior. +`out.sh` will get you completions of subcommands and flags. Copy it to `/etc/bash_completion.d/` as described [here](https://debian-administration.org/article/316/An_introduction_to_bash_completion_part_1) and reset your terminal to use autocompletion. If you make additional annotations to your code, you can get even more intelligent and flexible behavior. ## Creating your own custom functions @@ -80,7 +81,7 @@ The `BashCompletionFunction` option is really only valid/useful on the root comm In the above example "pod" was assumed to already be typed. But if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. Simplified code from `kubectl get` looks like: ```go -validArgs []string = { "pods", "nodes", "services", "replicationControllers" } +validArgs []string = { "pod", "node", "service", "replicationcontroller" } cmd := &cobra.Command{ Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)", @@ -99,9 +100,34 @@ Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give result ```bash # kubectl get [tab][tab] -nodes pods replicationControllers services +node pod replicationcontroller service ``` +## Plural form and shortcuts for nouns + +If your nouns have a number of aliases, you can define them alongside `ValidArgs` using `ArgAliases`: + +```go +argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" } + +cmd := &cobra.Command{ + ... + ValidArgs: validArgs, + ArgAliases: argAliases +} +``` + +The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by +the completion algorithm if entered manually, e.g. in: + +```bash +# kubectl get rc [tab][tab] +backend frontend database +``` + +Note that without declaring `rc` as an alias, the completion algorithm would show the list of nouns +in this example again instead of the replication controllers. + ## Mark flags as required Most of the time completions will only show subcommands. But if a flag is required to make a subcommand work, you probably want it to show up when the user types [tab][tab]. Marking a flag as 'Required' is incredibly easy. @@ -147,3 +173,49 @@ hello.yml test.json ``` So while there are many other files in the CWD it only shows me subdirs and those with valid extensions. + +# Specify custom flag completion + +Similar to the filename completion and filtering using cobra.BashCompFilenameExt, you can specify +a custom flag completion function with cobra.BashCompCustom: + +```go + annotation := make(map[string][]string) + annotation[cobra.BashCompFilenameExt] = []string{"__kubectl_get_namespaces"} + + flag := &pflag.Flag{ + Name: "namespace", + Usage: usage, + Annotations: annotation, + } + cmd.Flags().AddFlag(flag) +``` + +In addition add the `__handle_namespace_flag` implementation in the `BashCompletionFunction` +value, e.g.: + +```bash +__kubectl_get_namespaces() +{ + local template + template="{{ range .items }}{{ .metadata.name }} {{ end }}" + local kubectl_out + if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then + COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) ) + fi +} +``` +# Using bash aliases for commands + +You can also configure the `bash aliases` for the commands and they will also support completions. + +```bash +alias aliasname=origcommand +complete -o default -F __start_origcommand aliasname + +# and now when you run `aliasname` completion will make +# suggestions as it did for `origcommand`. + +$) aliasname +completion firstcommand secondcommand +``` diff --git a/vendor/github.com/spf13/cobra/bash_completions_test.go b/vendor/github.com/spf13/cobra/bash_completions_test.go index a1f2b13c..02a4f15b 100644 --- a/vendor/github.com/spf13/cobra/bash_completions_test.go +++ b/vendor/github.com/spf13/cobra/bash_completions_test.go @@ -4,84 +4,214 @@ import ( "bytes" "fmt" "os" + "os/exec" + "regexp" "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) + t.Errorf("Got: %q\nBut should not have!\n", unexpected) } } func check(t *testing.T, found, expected string) { if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) + t.Errorf("Expecting to contain: \n %q\nGot:\n %q\n", expected, found) } } +func checkRegex(t *testing.T, found, pattern string) { + matched, err := regexp.MatchString(pattern, found) + if err != nil { + t.Errorf("Error thrown performing MatchString: \n %s\n", err) + } + if !matched { + t.Errorf("Expecting to match: \n %q\nGot:\n %q\n", pattern, found) + } +} + +func runShellCheck(s string) error { + excluded := []string{ + "SC2034", // PREFIX appears unused. Verify it or export it. + } + cmd := exec.Command("shellcheck", "-s", "bash", "-", "-e", strings.Join(excluded, ",")) + cmd.Stderr = os.Stderr + cmd.Stdout = os.Stdout + + stdin, err := cmd.StdinPipe() + if err != nil { + return err + } + go func() { + stdin.Write([]byte(s)) + stdin.Close() + }() + + return cmd.Run() +} + // World worst custom function, just keep telling you to enter hello! -const ( - bash_completion_func = `__custom_func() { -COMPREPLY=( "hello" ) +const bashCompletionFunc = `__custom_func() { + COMPREPLY=( "hello" ) } ` -) func TestBashCompletions(t *testing.T) { - c := initializeWithRootCmd() - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdEcho, cmdPrint, cmdDeprecated) + rootCmd := &Command{ + Use: "root", + ArgAliases: []string{"pods", "nodes", "services", "replicationcontrollers", "po", "no", "svc", "rc"}, + ValidArgs: []string{"pod", "node", "service", "replicationcontroller"}, + BashCompletionFunction: bashCompletionFunc, + Run: emptyRun, + } + rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot") + rootCmd.MarkFlagRequired("introot") - // custom completion function - c.BashCompletionFunction = bash_completion_func + // Filename. + rootCmd.Flags().String("filename", "", "Enter a filename") + rootCmd.MarkFlagFilename("filename", "json", "yaml", "yml") - // required flag - c.MarkFlagRequired("introot") + // Persistent filename. + rootCmd.PersistentFlags().String("persistent-filename", "", "Enter a filename") + rootCmd.MarkPersistentFlagFilename("persistent-filename") + rootCmd.MarkPersistentFlagRequired("persistent-filename") - // valid nouns - validArgs := []string{"pods", "nodes", "services", "replicationControllers"} - c.ValidArgs = validArgs + // Filename extensions. + rootCmd.Flags().String("filename-ext", "", "Enter a filename (extension limited)") + rootCmd.MarkFlagFilename("filename-ext") + rootCmd.Flags().String("custom", "", "Enter a filename (extension limited)") + rootCmd.MarkFlagCustom("custom", "__complete_custom") - // filename - var flagval string - c.Flags().StringVar(&flagval, "filename", "", "Enter a filename") - c.MarkFlagFilename("filename", "json", "yaml", "yml") + // Subdirectories in a given directory. + rootCmd.Flags().String("theme", "", "theme to use (located in /themes/THEMENAME/)") + rootCmd.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"}) - // filename extensions - var flagvalExt string - c.Flags().StringVar(&flagvalExt, "filename-ext", "", "Enter a filename (extension limited)") - c.MarkFlagFilename("filename-ext") + echoCmd := &Command{ + Use: "echo [string to echo]", + Aliases: []string{"say"}, + Short: "Echo anything to the screen", + Long: "an utterly useless command for testing.", + Example: "Just run cobra-test echo", + Run: emptyRun, + } - // subdirectories in a given directory - var flagvalTheme string - c.Flags().StringVar(&flagvalTheme, "theme", "", "theme to use (located in /themes/THEMENAME/)") - c.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"}) + echoCmd.Flags().String("filename", "", "Enter a filename") + echoCmd.MarkFlagFilename("filename", "json", "yaml", "yml") + echoCmd.Flags().String("config", "", "config to use (located in /config/PROFILE/)") + echoCmd.Flags().SetAnnotation("config", BashCompSubdirsInDir, []string{"config"}) - out := new(bytes.Buffer) - c.GenBashCompletion(out) - str := out.String() + printCmd := &Command{ + Use: "print [string to print]", + Args: MinimumNArgs(1), + Short: "Print anything to the screen", + Long: "an absolutely utterly useless command for testing.", + Run: emptyRun, + } - check(t, str, "_cobra-test") - check(t, str, "_cobra-test_echo") - check(t, str, "_cobra-test_echo_times") - check(t, str, "_cobra-test_print") + deprecatedCmd := &Command{ + Use: "deprecated [can't do anything here]", + Args: NoArgs, + Short: "A command which is deprecated", + Long: "an absolutely utterly useless command for testing deprecation!.", + Deprecated: "Please use echo instead", + Run: emptyRun, + } + + colonCmd := &Command{ + Use: "cmd:colon", + Run: emptyRun, + } + + timesCmd := &Command{ + Use: "times [# times] [string to echo]", + SuggestFor: []string{"counts"}, + Args: OnlyValidArgs, + ValidArgs: []string{"one", "two", "three", "four"}, + Short: "Echo anything to the screen more times", + Long: "a slightly useless command for testing.", + Run: emptyRun, + } + + echoCmd.AddCommand(timesCmd) + rootCmd.AddCommand(echoCmd, printCmd, deprecatedCmd, colonCmd) + + buf := new(bytes.Buffer) + rootCmd.GenBashCompletion(buf) + output := buf.String() + + check(t, output, "_root") + check(t, output, "_root_echo") + check(t, output, "_root_echo_times") + check(t, output, "_root_print") + check(t, output, "_root_cmd__colon") // check for required flags - check(t, str, `must_have_one_flag+=("--introot=")`) + check(t, output, `must_have_one_flag+=("--introot=")`) + check(t, output, `must_have_one_flag+=("--persistent-filename=")`) // check for custom completion function - check(t, str, `COMPREPLY=( "hello" )`) + check(t, output, `COMPREPLY=( "hello" )`) // check for required nouns - check(t, str, `must_have_one_noun+=("pods")`) + check(t, output, `must_have_one_noun+=("pod")`) + // check for noun aliases + check(t, output, `noun_aliases+=("pods")`) + check(t, output, `noun_aliases+=("rc")`) + checkOmit(t, output, `must_have_one_noun+=("pods")`) // check for filename extension flags - check(t, str, `flags_completion+=("_filedir")`) + check(t, output, `flags_completion+=("_filedir")`) // check for filename extension flags - check(t, str, `flags_completion+=("__handle_filename_extension_flag json|yaml|yml")`) + check(t, output, `must_have_one_noun+=("three")`) + // check for filename extension flags + check(t, output, fmt.Sprintf(`flags_completion+=("__%s_handle_filename_extension_flag json|yaml|yml")`, rootCmd.Name())) + // check for filename extension flags in a subcommand + checkRegex(t, output, fmt.Sprintf(`_root_echo\(\)\n{[^}]*flags_completion\+=\("__%s_handle_filename_extension_flag json\|yaml\|yml"\)`, rootCmd.Name())) + // check for custom flags + check(t, output, `flags_completion+=("__complete_custom")`) // check for subdirs_in_dir flags - check(t, str, `flags_completion+=("__handle_subdirs_in_dir_flag themes")`) + check(t, output, fmt.Sprintf(`flags_completion+=("__%s_handle_subdirs_in_dir_flag themes")`, rootCmd.Name())) + // check for subdirs_in_dir flags in a subcommand + checkRegex(t, output, fmt.Sprintf(`_root_echo\(\)\n{[^}]*flags_completion\+=\("__%s_handle_subdirs_in_dir_flag config"\)`, rootCmd.Name())) - checkOmit(t, str, cmdDeprecated.Name()) + checkOmit(t, output, deprecatedCmd.Name()) + + // If available, run shellcheck against the script. + if err := exec.Command("which", "shellcheck").Run(); err != nil { + return + } + if err := runShellCheck(output); err != nil { + t.Fatalf("shellcheck failed: %v", err) + } +} + +func TestBashCompletionHiddenFlag(t *testing.T) { + c := &Command{Use: "c", Run: emptyRun} + + const flagName = "hiddenFlag" + c.Flags().Bool(flagName, false, "") + c.Flags().MarkHidden(flagName) + + buf := new(bytes.Buffer) + c.GenBashCompletion(buf) + output := buf.String() + + if strings.Contains(output, flagName) { + t.Errorf("Expected completion to not include %q flag: Got %v", flagName, output) + } +} + +func TestBashCompletionDeprecatedFlag(t *testing.T) { + c := &Command{Use: "c", Run: emptyRun} + + const flagName = "deprecated-flag" + c.Flags().Bool(flagName, false, "") + c.Flags().MarkDeprecated(flagName, "use --not-deprecated instead") + + buf := new(bytes.Buffer) + c.GenBashCompletion(buf) + output := buf.String() + + if strings.Contains(output, flagName) { + t.Errorf("expected completion to not include %q flag: Got %v", flagName, output) + } } diff --git a/vendor/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go index 78b92b0a..7010fd15 100644 --- a/vendor/github.com/spf13/cobra/cobra.go +++ b/vendor/github.com/spf13/cobra/cobra.go @@ -23,32 +23,64 @@ import ( "strconv" "strings" "text/template" + "unicode" ) +var templateFuncs = template.FuncMap{ + "trim": strings.TrimSpace, + "trimRightSpace": trimRightSpace, + "trimTrailingWhitespaces": trimRightSpace, + "appendIfNotPresent": appendIfNotPresent, + "rpad": rpad, + "gt": Gt, + "eq": Eq, +} + var initializers []func() -// automatic prefix matching can be a dangerous thing to automatically enable in CLI tools. -// Set this to true to enable it -var EnablePrefixMatching bool = false +// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing +// to automatically enable in CLI tools. +// Set this to true to enable it. +var EnablePrefixMatching = false -// enables an information splash screen on Windows if the CLI is started from explorer.exe. -var EnableWindowsMouseTrap bool = true +// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default. +// To disable sorting, set it to false. +var EnableCommandSorting = true -var MousetrapHelpText string = `This is a command line tool +// MousetrapHelpText enables an information splash screen on Windows +// if the CLI is started from explorer.exe. +// To disable the mousetrap, just set this variable to blank string (""). +// Works only on Microsoft Windows. +var MousetrapHelpText string = `This is a command line tool. You need to open cmd.exe and run it from there. ` -//OnInitialize takes a series of func() arguments and appends them to a slice of func(). -func OnInitialize(y ...func()) { - for _, x := range y { - initializers = append(initializers, x) +// AddTemplateFunc adds a template function that's available to Usage and Help +// template generation. +func AddTemplateFunc(name string, tmplFunc interface{}) { + templateFuncs[name] = tmplFunc +} + +// AddTemplateFuncs adds multiple template functions that are available to Usage and +// Help template generation. +func AddTemplateFuncs(tmplFuncs template.FuncMap) { + for k, v := range tmplFuncs { + templateFuncs[k] = v } } -//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. +// OnInitialize sets the passed functions to be run when each command's +// Execute method is called. +func OnInitialize(y ...func()) { + initializers = append(initializers, y...) +} + +// 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) @@ -76,7 +108,9 @@ func Gt(a interface{}, b interface{}) bool { return left > right } -//Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic. +// 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) @@ -92,7 +126,21 @@ func Eq(a interface{}, b interface{}) bool { return false } -//rpad adds padding to the right of a string +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) return fmt.Sprintf(template, s) @@ -101,12 +149,52 @@ 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") - t.Funcs(template.FuncMap{ - "trim": strings.TrimSpace, - "rpad": rpad, - "gt": Gt, - "eq": Eq, - }) + t.Funcs(templateFuncs) template.Must(t.Parse(text)) return t.Execute(w, data) } + +// ld compares two strings and returns the levenshtein distance between them. +func ld(s, t string, ignoreCase bool) int { + if ignoreCase { + s = strings.ToLower(s) + t = strings.ToLower(t) + } + d := make([][]int, len(s)+1) + for i := range d { + d[i] = make([]int, len(t)+1) + } + for i := range d { + d[i][0] = i + } + for j := range d[0] { + d[0][j] = j + } + for j := 1; j <= len(t); j++ { + for i := 1; i <= len(s); i++ { + if s[i-1] == t[j-1] { + d[i][j] = d[i-1][j-1] + } else { + min := d[i-1][j] + if d[i][j-1] < min { + min = d[i][j-1] + } + if d[i-1][j-1] < min { + min = d[i-1][j-1] + } + d[i][j] = min + 1 + } + } + + } + return d[len(s)][len(t)] +} + +func stringInSlice(a string, list []string) bool { + for _, b := range list { + if b == a { + return true + } + } + return false +} diff --git a/vendor/github.com/spf13/cobra/cobra/README.md b/vendor/github.com/spf13/cobra/cobra/README.md new file mode 100644 index 00000000..6054f95c --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/README.md @@ -0,0 +1,94 @@ +# Cobra Generator + +Cobra provides its own program that will create your application and add any +commands you want. It's the easiest way to incorporate Cobra into your application. + +In order to use the cobra command, compile it using the following command: + + go get github.com/spf13/cobra/cobra + +This will create the cobra executable under your `$GOPATH/bin` directory. + +### cobra init + +The `cobra init [app]` command will create your initial application code +for you. It is a very powerful application that will populate your program with +the right structure so you can immediately enjoy all the benefits of Cobra. It +will also automatically apply the license you specify to your application. + +Cobra init is pretty smart. You can provide it a full path, or simply a path +similar to what is expected in the import. + +``` +cobra init github.com/spf13/newApp +``` + +### cobra add + +Once an application is initialized, Cobra can create additional commands for you. +Let's say you created an app and you wanted the following commands for it: + +* app serve +* app config +* app config create + +In your project directory (where your main.go file is) you would run the following: + +``` +cobra add serve +cobra add config +cobra add create -p 'configCmd' +``` + +*Note: Use camelCase (not snake_case/snake-case) for command names. +Otherwise, you will encounter 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 similar to +the following: + +``` + ▾ app/ + ▾ cmd/ + serve.go + config.go + create.go + main.go +``` + +At this point you can run `go run main.go` and it would run your app. `go run +main.go serve`, `go run main.go config`, `go run main.go config create` along +with `go run main.go help serve`, etc. would all work. + +Obviously you haven't added your own code to these yet. The commands are ready +for you to give them their tasks. Have fun! + +### Configuring the cobra generator + +The Cobra generator will be easier to use if you provide a simple configuration +file which will help you eliminate providing a bunch of repeated information in +flags over and over. + +An example ~/.cobra.yaml file: + +```yaml +author: Steve Francia +license: MIT +``` + +You can specify no license by setting `license` to `none` or you can specify +a custom license: + +```yaml +license: + header: This file is part of {{ .appName }}. + text: | + {{ .copyright }} + + This is my license. There are many like it, but this one is mine. + My license is my best friend. It is my life. I must master it as I must + master my life. +``` + +You can also use built-in licenses. For example, **GPLv2**, **GPLv3**, **LGPL**, +**AGPL**, **MIT**, **2-Clause BSD** or **3-Clause BSD**. diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/add.go b/vendor/github.com/spf13/cobra/cobra/cmd/add.go new file mode 100644 index 00000000..fb22096a --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/add.go @@ -0,0 +1,179 @@ +// Copyright © 2015 Steve Francia . +// +// 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" + "path/filepath" + "unicode" + + "github.com/spf13/cobra" +) + +func init() { + addCmd.Flags().StringVarP(&packageName, "package", "t", "", "target package name (e.g. github.com/spf13/hugo)") + addCmd.Flags().StringVarP(&parentName, "parent", "p", "rootCmd", "variable name of parent command for this command") +} + +var packageName, parentName string + +var addCmd = &cobra.Command{ + Use: "add [command name]", + Aliases: []string{"command"}, + Short: "Add a command to a Cobra Application", + Long: `Add (cobra add) will create a new command, with a license and +the appropriate structure for a Cobra-based CLI application, +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`, + + Run: func(cmd *cobra.Command, args []string) { + if len(args) < 1 { + er("add needs a name for the command") + } + + var project *Project + if packageName != "" { + project = NewProject(packageName) + } else { + 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) + }, +} + +// 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 + } + + // If the current character isn't dash or underscore, + // just add it. + if output != "" { + output += string(source[i]) + } + i++ + } + + if output == "" { + return source // source is initially valid name. + } + return output +} + +func createCmdFile(license License, path, cmdName string) { + template := `{{comment .copyright}} +{{if .license}}{{comment .license}}{{end}} + +package {{.cmdPackage}} + +import ( + "fmt" + + "github.com/spf13/cobra" +) + +// {{.cmdName}}Cmd represents the {{.cmdName}} command +var {{.cmdName}}Cmd = &cobra.Command{ + Use: "{{.cmdName}}", + Short: "A brief description of your command", + Long: ` + "`" + `A longer description that spans multiple lines and likely contains examples +and usage of using your command. For example: + +Cobra is a CLI library for Go that empowers applications. +This application is a tool to generate the needed files +to quickly create a Cobra application.` + "`" + `, + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("{{.cmdName}} called") + }, +} + +func init() { + {{.parentName}}.AddCommand({{.cmdName}}Cmd) + + // Here you will define your flags and configuration settings. + + // Cobra supports Persistent Flags which will work for this command + // and all subcommands, e.g.: + // {{.cmdName}}Cmd.PersistentFlags().String("foo", "", "A help for foo") + + // Cobra supports local flags which will only run when this command + // is called directly, e.g.: + // {{.cmdName}}Cmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") +} +` + + data := make(map[string]interface{}) + data["copyright"] = copyrightLine() + data["license"] = license.Header + data["cmdPackage"] = filepath.Base(filepath.Dir(path)) // last dir of path + data["parentName"] = parentName + data["cmdName"] = cmdName + + cmdScript, err := executeTemplate(template, data) + if err != nil { + er(err) + } + err = writeStringToFile(path, cmdScript) + if err != nil { + er(err) + } +} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/add_test.go b/vendor/github.com/spf13/cobra/cobra/cmd/add_test.go new file mode 100644 index 00000000..b920e2b9 --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/add_test.go @@ -0,0 +1,109 @@ +package cmd + +import ( + "errors" + "io/ioutil" + "os" + "path/filepath" + "testing" + + "github.com/spf13/viper" +) + +// 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) + defer os.RemoveAll(project.AbsPath()) + + viper.Set("author", "NAME HERE ") + viper.Set("license", "apache") + viper.Set("year", 2017) + defer viper.Set("author", nil) + defer viper.Set("license", nil) + defer viper.Set("year", nil) + + // Initialize the project first. + initializeProject(project) + + // 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 { + // Known 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/vendor/github.com/spf13/cobra/cobra/cmd/golden_test.go b/vendor/github.com/spf13/cobra/cobra/cmd/golden_test.go new file mode 100644 index 00000000..59a5a1c9 --- /dev/null +++ b/vendor/github.com/spf13/cobra/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, "-u", pathA, pathB) + diffCmd.Stdout = output + diffCmd.Stderr = output + + output.WriteString("$ diff -u " + 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/vendor/github.com/spf13/cobra/cobra/cmd/helpers.go b/vendor/github.com/spf13/cobra/cobra/cmd/helpers.go new file mode 100644 index 00000000..cd94b3e3 --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/helpers.go @@ -0,0 +1,168 @@ +// Copyright © 2015 Steve Francia . +// +// 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 ( + "bytes" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "text/template" +) + +var srcPaths []string + +func init() { + // Initialize srcPaths. + envGoPath := os.Getenv("GOPATH") + goPaths := filepath.SplitList(envGoPath) + if len(goPaths) == 0 { + // Adapted from https://github.com/Masterminds/glide/pull/798/files. + // As of Go 1.8 the GOPATH is no longer required to be set. Instead there + // is a default value. If there is no GOPATH check for the default value. + // Note, checking the GOPATH first to avoid invoking the go toolchain if + // possible. + + goExecutable := os.Getenv("COBRA_GO_EXECUTABLE") + if len(goExecutable) <= 0 { + goExecutable = "go" + } + + out, err := exec.Command(goExecutable, "env", "GOPATH").Output() + if err != nil { + er(err) + } + + toolchainGoPath := strings.TrimSpace(string(out)) + goPaths = filepath.SplitList(toolchainGoPath) + if len(goPaths) == 0 { + er("$GOPATH is not set") + } + } + srcPaths = make([]string, 0, len(goPaths)) + for _, goPath := range goPaths { + srcPaths = append(srcPaths, filepath.Join(goPath, "src")) + } +} + +func er(msg interface{}) { + fmt.Println("Error:", msg) + os.Exit(1) +} + +// isEmpty checks if a given path is empty. +// Hidden files in path are ignored. +func isEmpty(path string) bool { + fi, err := os.Stat(path) + if err != nil { + er(err) + } + + if !fi.IsDir() { + return fi.Size() == 0 + } + + f, err := os.Open(path) + if err != nil { + er(err) + } + defer f.Close() + + names, err := f.Readdirnames(-1) + if err != nil && err != io.EOF { + er(err) + } + + for _, name := range names { + if len(name) > 0 && name[0] != '.' { + return false + } + } + return true +} + +// exists checks if a file or directory exists. +func exists(path string) bool { + if path == "" { + return false + } + _, err := os.Stat(path) + if err == nil { + return true + } + if !os.IsNotExist(err) { + er(err) + } + return false +} + +func executeTemplate(tmplStr string, data interface{}) (string, error) { + tmpl, err := template.New("").Funcs(template.FuncMap{"comment": commentifyString}).Parse(tmplStr) + if err != nil { + return "", err + } + + buf := new(bytes.Buffer) + err = tmpl.Execute(buf, data) + return buf.String(), err +} + +func writeStringToFile(path string, s string) error { + return writeToFile(path, strings.NewReader(s)) +} + +// writeToFile writes r to file with path only +// if file/directory on given path doesn't exist. +func writeToFile(path string, r io.Reader) error { + if exists(path) { + return fmt.Errorf("%v already exists", path) + } + + dir := filepath.Dir(path) + if dir != "" { + if err := os.MkdirAll(dir, 0777); err != nil { + return err + } + } + + file, err := os.Create(path) + if err != nil { + return err + } + defer file.Close() + + _, err = io.Copy(file, r) + return err +} + +// commentfyString comments every line of in. +func commentifyString(in string) string { + var newlines []string + lines := strings.Split(in, "\n") + for _, line := range lines { + if strings.HasPrefix(line, "//") { + newlines = append(newlines, line) + } else { + if line == "" { + newlines = append(newlines, "//") + } else { + newlines = append(newlines, "// "+line) + } + } + } + return strings.Join(newlines, "\n") +} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/init.go b/vendor/github.com/spf13/cobra/cobra/cmd/init.go new file mode 100644 index 00000000..24413701 --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/init.go @@ -0,0 +1,234 @@ +// Copyright © 2015 Steve Francia . +// +// 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" + "path" + "path/filepath" + + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +var initCmd = &cobra.Command{ + Use: "init [name]", + Aliases: []string{"initialize", "initialise", "create"}, + Short: "Initialize a Cobra Application", + Long: `Initialize (cobra init) will create a new application, with a license +and the appropriate structure for a Cobra-based CLI application. + + * If a name is provided, it will be created in the current directory; + * If no name is provided, the current directory will be assumed; + * If a relative path is provided, it will be created inside $GOPATH + (e.g. github.com/spf13/hugo); + * If an absolute path is provided, it will be created; + * If the directory already exists but is empty, it will be used. + +Init will not use an existing directory with contents.`, + + Run: func(cmd *cobra.Command, args []string) { + wd, err := os.Getwd() + if err != nil { + er(err) + } + + 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 provide only one argument") + } + + 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 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 !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(project.License(), project.AbsPath()) + createMainFile(project) + createRootCmdFile(project) +} + +func createLicenseFile(license License, path string) { + data := make(map[string]interface{}) + data["copyright"] = copyrightLine() + + // Generate license template from text and data. + text, err := executeTemplate(license.Text, data) + 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(project *Project) { + mainTemplate := `{{ comment .copyright }} +{{if .license}}{{ comment .license }}{{end}} + +package main + +import "{{ .importpath }}" + +func main() { + cmd.Execute() +} +` + data := make(map[string]interface{}) + data["copyright"] = copyrightLine() + data["license"] = project.License().Header + data["importpath"] = path.Join(project.Name(), filepath.Base(project.CmdPath())) + + mainScript, err := executeTemplate(mainTemplate, data) + if err != nil { + er(err) + } + + err = writeStringToFile(filepath.Join(project.AbsPath(), "main.go"), mainScript) + if err != nil { + er(err) + } +} + +func createRootCmdFile(project *Project) { + template := `{{comment .copyright}} +{{if .license}}{{comment .license}}{{end}} + +package cmd + +import ( + "fmt" + "os" +{{if .viper}} + homedir "github.com/mitchellh/go-homedir"{{end}} + "github.com/spf13/cobra"{{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}}", + 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 and 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() { {{- 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 }} + +// 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(err) + os.Exit(1) + } + + // Search config in home directory with name ".{{ .appName }}" (without extension). + viper.AddConfigPath(home) + viper.SetConfigName(".{{ .appName }}") + } + + 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 }} +` + + data := make(map[string]interface{}) + data["copyright"] = copyrightLine() + 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 = writeStringToFile(filepath.Join(project.CmdPath(), "root.go"), rootCmdScript) + if err != nil { + er(err) + } + +} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/init_test.go b/vendor/github.com/spf13/cobra/cobra/cmd/init_test.go new file mode 100644 index 00000000..40eb4038 --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/init_test.go @@ -0,0 +1,83 @@ +package cmd + +import ( + "errors" + "io/ioutil" + "os" + "path/filepath" + "testing" + + "github.com/spf13/viper" +) + +// 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()) + + viper.Set("author", "NAME HERE ") + viper.Set("license", "apache") + viper.Set("year", 2017) + defer viper.Set("author", nil) + defer viper.Set("license", nil) + defer viper.Set("year", nil) + + 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 { + // Known 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 + } + if err := ioutil.WriteFile(goldenPath, got, 0644); err != nil { + t.Fatal("Error while updating file:", err) + } + } + 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/vendor/github.com/spf13/cobra/cobra/cmd/license_agpl.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_agpl.go new file mode 100644 index 00000000..bc22e973 --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/license_agpl.go @@ -0,0 +1,683 @@ +package cmd + +func initAgpl() { + Licenses["agpl"] = License{ + Name: "GNU Affero General Public License", + PossibleMatches: []string{"agpl", "affero gpl", "gnu agpl"}, + Header: ` +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. + +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 this program. If not, see .`, + Text: ` GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +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. + + + Copyright (C) + + 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. + + 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 this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +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 +. +`, + } +} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/license_apache_2.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_apache_2.go new file mode 100644 index 00000000..38393d54 --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/license_apache_2.go @@ -0,0 +1,238 @@ +// Copyright © 2015 Steve Francia . +// +// 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. + +// Parts inspired by https://github.com/ryanuber/go-license + +package cmd + +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.`, + Text: ` + 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/vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_2.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_2.go new file mode 100644 index 00000000..4a847e04 --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_2.go @@ -0,0 +1,71 @@ +// Copyright © 2015 Steve Francia . +// +// 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. + +// Parts inspired by https://github.com/ryanuber/go-license + +package cmd + +func initBsdClause2() { + Licenses["freebsd"] = License{ + Name: "Simplified BSD License", + PossibleMatches: []string{"freebsd", "simpbsd", "simple bsd", "2-clause bsd", + "2 clause bsd", "simplified bsd license"}, + Header: `All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE.`, + Text: `{{ .copyright }} +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +`, + } +} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_3.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_3.go new file mode 100644 index 00000000..c7476b31 --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_3.go @@ -0,0 +1,78 @@ +// Copyright © 2015 Steve Francia . +// +// 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. + +// Parts inspired by https://github.com/ryanuber/go-license + +package cmd + +func initBsdClause3() { + Licenses["bsd"] = License{ + Name: "NewBSD", + PossibleMatches: []string{"bsd", "newbsd", "3 clause bsd", "3-clause bsd"}, + Header: `All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE.`, + Text: `{{ .copyright }} +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +`, + } +} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_2.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_2.go new file mode 100644 index 00000000..03e05b3a --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_2.go @@ -0,0 +1,376 @@ +// Copyright © 2015 Steve Francia . +// +// 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. + +// Parts inspired by https://github.com/ryanuber/go-license + +package cmd + +func initGpl2() { + Licenses["gpl2"] = License{ + Name: "GNU General Public License 2.0", + PossibleMatches: []string{"gpl2", "gnu gpl2", "gplv2"}, + Header: ` +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 Lesser General Public License +along with this program. If not, see .`, + Text: ` GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +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. + + + Copyright (C) + + 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. + + , 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/vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_3.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_3.go new file mode 100644 index 00000000..ce07679c --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_3.go @@ -0,0 +1,711 @@ +// Copyright © 2015 Steve Francia . +// +// 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. + +// Parts inspired by https://github.com/ryanuber/go-license + +package cmd + +func initGpl3() { + Licenses["gpl3"] = License{ + Name: "GNU General Public License 3.0", + PossibleMatches: []string{"gpl3", "gplv3", "gpl", "gnu gpl3", "gnu gpl"}, + Header: ` +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 .`, + Text: ` GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +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. + + + Copyright (C) + + 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 . + +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: + + Copyright (C) + 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 +. + + 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 +. +`, + } +} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/license_lgpl.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_lgpl.go new file mode 100644 index 00000000..0f8b96ca --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/license_lgpl.go @@ -0,0 +1,186 @@ +package cmd + +func initLgpl() { + Licenses["lgpl"] = License{ + Name: "GNU Lesser General Public License", + PossibleMatches: []string{"lgpl", "lesser gpl", "gnu lgpl"}, + Header: ` +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. + +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 this program. If not, see .`, + Text: ` GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library.`, + } +} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/license_mit.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_mit.go new file mode 100644 index 00000000..bd2d0c4f --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/license_mit.go @@ -0,0 +1,63 @@ +// Copyright © 2015 Steve Francia . +// +// 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. + +// Parts inspired by https://github.com/ryanuber/go-license + +package cmd + +func initMit() { + Licenses["mit"] = License{ + Name: "MIT License", + PossibleMatches: []string{"mit"}, + Header: ` +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE.`, + Text: `The MIT License (MIT) + +{{ .copyright }} + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +`, + } +} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/licenses.go b/vendor/github.com/spf13/cobra/cobra/cmd/licenses.go new file mode 100644 index 00000000..a070134d --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/licenses.go @@ -0,0 +1,118 @@ +// Copyright © 2015 Steve Francia . +// +// 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. + +// Parts inspired by https://github.com/ryanuber/go-license + +package cmd + +import ( + "strings" + "time" + + "github.com/spf13/viper" +) + +// 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), +// the header to be used with each file on the file's creating, and the text +// of the license +type License struct { + Name string // The type of license in use + PossibleMatches []string // Similar names to guess + Text string // License text data + Header string // License header for source files +} + +func init() { + // Allows a user to not use a license. + Licenses["none"] = License{"None", []string{"none", "false"}, "", ""} + + initApache2() + initMit() + initBsdClause3() + initBsdClause2() + initGpl2() + initGpl3() + initLgpl() + initAgpl() +} + +// 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 { + // If explicitly flagged, use that. + if userLicense != "" { + return findLicense(userLicense) + } + + // If user wants to have custom license, use that. + if viper.IsSet("license.header") || viper.IsSet("license.text") { + return License{Header: viper.GetString("license.header"), + Text: viper.GetString("license.text")} + } + + // If user wants to have built-in license, use that. + if viper.IsSet("license") { + return findLicense(viper.GetString("license")) + } + + // If user didn't set any license, use Apache 2.0 by default. + return Licenses["apache"] +} + +func copyrightLine() string { + author := viper.GetString("author") + + year := viper.GetString("year") // For tests. + if year == "" { + year = time.Now().Format("2006") + } + + return "Copyright © " + year + " " + author +} + +// 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(name, match) { + return key + } + } + } + + return "" +} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/project.go b/vendor/github.com/spf13/cobra/cobra/cmd/project.go new file mode 100644 index 00000000..7ddb8258 --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/project.go @@ -0,0 +1,200 @@ +package cmd + +import ( + "os" + "path/filepath" + "runtime" + "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. +func NewProject(projectName string) *Project { + if projectName == "" { + er("can't create project with blank name") + } + + 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 filepathHasPrefix(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. +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. +func NewProjectFromPath(absPath string) *Project { + if absPath == "" { + er("can't create project: absPath can't be blank") + } + if !filepath.IsAbs(absPath) { + er("can't create project: absPath is not absolute") + } + + // If absPath is symlink, use its destination. + fi, err := os.Lstat(absPath) + if err != nil { + er("can't read path info: " + err.Error()) + } + if fi.Mode()&os.ModeSymlink != 0 { + path, err := os.Readlink(absPath) + if err != nil { + er("can't read the destination of symlink: " + err.Error()) + } + absPath = path + } + + p := new(Project) + p.absPath = strings.TrimSuffix(absPath, findCmdDir(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(err) + } + 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. +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. +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 []string{"cmd", "cmds", "command", "commands"} { + 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 filepathHasPrefix(p.absPath, srcPath) { + p.srcPath = srcPath + break + } + } + + 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/vendor/github.com/spf13/cobra/cobra/cmd/project_test.go b/vendor/github.com/spf13/cobra/cobra/cmd/project_test.go new file mode 100644 index 00000000..037f7c55 --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/project_test.go @@ -0,0 +1,24 @@ +package cmd + +import ( + "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 filepathHasPrefix(path, srcPath) { + return true + } + } + return false +} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/root.go b/vendor/github.com/spf13/cobra/cobra/cmd/root.go new file mode 100644 index 00000000..19568f98 --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/root.go @@ -0,0 +1,79 @@ +// Copyright © 2015 Steve Francia . +// +// 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" + + homedir "github.com/mitchellh/go-homedir" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +var ( + // Used for flags. + cfgFile, userLicense string + + 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() { + rootCmd.Execute() +} + +func init() { + cobra.OnInitialize(initConfig) + + rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") + rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution") + rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project") + rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration") + viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) + viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) + viper.SetDefault("author", "NAME HERE ") + viper.SetDefault("license", "apache") + + rootCmd.AddCommand(addCmd) + rootCmd.AddCommand(initCmd) +} + +func initConfig() { + if cfgFile != "" { + // Use config file from the flag. + viper.SetConfigFile(cfgFile) + } else { + // Find home directory. + home, err := homedir.Dir() + if err != nil { + er(err) + } + + // Search config in home directory with name ".cobra" (without extension). + viper.AddConfigPath(home) + viper.SetConfigName(".cobra") + } + + viper.AutomaticEnv() + + if err := viper.ReadInConfig(); err == nil { + fmt.Println("Using config file:", viper.ConfigFileUsed()) + } +} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/testdata/LICENSE.golden b/vendor/github.com/spf13/cobra/cobra/cmd/testdata/LICENSE.golden new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/vendor/github.com/spf13/cobra/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/vendor/github.com/spf13/cobra/cobra/cmd/testdata/main.go.golden b/vendor/github.com/spf13/cobra/cobra/cmd/testdata/main.go.golden new file mode 100644 index 00000000..cdbe38d7 --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/testdata/main.go.golden @@ -0,0 +1,21 @@ +// Copyright © 2017 NAME HERE +// +// 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/vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden b/vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden new file mode 100644 index 00000000..d74f4cd4 --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden @@ -0,0 +1,89 @@ +// Copyright © 2017 NAME HERE +// +// 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 and 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(err) + os.Exit(1) + } + + // Search config in home directory with name ".testproject" (without extension). + viper.AddConfigPath(home) + viper.SetConfigName(".testproject") + } + + 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/vendor/github.com/spf13/cobra/cobra/cmd/testdata/test.go.golden b/vendor/github.com/spf13/cobra/cobra/cmd/testdata/test.go.golden new file mode 100644 index 00000000..ed644275 --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/cmd/testdata/test.go.golden @@ -0,0 +1,50 @@ +// Copyright © 2017 NAME HERE +// +// 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/vendor/github.com/spf13/cobra/cobra/main.go b/vendor/github.com/spf13/cobra/cobra/main.go new file mode 100644 index 00000000..c3a9d9cb --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra/main.go @@ -0,0 +1,20 @@ +// Copyright © 2015 Steve Francia . +// +// 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/cobra/cobra/cmd" + +func main() { + cmd.Execute() +} diff --git a/vendor/github.com/spf13/cobra/cobra_test.go b/vendor/github.com/spf13/cobra/cobra_test.go index 7cb4917d..0d1755bd 100644 --- a/vendor/github.com/spf13/cobra/cobra_test.go +++ b/vendor/github.com/spf13/cobra/cobra_test.go @@ -1,965 +1,22 @@ package cobra import ( - "bytes" - "fmt" - "os" - "reflect" - "runtime" - "strings" "testing" - - "github.com/spf13/pflag" + "text/template" ) -var _ = fmt.Println -var _ = os.Stderr +func TestAddTemplateFunctions(t *testing.T) { + AddTemplateFunc("t", func() bool { return true }) + AddTemplateFuncs(template.FuncMap{ + "f": func() bool { return false }, + "h": func() string { return "Hello," }, + "w": func() string { return "world." }}) -var tp, te, tt, t1, tr []string -var rootPersPre, echoPre, echoPersPre, timesPersPre []string -var flagb1, flagb2, flagb3, flagbr, flagbp bool -var flags1, flags2a, flags2b, flags3 string -var flagi1, flagi2, flagi3, flagir int -var globalFlag1 bool -var flagEcho, rootcalled bool -var versionUsed int + c := &Command{} + c.SetUsageTemplate(`{{if t}}{{h}}{{end}}{{if f}}{{h}}{{end}} {{w}}`) -const strtwoParentHelp = "help message for parent flag strtwo" -const strtwoChildHelp = "help message for child flag strtwo" - -var cmdPrint = &Command{ - Use: "print [string to print]", - Short: "Print anything to the screen", - Long: `an absolutely utterly useless command for testing.`, - Run: func(cmd *Command, args []string) { - tp = args - }, -} - -var cmdEcho = &Command{ - Use: "echo [string to echo]", - Aliases: []string{"say"}, - Short: "Echo anything to the screen", - Long: `an utterly useless command for testing.`, - Example: "Just run cobra-test echo", - PersistentPreRun: func(cmd *Command, args []string) { - echoPersPre = args - }, - PreRun: func(cmd *Command, args []string) { - echoPre = args - }, - Run: func(cmd *Command, args []string) { - te = args - }, -} - -var cmdEchoSub = &Command{ - Use: "echosub [string to print]", - Short: "second sub command for echo", - Long: `an absolutely utterly useless command for testing gendocs!.`, - Run: func(cmd *Command, args []string) { - }, -} - -var cmdDeprecated = &Command{ - Use: "deprecated [can't do anything here]", - Short: "A command which is deprecated", - Long: `an absolutely utterly useless command for testing deprecation!.`, - Deprecated: "Please use echo instead", - Run: func(cmd *Command, args []string) { - }, -} - -var cmdTimes = &Command{ - Use: "times [# times] [string to echo]", - Short: "Echo anything to the screen more times", - Long: `a slightly useless command for testing.`, - PersistentPreRun: func(cmd *Command, args []string) { - timesPersPre = args - }, - Run: func(cmd *Command, args []string) { - tt = args - }, -} - -var cmdRootNoRun = &Command{ - Use: "cobra-test", - Short: "The root can run it's own function", - Long: "The root description for help", - PersistentPreRun: func(cmd *Command, args []string) { - rootPersPre = args - }, -} - -var cmdRootSameName = &Command{ - Use: "print", - Short: "Root with the same name as a subcommand", - Long: "The root description for help", -} - -var cmdRootWithRun = &Command{ - Use: "cobra-test", - Short: "The root can run it's own function", - Long: "The root description for help", - Run: func(cmd *Command, args []string) { - tr = args - rootcalled = true - }, -} - -var cmdSubNoRun = &Command{ - Use: "subnorun", - Short: "A subcommand without a Run function", - Long: "A long output about a subcommand without a Run function", -} - -var cmdVersion1 = &Command{ - Use: "version", - Short: "Print the version number", - Long: `First version of the version command`, - Run: func(cmd *Command, args []string) { - versionUsed = 1 - }, -} - -var cmdVersion2 = &Command{ - Use: "version", - Short: "Print the version number", - Long: `Second version of the version command`, - Run: func(cmd *Command, args []string) { - versionUsed = 2 - }, -} - -func flagInit() { - cmdEcho.ResetFlags() - cmdPrint.ResetFlags() - cmdTimes.ResetFlags() - cmdRootNoRun.ResetFlags() - cmdRootSameName.ResetFlags() - cmdRootWithRun.ResetFlags() - cmdSubNoRun.ResetFlags() - cmdRootNoRun.PersistentFlags().StringVarP(&flags2a, "strtwo", "t", "two", strtwoParentHelp) - cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone") - cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo") - cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree") - cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone") - cmdEcho.PersistentFlags().BoolVarP(&flagbp, "persistentbool", "p", false, "help message for flag persistentbool") - cmdTimes.PersistentFlags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp) - cmdPrint.PersistentFlags().StringVarP(&flags3, "strthree", "s", "three", "help message for flag strthree") - cmdEcho.Flags().BoolVarP(&flagb1, "boolone", "b", true, "help message for flag boolone") - cmdTimes.Flags().BoolVarP(&flagb2, "booltwo", "c", false, "help message for flag booltwo") - cmdPrint.Flags().BoolVarP(&flagb3, "boolthree", "b", true, "help message for flag boolthree") - cmdVersion1.ResetFlags() - cmdVersion2.ResetFlags() -} - -func commandInit() { - cmdEcho.ResetCommands() - cmdPrint.ResetCommands() - cmdTimes.ResetCommands() - cmdRootNoRun.ResetCommands() - cmdRootSameName.ResetCommands() - cmdRootWithRun.ResetCommands() - cmdSubNoRun.ResetCommands() -} - -func initialize() *Command { - tt, tp, te = nil, nil, nil - rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil - - var c = cmdRootNoRun - flagInit() - commandInit() - return c -} - -func initializeWithSameName() *Command { - tt, tp, te = nil, nil, nil - rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil - var c = cmdRootSameName - flagInit() - commandInit() - return c -} - -func initializeWithRootCmd() *Command { - cmdRootWithRun.ResetCommands() - tt, tp, te, tr, rootcalled = nil, nil, nil, nil, false - flagInit() - cmdRootWithRun.Flags().BoolVarP(&flagbr, "boolroot", "b", false, "help message for flag boolroot") - cmdRootWithRun.Flags().IntVarP(&flagir, "introot", "i", 321, "help message for flag introot") - commandInit() - return cmdRootWithRun -} - -type resulter struct { - Error error - Output string - Command *Command -} - -func fullSetupTest(input string) resulter { - c := initializeWithRootCmd() - - return fullTester(c, input) -} - -func noRRSetupTest(input string) resulter { - c := initialize() - - return fullTester(c, input) -} - -func rootOnlySetupTest(input string) resulter { - c := initializeWithRootCmd() - - return simpleTester(c, input) -} - -func simpleTester(c *Command, input string) resulter { - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - c.SetArgs(strings.Split(input, " ")) - - err := c.Execute() - output := buf.String() - - return resulter{err, output, c} -} - -func fullTester(c *Command, input string) resulter { - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdPrint, cmdEcho, cmdSubNoRun, cmdDeprecated) - c.SetArgs(strings.Split(input, " ")) - - err := c.Execute() - output := buf.String() - - return resulter{err, output, c} -} - -func logErr(t *testing.T, found, expected string) { - out := new(bytes.Buffer) - - _, _, line, ok := runtime.Caller(2) - if ok { - fmt.Fprintf(out, "Line: %d ", line) - } - fmt.Fprintf(out, "Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - t.Errorf(out.String()) -} - -func checkResultContains(t *testing.T, x resulter, check string) { - if !strings.Contains(x.Output, check) { - logErr(t, x.Output, check) - } -} - -func checkResultOmits(t *testing.T, x resulter, check string) { - if strings.Contains(x.Output, check) { - logErr(t, x.Output, check) - } -} - -func checkOutputContains(t *testing.T, c *Command, check string) { - buf := new(bytes.Buffer) - c.SetOutput(buf) - c.Execute() - - if !strings.Contains(buf.String(), check) { - logErr(t, buf.String(), check) - } -} - -func TestSingleCommand(t *testing.T) { - noRRSetupTest("print one two") - - if te != nil || tt != nil { - t.Error("Wrong command called") - } - if tp == nil { - t.Error("Wrong command called") - } - if strings.Join(tp, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestChildCommand(t *testing.T) { - noRRSetupTest("echo times one two") - - if te != nil || tp != nil { - t.Error("Wrong command called") - } - if tt == nil { - t.Error("Wrong command called") - } - if strings.Join(tt, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestCommandAlias(t *testing.T) { - noRRSetupTest("say times one two") - - if te != nil || tp != nil { - t.Error("Wrong command called") - } - if tt == nil { - t.Error("Wrong command called") - } - if strings.Join(tt, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestPrefixMatching(t *testing.T) { - EnablePrefixMatching = true - noRRSetupTest("ech times one two") - - if te != nil || tp != nil { - t.Error("Wrong command called") - } - if tt == nil { - t.Error("Wrong command called") - } - if strings.Join(tt, " ") != "one two" { - t.Error("Command didn't parse correctly") - } - - EnablePrefixMatching = false -} - -func TestNoPrefixMatching(t *testing.T) { - EnablePrefixMatching = false - - noRRSetupTest("ech times one two") - - if !(tt == nil && te == nil && tp == nil) { - t.Error("Wrong command called") - } -} - -func TestAliasPrefixMatching(t *testing.T) { - EnablePrefixMatching = true - noRRSetupTest("sa times one two") - - if te != nil || tp != nil { - t.Error("Wrong command called") - } - if tt == nil { - t.Error("Wrong command called") - } - if strings.Join(tt, " ") != "one two" { - t.Error("Command didn't parse correctly") - } - EnablePrefixMatching = false -} - -func TestChildSameName(t *testing.T) { - c := initializeWithSameName() - c.AddCommand(cmdPrint, cmdEcho) - c.SetArgs(strings.Split("print one two", " ")) - c.Execute() - - if te != nil || tt != nil { - t.Error("Wrong command called") - } - if tp == nil { - t.Error("Wrong command called") - } - if strings.Join(tp, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestGrandChildSameName(t *testing.T) { - c := initializeWithSameName() - cmdTimes.AddCommand(cmdPrint) - c.AddCommand(cmdTimes) - c.SetArgs(strings.Split("times print one two", " ")) - c.Execute() - - if te != nil || tt != nil { - t.Error("Wrong command called") - } - if tp == nil { - t.Error("Wrong command called") - } - if strings.Join(tp, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestFlagLong(t *testing.T) { - noRRSetupTest("echo --intone=13 something here") - - if strings.Join(te, " ") != "something here" { - t.Errorf("flags didn't leave proper args remaining..%s given", te) - } - if flagi1 != 13 { - t.Errorf("int flag didn't get correct value, had %d", flagi1) - } - if flagi2 != 234 { - t.Errorf("default flag value changed, 234 expected, %d given", flagi2) - } -} - -func TestFlagShort(t *testing.T) { - noRRSetupTest("echo -i13 something here") - - if strings.Join(te, " ") != "something here" { - t.Errorf("flags didn't leave proper args remaining..%s given", te) - } - if flagi1 != 13 { - t.Errorf("int flag didn't get correct value, had %d", flagi1) - } - if flagi2 != 234 { - t.Errorf("default flag value changed, 234 expected, %d given", flagi2) - } - - noRRSetupTest("echo -i 13 something here") - - if strings.Join(te, " ") != "something here" { - t.Errorf("flags didn't leave proper args remaining..%s given", te) - } - if flagi1 != 13 { - t.Errorf("int flag didn't get correct value, had %d", flagi1) - } - if flagi2 != 234 { - t.Errorf("default flag value changed, 234 expected, %d given", flagi2) - } - - noRRSetupTest("print -i99 one two") - - if strings.Join(tp, " ") != "one two" { - t.Errorf("flags didn't leave proper args remaining..%s given", tp) - } - if flagi3 != 99 { - t.Errorf("int flag didn't get correct value, had %d", flagi3) - } - if flagi1 != 123 { - t.Errorf("default flag value changed on different command with same shortname, 234 expected, %d given", flagi2) - } -} - -func TestChildCommandFlags(t *testing.T) { - 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") - - if r.Error == nil { - t.Errorf("invalid flag should generate error") - } - - if !strings.Contains(r.Output, "unknown shorthand") { - t.Errorf("Wrong error message displayed, \n %s", r.Output) - } - - if flagi2 != 99 { - t.Errorf("flag value should be 99, %d given", flagi2) - } - - if flagi1 != 123 { - t.Errorf("unset flag should have default value, expecting 123, given %d", flagi1) - } - - // Testing with flag only existing on child - r = noRRSetupTest("echo -j 99 -i77 one two") - - if r.Error == nil { - t.Errorf("invalid flag should generate error") - } - - if !strings.Contains(r.Output, "unknown shorthand flag") { - t.Errorf("Wrong error message displayed, \n %s", r.Output) - } - - // Testing with persistent flag overwritten by child - noRRSetupTest("echo times --strtwo=child one two") - - if flags2b != "child" { - t.Errorf("flag value should be child, %s given", flags2b) - } - - if flags2a != "two" { - t.Errorf("unset flag should have default value, expecting two, given %s", flags2a) - } - - // Testing flag with invalid input - r = noRRSetupTest("echo -i10E") - - if r.Error == nil { - t.Errorf("invalid input should generate error") - } - - if !strings.Contains(r.Output, "invalid argument \"10E\" for i10E") { - t.Errorf("Wrong error message displayed, \n %s", r.Output) - } -} - -func TestTrailingCommandFlags(t *testing.T) { - x := fullSetupTest("echo two -x") - - if x.Error == nil { - t.Errorf("invalid flag should generate error") - } -} - -func TestInvalidSubcommandFlags(t *testing.T) { - cmd := initializeWithRootCmd() - cmd.AddCommand(cmdTimes) - - result := simpleTester(cmd, "times --inttwo=2 --badflag=bar") - - checkResultContains(t, result, "unknown flag: --badflag") - - if strings.Contains(result.Output, "unknown flag: --inttwo") { - t.Errorf("invalid --badflag flag shouldn't fail on 'unknown' --inttwo flag") - } - -} - -func TestSubcommandArgEvaluation(t *testing.T) { - cmd := initializeWithRootCmd() - - first := &Command{ - Use: "first", - Run: func(cmd *Command, args []string) { - }, - } - cmd.AddCommand(first) - - second := &Command{ - Use: "second", - Run: func(cmd *Command, args []string) { - fmt.Fprintf(cmd.Out(), "%v", args) - }, - } - first.AddCommand(second) - - result := simpleTester(cmd, "first second first third") - - expectedOutput := fmt.Sprintf("%v", []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") - - // persistentFlag should act like normal flag on it's own command - if strings.Join(te, " ") != "more here" { - t.Errorf("flags didn't leave proper args remaining..%s given", te) - } - if flags1 != "something" { - t.Errorf("string flag didn't get correct value, had %v", flags1) - } - if !flagbp { - t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp) - } - - // persistentFlag should act like normal flag on it's own command - 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) - } - - if flags1 != "again" { - t.Errorf("string flag didn't get correct value, had %v", flags1) - } - - if !flagb2 { - t.Errorf("local flag not parsed correctly. Expected true, had %v", flagb2) - } - if !flagbp { - t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp) - } -} - -func TestHelpCommand(t *testing.T) { - x := fullSetupTest("help") - checkResultContains(t, x, cmdRootWithRun.Long) - - x = fullSetupTest("help echo") - checkResultContains(t, x, cmdEcho.Long) - - x = fullSetupTest("help echo times") - checkResultContains(t, x, cmdTimes.Long) -} - -func TestChildCommandHelp(t *testing.T) { - c := noRRSetupTest("print --help") - checkResultContains(t, c, strtwoParentHelp) - r := noRRSetupTest("echo times --help") - checkResultContains(t, r, strtwoChildHelp) -} - -func TestNonRunChildHelp(t *testing.T) { - x := noRRSetupTest("subnorun") - checkResultContains(t, x, cmdSubNoRun.Long) -} - -func TestRunnableRootCommand(t *testing.T) { - fullSetupTest("") - - if rootcalled != true { - t.Errorf("Root Function was not called") - } -} - -func TestRunnableRootCommandNilInput(t *testing.T) { - empty_arg := make([]string, 0) - c := initializeWithRootCmd() - - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdPrint, cmdEcho) - c.SetArgs(empty_arg) - - c.Execute() - - if rootcalled != true { - t.Errorf("Root Function was not called") - } -} - -func TestRunnableRootCommandEmptyInput(t *testing.T) { - args := make([]string, 3) - args[0] = "" - args[1] = "--introot=12" - args[2] = "" - c := initializeWithRootCmd() - - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdPrint, cmdEcho) - c.SetArgs(args) - - c.Execute() - - if rootcalled != true { - t.Errorf("Root Function was not called.\n\nOutput was:\n\n%s\n", buf) - } -} - -func TestInvalidSubcommandWhenArgsAllowed(t *testing.T) { - fullSetupTest("echo invalid-sub") - - if te[0] != "invalid-sub" { - t.Errorf("Subcommand didn't work...") - } -} - -func TestRootFlags(t *testing.T) { - fullSetupTest("-i 17 -b") - - if flagbr != true { - t.Errorf("flag value should be true, %v given", flagbr) - } - - if flagir != 17 { - t.Errorf("flag value should be 17, %d given", flagir) - } -} - -func TestRootHelp(t *testing.T) { - x := fullSetupTest("--help") - - checkResultContains(t, x, "Available Commands:") - checkResultContains(t, x, "for more information about a command") - - if strings.Contains(x.Output, "unknown flag: --help") { - t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) - } - - if strings.Contains(x.Output, cmdEcho.Use) { - t.Errorf("--help shouldn't display subcommand's usage, Got: \n %s", x.Output) - } - - 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) - } - - checkResultContains(t, x, "Available Commands:") - checkResultContains(t, x, "for more information about a command") - - if strings.Contains(x.Output, "unknown flag: --help") { - t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) - } - -} - -func TestFlagAccess(t *testing.T) { - initialize() - - local := cmdTimes.LocalFlags() - inherited := cmdTimes.InheritedFlags() - - for _, f := range []string{"inttwo", "strtwo", "booltwo"} { - if local.Lookup(f) == nil { - t.Errorf("LocalFlags expected to contain %s, Got: nil", f) - } - } - if inherited.Lookup("strone") == nil { - t.Errorf("InheritedFlags expected to contain strone, Got: nil") - } - if inherited.Lookup("strtwo") != nil { - t.Errorf("InheritedFlags shouldn not contain overwritten flag strtwo") - - } -} - -func TestNoNRunnableRootCommandNilInput(t *testing.T) { - args := make([]string, 0) - c := initialize() - - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdPrint, cmdEcho) - c.SetArgs(args) - - c.Execute() - - if !strings.Contains(buf.String(), cmdRootNoRun.Long) { - t.Errorf("Expected to get help output, Got: \n %s", buf) - } -} - -func TestRootNoCommandHelp(t *testing.T) { - x := rootOnlySetupTest("--help") - - checkResultOmits(t, x, "Available Commands:") - checkResultOmits(t, x, "for more information about a command") - - if strings.Contains(x.Output, "unknown flag: --help") { - t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) - } - - x = rootOnlySetupTest("echo --help") - - checkResultOmits(t, x, "Available Commands:") - checkResultOmits(t, x, "for more information about a command") - - if strings.Contains(x.Output, "unknown flag: --help") { - t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) - } -} - -func TestRootUnknownCommand(t *testing.T) { - r := noRRSetupTest("bogus") - s := "Error: unknown command \"bogus\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n" - - if r.Output != s { - t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output) - } - - 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) - } -} - -func TestFlagsBeforeCommand(t *testing.T) { - // short without space - 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) - //} - - // long with equals - 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") - if !strings.Contains(x.Output, "invalid argument \"10E\" for i10E") { - t.Errorf("Wrong error message displayed, \n %s", x.Output) - } - - //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) { - versionUsed = 0 - c := initializeWithRootCmd() - c.AddCommand(cmdVersion1) - c.RemoveCommand(cmdVersion1) - x := fullTester(c, "version") - if x.Error == nil { - t.Errorf("Removed command should not have been called\n") - return - } -} - -func TestCommandWithoutSubcommands(t *testing.T) { - c := initializeWithRootCmd() - - x := simpleTester(c, "") - if x.Error != nil { - t.Errorf("Calling command without subcommands should not have error: %v", x.Error) - return - } -} - -func TestCommandWithoutSubcommandsWithArg(t *testing.T) { - c := initializeWithRootCmd() - expectedArgs := []string{"arg"} - - x := simpleTester(c, "arg") - if x.Error != nil { - t.Errorf("Calling command without subcommands but with arg should not have error: %v", x.Error) - return - } - if !reflect.DeepEqual(expectedArgs, tr) { - t.Errorf("Calling command without subcommands but with arg has wrong args: expected: %v, actual: %v", expectedArgs, tr) - return - } -} - -func TestReplaceCommandWithRemove(t *testing.T) { - versionUsed = 0 - c := initializeWithRootCmd() - c.AddCommand(cmdVersion1) - c.RemoveCommand(cmdVersion1) - c.AddCommand(cmdVersion2) - x := fullTester(c, "version") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - return - } - if versionUsed == 1 { - t.Errorf("Removed command shouldn't be called\n") - } - if versionUsed != 2 { - t.Errorf("Replacing command should have been called but didn't\n") - } -} - -func TestDeprecatedSub(t *testing.T) { - c := fullSetupTest("deprecated") - - checkResultContains(t, c, cmdDeprecated.Deprecated) -} - -func TestPreRun(t *testing.T) { - noRRSetupTest("echo one two") - if echoPre == nil || echoPersPre == nil { - t.Error("PreRun or PersistentPreRun not called") - } - if rootPersPre != nil || timesPersPre != nil { - t.Error("Wrong *Pre functions called!") - } - - noRRSetupTest("echo times one two") - if timesPersPre == nil { - t.Error("PreRun or PersistentPreRun not called") - } - if echoPre != nil || echoPersPre != nil || rootPersPre != nil { - t.Error("Wrong *Pre functions called!") - } - - noRRSetupTest("print one two") - if rootPersPre == nil { - t.Error("Parent PersistentPreRun not called but should not have been") - } - if echoPre != nil || echoPersPre != nil || timesPersPre != nil { - t.Error("Wrong *Pre functions called!") - } -} - -// Check if cmdEchoSub gets PersistentPreRun from rootCmd even if is added last -func TestPeristentPreRunPropagation(t *testing.T) { - rootCmd := initialize() - - // First add the cmdEchoSub to cmdPrint - cmdPrint.AddCommand(cmdEchoSub) - // Now add cmdPrint to rootCmd - rootCmd.AddCommand(cmdPrint) - - rootCmd.SetArgs(strings.Split("print echosub lala", " ")) - rootCmd.Execute() - - if rootPersPre == nil || len(rootPersPre) == 0 || rootPersPre[0] != "lala" { - t.Error("RootCmd PersistentPreRun not called but should have been") - } -} - -func TestGlobalNormFuncPropagation(t *testing.T) { - normFunc := func(f *pflag.FlagSet, name string) pflag.NormalizedName { - return pflag.NormalizedName(name) - } - - rootCmd := initialize() - rootCmd.SetGlobalNormalizationFunc(normFunc) - if reflect.ValueOf(normFunc) != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()) { - t.Error("rootCmd seems to have a wrong normalization function") - } - - // First add the cmdEchoSub to cmdPrint - cmdPrint.AddCommand(cmdEchoSub) - if cmdPrint.GlobalNormalizationFunc() != nil && cmdEchoSub.GlobalNormalizationFunc() != nil { - t.Error("cmdPrint and cmdEchoSub should had no normalization functions") - } - - // Now add cmdPrint to rootCmd - rootCmd.AddCommand(cmdPrint) - if reflect.ValueOf(cmdPrint.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() || - reflect.ValueOf(cmdEchoSub.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() { - t.Error("cmdPrint and cmdEchoSub should had the normalization function of rootCmd") + const expected = "Hello, world." + if got := c.UsageString(); got != expected { + t.Errorf("Expected UsageString: %v\nGot: %v", expected, got) } } diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go index 74565c2b..15b81127 100644 --- a/vendor/github.com/spf13/cobra/command.go +++ b/vendor/github.com/spf13/cobra/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 ( @@ -20,145 +20,230 @@ import ( "fmt" "io" "os" - "runtime" + "path/filepath" + "sort" "strings" - "time" - "github.com/inconshreveable/mousetrap" flag "github.com/spf13/pflag" ) // 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 - // The short description shown in the 'help' output. + + // SuggestFor is an array of command names for which this command will be suggested - + // similar to aliases but only suggests. + SuggestFor []string + + // Short is the short description shown in the 'help' output. Short string - // The long message shown in the 'help ' output. + + // Long is the long message shown in the 'help ' 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, used for bash completions *TODO* actually validate these + + // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions ValidArgs []string - // Custom functions used by the bash autocompletion generator + + // Expected arguments + Args PositionalArgs + + // 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 + + // 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 - // 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 + + // 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. + Annotations map[string]string + + // Version defines the version for this command. If this value is non-empty and the command does not + // define a "version" flag, a "version" boolean flag will be added to the command and, if specified, + // will print content of the "Version" variable. + Version string + // 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 func(cmd *Command, args []string) error // PreRun: children of this command will not inherit. PreRun func(cmd *Command, args []string) - // Run: Typically the actual work function. Most commands will only implement this + // 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 func(cmd *Command, args []string) + // 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) - // PersistentPostRun: children of this command will inherit and execute after PostRun + // 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 func(cmd *Command, args []string) - // Commands is the list of commands supported by this program. + // PersistentPostRunE: PersistentPostRun but returns an error. + PersistentPostRunE func(cmd *Command, args []string) error + + // 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 + + // DisableFlagsInUseLine will disable the addition of [flags] to the usage + // line of a command when printing help or generating docs + DisableFlagsInUseLine bool + + // 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 + + // TraverseChildren parses flags on all parents before executing child command. + TraverseChildren bool + + // 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 + // commandsAreSorted defines, if command slice are sorted or not. + commandsAreSorted bool + // commandCalledAs is the name or alias value used to call this command. + commandCalledAs struct { + name string + called 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 // nil means stderr; use Out() method instead - usageFunc func(*Command) error // Usage can be defined by application - usageTemplate string // Can be defined by Application - helpTemplate string // Can be defined by Application - helpFunc func(*Command, []string) // Help can be defined by application - helpCommand *Command // The help command - helpFlagVal bool - // 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 + + // 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 + // versionTemplate is the version template defined by user. + versionTemplate string } -// os.Args[1:] by default, if desired, can be overridden +// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden // particularly useful when testing. func (c *Command) SetArgs(a []string) { c.args = a } -func (c *Command) getOut(def io.Writer) io.Writer { - if c.output != nil { - return *c.output - } - - if c.HasParent() { - return c.parent.Out() - } else { - return def - } -} - -func (c *Command) Out() io.Writer { - return c.getOut(os.Stderr) -} - -func (c *Command) getOutOrStdout() io.Writer { - return c.getOut(os.Stdout) -} - // SetOutput sets the destination for usage and error messages. // If output is nil, os.Stderr is used. func (c *Command) SetOutput(output io.Writer) { - c.output = &output + c.output = output } -// Usage can be defined by application +// SetUsageFunc sets usage function. Usage can be defined by application. func (c *Command) SetUsageFunc(f func(*Command) error) { c.usageFunc = f } -// Can be defined by Application +// SetUsageTemplate sets usage template. Can be defined by Application. func (c *Command) SetUsageTemplate(s string) { c.usageTemplate = s } -// Can be defined by Application +// SetFlagErrorFunc sets a function to generate an error when flag parsing +// fails. +func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) { + c.flagErrorFunc = f +} + +// SetHelpFunc sets help function. Can be defined by Application. func (c *Command) SetHelpFunc(f func(*Command, []string)) { c.helpFunc = f } +// SetHelpCommand sets help command. func (c *Command) SetHelpCommand(cmd *Command) { c.helpCommand = cmd } -// Can be defined by Application +// SetHelpTemplate sets help template to be used. Application can use it to set custom template. func (c *Command) SetHelpTemplate(s string) { c.helpTemplate = s } +// SetVersionTemplate sets version template to be used. Application can use it to set custom template. +func (c *Command) SetVersionTemplate(s string) { + c.versionTemplate = s +} + // SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. // The user should not have a cyclic dependency on commands. func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) { c.Flags().SetNormalizeFunc(n) c.PersistentFlags().SetNormalizeFunc(n) - c.LocalFlags().SetNormalizeFunc(n) c.globNormFunc = n for _, command := range c.commands { @@ -166,81 +251,135 @@ func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string } } +// OutOrStdout returns output to stdout. +func (c *Command) OutOrStdout() io.Writer { + return c.getOut(os.Stdout) +} + +// OutOrStderr returns output to stderr +func (c *Command) OutOrStderr() io.Writer { + return c.getOut(os.Stderr) +} + +func (c *Command) getOut(def io.Writer) io.Writer { + if c.output != nil { + return c.output + } + if c.HasParent() { + return c.parent.getOut(def) + } + return def +} + +// UsageFunc returns either the function set by SetUsageFunc for this command +// or a parent, or it returns a default usage function. func (c *Command) UsageFunc() (f func(*Command) error) { if c.usageFunc != nil { return c.usageFunc } - if c.HasParent() { - return c.parent.UsageFunc() - } else { - return func(c *Command) error { - err := tmpl(c.Out(), c.UsageTemplate(), c) - return err + return c.Parent().UsageFunc() + } + return func(c *Command) error { + c.mergePersistentFlags() + err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c) + if err != nil { + c.Println(err) } + return err } } + +// Usage puts out the usage for the command. +// Used when a user provides invalid input. +// Can be defined by user by overriding UsageFunc. +func (c *Command) Usage() error { + return c.UsageFunc()(c) +} + +// HelpFunc returns either the function set by SetHelpFunc for this command +// or a parent, or it returns a function with default help behavior. func (c *Command) HelpFunc() func(*Command, []string) { if c.helpFunc != nil { return c.helpFunc } - if c.HasParent() { - return c.parent.HelpFunc() - } else { - return func(c *Command, args []string) { - if len(args) == 0 { - // Help called without any topic, calling on root - c.Root().Help() - return - } - - cmd, _, e := c.Root().Find(args) - if cmd == nil || e != nil { - c.Printf("Unknown help topic %#q.", args) - - c.Root().Usage() - } else { - err := cmd.Help() - if err != nil { - c.Println(err) - } - } + return c.Parent().HelpFunc() + } + return func(c *Command, a []string) { + c.mergePersistentFlags() + err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c) + if err != nil { + c.Println(err) } } } -var minUsagePadding int = 25 +// Help puts out the help for the command. +// Used when a user calls help [command]. +// Can be defined by user by overriding HelpFunc. +func (c *Command) Help() error { + c.HelpFunc()(c, []string{}) + return nil +} +// UsageString return usage string. +func (c *Command) UsageString() string { + tmpOutput := c.output + bb := new(bytes.Buffer) + c.SetOutput(bb) + c.Usage() + c.output = tmpOutput + return bb.String() +} + +// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this +// command or a parent, or it returns a function which returns the original +// error. +func (c *Command) FlagErrorFunc() (f func(*Command, error) error) { + if c.flagErrorFunc != nil { + return c.flagErrorFunc + } + + if c.HasParent() { + return c.parent.FlagErrorFunc() + } + return func(c *Command, err error) error { + return err + } +} + +var minUsagePadding = 25 + +// UsagePadding return padding for the usage. func (c *Command) UsagePadding() int { if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen { return minUsagePadding - } else { - return c.parent.commandsMaxUseLen } + return c.parent.commandsMaxUseLen } -var minCommandPathPadding int = 11 +var minCommandPathPadding = 11 -// +// CommandPathPadding return padding for the command path. func (c *Command) CommandPathPadding() int { if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen { return minCommandPathPadding - } else { - return c.parent.commandsMaxCommandPathLen } + return c.parent.commandsMaxCommandPathLen } -var minNamePadding int = 11 +var minNamePadding = 11 +// NamePadding returns padding for the name. func (c *Command) NamePadding() int { if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen { return minNamePadding - } else { - return c.parent.commandsMaxNameLen } + return c.parent.commandsMaxNameLen } +// UsageTemplate returns usage template for the command. func (c *Command) UsageTemplate() string { if c.usageTemplate != "" { return c.usageTemplate @@ -248,36 +387,34 @@ func (c *Command) UsageTemplate() string { if c.HasParent() { return c.parent.UsageTemplate() - } else { - return `{{ $cmd := . }} -Usage: {{if .Runnable}} - {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}} - {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}} + } + return `Usage:{{if .Runnable}} + {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}} + {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}} Aliases: - {{.NameAndAliases}} -{{end}}{{if .HasExample}} + {{.NameAndAliases}}{{end}}{{if .HasExample}} Examples: -{{ .Example }}{{end}}{{ if .HasNonHelpSubCommands}} +{{.Example}}{{end}}{{if .HasAvailableSubCommands}} -Available Commands: {{range .Commands}}{{if (not .IsHelpCommand)}} - {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasLocalFlags}} +Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}} + {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}} Flags: -{{.LocalFlags.FlagUsages}}{{end}}{{ if .HasInheritedFlags}} +{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}} Global Flags: -{{.InheritedFlags.FlagUsages}}{{end}}{{if .HasHelpSubCommands}} +{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}} -Additional help topics: {{range .Commands}}{{if .IsHelpCommand}} - {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}}{{end}}{{end}}{{ if .HasSubCommands }} +Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}} + {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}} -Use "{{.CommandPath}} [command] --help" for more information about a command. -{{end}}` - } +Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}} +` } +// HelpTemplate return help template for the command. func (c *Command) HelpTemplate() string { if c.helpTemplate != "" { return c.helpTemplate @@ -285,74 +422,77 @@ func (c *Command) HelpTemplate() string { if c.HasParent() { return c.parent.HelpTemplate() - } else { - return `{{with or .Long .Short }}{{. | trim}}{{end}} -{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}} + } + return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}} + +{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` +} + +// VersionTemplate return version template for the command. +func (c *Command) VersionTemplate() string { + if c.versionTemplate != "" { + return c.versionTemplate + } + + if c.HasParent() { + return c.parent.VersionTemplate() + } + return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}} ` - } } -// Really only used when casting a command to a commander -func (c *Command) resetChildrensParents() { - for _, x := range c.commands { - x.parent = c - } -} - -// Test if the named flag is a boolean flag. -func isBooleanFlag(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 } - return flag.Value.Type() == "bool" + return flag.NoOptDefVal != "" } -// Test if the named flag is a boolean flag. -func isBooleanShortFlag(name string, f *flag.FlagSet) bool { - result := false - f.VisitAll(func(f *flag.Flag) { - if f.Shorthand == name && f.Value.Type() == "bool" { - result = true - } - }) - return result +func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool { + 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 { - if len(args) < 1 { + if len(args) == 0 { return args } c.mergePersistentFlags() commands := []string{} + flags := c.Flags() - inQuote := false - inFlag := false - for _, y := range args { - if !inQuote { - switch { - case strings.HasPrefix(y, "\""): - inQuote = true - case strings.Contains(y, "=\""): - inQuote = true - case strings.HasPrefix(y, "--") && !strings.Contains(y, "="): - // TODO: this isn't quite right, we should really check ahead for 'true' or 'false' - inFlag = !isBooleanFlag(y[2:], c.Flags()) - case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()): - inFlag = true - case inFlag: - inFlag = false - case y == "": - // strip empty commands, as the go tests expect this to be ok.... - case !strings.HasPrefix(y, "-"): - commands = append(commands, y) - inFlag = false +Loop: + for len(args) > 0 { + s := args[0] + args = args[1:] + switch { + case s == "--": + // "--" terminates the flags + break Loop + 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(y, "\"") && !strings.HasSuffix(y, "\\\"") { - inQuote = false + case s != "" && !strings.HasPrefix(s, "-"): + commands = append(commands, s) } } @@ -373,13 +513,14 @@ func argsMinusFirstX(args []string, x string) []string { return args } -// find the target command given the args and command tree +func isFlagArg(arg string) bool { + return ((len(arg) >= 3 && arg[1] == '-') || + (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-')) +} + +// Find the target command given the args and command tree // Meant to be run on the highest node. Only searches down. func (c *Command) Find(args []string) (*Command, []string, error) { - if c == nil { - return nil, nil, fmt.Errorf("Called find() on a nil Command") - } - var innerfind func(*Command, []string) (*Command, []string) innerfind = func(c *Command, innerArgs []string) (*Command, []string) { @@ -388,58 +529,141 @@ func (c *Command) Find(args []string) (*Command, []string, error) { return c, innerArgs } nextSubCmd := argsWOflags[0] - matches := make([]*Command, 0) - for _, cmd := range c.commands { - if cmd.Name() == nextSubCmd || cmd.HasAlias(nextSubCmd) { // exact name or alias match - return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd)) - } - if EnablePrefixMatching { - if strings.HasPrefix(cmd.Name(), nextSubCmd) { // prefix match - matches = append(matches, cmd) - } - for _, x := range cmd.Aliases { - if strings.HasPrefix(x, nextSubCmd) { - matches = append(matches, cmd) - } - } - } - } - // only accept a single prefix match - multiple matches would be ambiguous - if len(matches) == 1 { - return innerfind(matches[0], argsMinusFirstX(innerArgs, argsWOflags[0])) + cmd := c.findNext(nextSubCmd) + if cmd != nil { + return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd)) } - return c, innerArgs } commandFound, a := innerfind(c, args) - argsWOflags := stripFlags(a, commandFound) - - // no subcommand, always take args - if !commandFound.HasSubCommands() { - return commandFound, a, nil + if commandFound.Args == nil { + return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound)) } - // root command with subcommands, do subcommand checking - if commandFound == c && len(argsWOflags) > 0 { - return commandFound, a, fmt.Errorf("unknown command %q for %q", argsWOflags[0], commandFound.CommandPath()) - } - return commandFound, a, nil } -func (c *Command) Root() *Command { - var findRoot func(*Command) *Command +func (c *Command) findSuggestions(arg string) string { + if c.DisableSuggestions { + return "" + } + if c.SuggestionsMinimumDistance <= 0 { + c.SuggestionsMinimumDistance = 2 + } + suggestionsString := "" + if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 { + suggestionsString += "\n\nDid you mean this?\n" + for _, s := range suggestions { + suggestionsString += fmt.Sprintf("\t%v\n", s) + } + } + return suggestionsString +} - findRoot = func(x *Command) *Command { - if x.HasParent() { - return findRoot(x.parent) - } else { - return x +func (c *Command) findNext(next string) *Command { + matches := make([]*Command, 0) + for _, cmd := range c.commands { + if cmd.Name() == next || cmd.HasAlias(next) { + cmd.commandCalledAs.name = next + return cmd + } + if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) { + matches = append(matches, cmd) } } - return findRoot(c) + if len(matches) == 1 { + return matches[0] + } + + return nil +} + +// Traverse the command tree to find the command, and parse args for +// each parent. +func (c *Command) Traverse(args []string) (*Command, []string, error) { + flags := []string{} + inFlag := false + + for i, arg := range args { + switch { + // A long flag with a space separated value + case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="): + // TODO: this isn't quite right, we should really check ahead for 'true' or 'false' + inFlag = !hasNoOptDefVal(arg[2:], c.Flags()) + flags = append(flags, arg) + continue + // A short flag with a space separated value + case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()): + inFlag = true + flags = append(flags, arg) + continue + // The value for a flag + case inFlag: + inFlag = false + flags = append(flags, arg) + continue + // A flag without a value, or with an `=` separated value + case isFlagArg(arg): + flags = append(flags, arg) + continue + } + + cmd := c.findNext(arg) + if cmd == nil { + return c, args, nil + } + + if err := c.ParseFlags(flags); err != nil { + return nil, args, err + } + return cmd.Traverse(args[i+1:]) + } + return c, args, nil +} + +// SuggestionsFor provides suggestions for the typedName. +func (c *Command) SuggestionsFor(typedName string) []string { + suggestions := []string{} + for _, cmd := range c.commands { + if cmd.IsAvailableCommand() { + levenshteinDistance := ld(typedName, cmd.Name(), true) + suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance + suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName)) + if suggestByLevenshtein || suggestByPrefix { + suggestions = append(suggestions, cmd.Name()) + } + for _, explicitSuggestion := range cmd.SuggestFor { + if strings.EqualFold(typedName, explicitSuggestion) { + suggestions = append(suggestions, cmd.Name()) + } + } + } + } + return suggestions +} + +// VisitParents visits all parents of the command and invokes fn on each parent. +func (c *Command) VisitParents(fn func(*Command)) { + if c.HasParent() { + fn(c.Parent()) + c.Parent().VisitParents(fn) + } +} + +// Root finds root command. +func (c *Command) Root() *Command { + if c.HasParent() { + return c.Parent().Root() + } + return c +} + +// ArgsLenAtDash will return the length of c.Flags().Args at the moment +// when a -- was found during args parsing. +func (c *Command) ArgsLenAtDash() int { + return c.Flags().ArgsLenAtDash() } func (c *Command) execute(a []string) (err error) { @@ -451,36 +675,104 @@ func (c *Command) execute(a []string) (err error) { c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated) } + // initialize help and version flag at the last point possible to allow for user + // overriding + c.InitDefaultHelpFlag() + c.InitDefaultVersionFlag() + err = c.ParseFlags(a) if err != nil { + return c.FlagErrorFunc()(c, err) + } + + // 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 InitDefaultHelpFlag() + c.Println("\"help\" flag declared as non-bool. Please correct your code") return err } - // If help is called, regardless of other flags, return we want help - // Also say we need help if c.Run is nil. - if c.helpFlagVal || !c.Runnable() { + + if helpVal { + return flag.ErrHelp + } + + // for back-compat, only add version flag behavior if version is defined + if c.Version != "" { + versionVal, err := c.Flags().GetBool("version") + if err != nil { + c.Println("\"version\" flag declared as non-bool. Please correct your code") + return err + } + if versionVal { + err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c) + if err != nil { + c.Println(err) + } + return err + } + } + + if !c.Runnable() { return flag.ErrHelp } c.preRun() + argWoFlags := c.Flags().Args() + if c.DisableFlagParsing { + argWoFlags = a + } + + if err := c.ValidateArgs(argWoFlags); err != nil { + return err + } for p := c; p != nil; p = p.Parent() { - if p.PersistentPreRun != nil { + if p.PersistentPreRunE != nil { + if err := p.PersistentPreRunE(c, argWoFlags); err != nil { + return err + } + break + } else if p.PersistentPreRun != nil { p.PersistentPreRun(c, argWoFlags) break } } - if c.PreRun != nil { + if c.PreRunE != nil { + if err := c.PreRunE(c, argWoFlags); err != nil { + return err + } + } else if c.PreRun != nil { c.PreRun(c, argWoFlags) } - c.Run(c, argWoFlags) - - if c.PostRun != nil { + if err := c.validateRequiredFlags(); err != nil { + return err + } + if c.RunE != nil { + if err := c.RunE(c, argWoFlags); err != nil { + return err + } + } else { + c.Run(c, argWoFlags) + } + if c.PostRunE != nil { + if err := c.PostRunE(c, argWoFlags); err != nil { + return err + } + } else if c.PostRun != nil { c.PostRun(c, argWoFlags) } for p := c; p != nil; p = p.Parent() { - if p.PersistentPostRun != nil { + if p.PersistentPostRunE != nil { + if err := p.PersistentPostRunE(c, argWoFlags); err != nil { + return err + } + break + } else if p.PersistentPostRun != nil { p.PersistentPostRun(c, argWoFlags) break } @@ -495,99 +787,202 @@ func (c *Command) preRun() { } } -func (c *Command) errorMsgFromParse() string { - s := c.flagErrorBuf.String() - - x := strings.Split(s, "\n") - - if len(x) > 0 { - return x[0] - } else { - return "" - } -} - -// Call execute to use the args (os.Args[1:] by default) +// Execute uses the args (os.Args[1:] by default) // and run through the command tree finding appropriate matches // for commands and then corresponding flags. -func (c *Command) Execute() (err error) { +func (c *Command) Execute() error { + _, err := c.ExecuteC() + return err +} +// ExecuteC executes the command. +func (c *Command) ExecuteC() (cmd *Command, err error) { // Regardless of what command execute is called on, run on Root only if c.HasParent() { - return c.Root().Execute() + return c.Root().ExecuteC() } - if EnableWindowsMouseTrap && runtime.GOOS == "windows" { - if mousetrap.StartedByExplorer() { - c.Print(MousetrapHelpText) - time.Sleep(5 * time.Second) - os.Exit(1) - } + // windows hook + if preExecHookFn != nil { + preExecHookFn(c) } // initialize help as the last point possible to allow for user // overriding - c.initHelp() + c.InitDefaultHelpCmd() var args []string - if len(c.args) == 0 { + // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155 + if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" { args = os.Args[1:] } else { args = c.args } - cmd, flags, err := c.Find(args) + var flags []string + if c.TraverseChildren { + cmd, flags, err = c.Traverse(args) + } else { + cmd, flags, err = c.Find(args) + } if err != nil { // If found parse to a subcommand and then failed, talk about the subcommand if cmd != nil { c = cmd } - c.Println("Error:", err.Error()) - c.Printf("Run '%v --help' for usage.\n", c.CommandPath()) - return err + if !c.SilenceErrors { + c.Println("Error:", err.Error()) + c.Printf("Run '%v --help' for usage.\n", c.CommandPath()) + } + return c, err + } + + cmd.commandCalledAs.called = true + if cmd.commandCalledAs.name == "" { + cmd.commandCalledAs.name = cmd.Name() } err = cmd.execute(flags) if err != nil { + // Always show help if requested, even if SilenceErrors is in + // effect if err == flag.ErrHelp { - cmd.Help() - return nil + cmd.HelpFunc()(cmd, args) + return cmd, nil } - c.Println(cmd.UsageString()) - c.Println("Error:", err.Error()) - } - return + // If root command has SilentErrors flagged, + // all subcommands should respect it + if !cmd.SilenceErrors && !c.SilenceErrors { + c.Println("Error:", err.Error()) + } + + // If root command has SilentUsage flagged, + // all subcommands should respect it + if !cmd.SilenceUsage && !c.SilenceUsage { + c.Println(cmd.UsageString()) + } + } + return cmd, err } -func (c *Command) initHelp() { - if c.helpCommand == nil { - if !c.HasSubCommands() { +func (c *Command) ValidateArgs(args []string) error { + if c.Args == nil { + return nil + } + return c.Args(c, args) +} + +func (c *Command) validateRequiredFlags() error { + flags := c.Flags() + missingFlagNames := []string{} + flags.VisitAll(func(pflag *flag.Flag) { + requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag] + if !found { return } + if (requiredAnnotation[0] == "true") && !pflag.Changed { + missingFlagNames = append(missingFlagNames, pflag.Name) + } + }) + if len(missingFlagNames) > 0 { + return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`)) + } + return nil +} + +// InitDefaultHelpFlag adds default help flag to c. +// It is called automatically by executing the c or by calling help and usage. +// If c already has help flag, it will do nothing. +func (c *Command) InitDefaultHelpFlag() { + c.mergePersistentFlags() + if c.Flags().Lookup("help") == nil { + usage := "help for " + if c.Name() == "" { + usage += "this command" + } else { + usage += c.Name() + } + c.Flags().BoolP("help", "h", false, usage) + } +} + +// InitDefaultVersionFlag adds default version flag to c. +// It is called automatically by executing the c. +// If c already has a version flag, it will do nothing. +// If c.Version is empty, it will do nothing. +func (c *Command) InitDefaultVersionFlag() { + if c.Version == "" { + return + } + + c.mergePersistentFlags() + if c.Flags().Lookup("version") == nil { + usage := "version for " + if c.Name() == "" { + usage += "this command" + } else { + usage += c.Name() + } + c.Flags().Bool("version", false, usage) + } +} + +// 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.HasSubCommands() { + return + } + + if c.helpCommand == nil { 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.`, - Run: c.HelpFunc(), - PersistentPreRun: func(cmd *Command, args []string) {}, - PersistentPostRun: func(cmd *Command, args []string) {}, +Simply type ` + c.Name() + ` help [path to command] for full details.`, + + 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) } -// Used for testing +// ResetCommands delete parent, subcommand and help command from c. func (c *Command) ResetCommands() { + c.parent = nil c.commands = nil c.helpCommand = nil + c.parentsPflags = nil } -//Commands returns a slice of child commands. +// Sorts commands by their names. +type commandSorterByName []*Command + +func (c commandSorterByName) Len() int { return len(c) } +func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] } +func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() } + +// Commands returns a sorted slice of child commands. func (c *Command) Commands() []*Command { + // do not sort commands if it already sorted or sorting was disabled + if EnableCommandSorting && !c.commandsAreSorted { + sort.Sort(commandSorterByName(c.commands)) + c.commandsAreSorted = true + } return c.commands } @@ -611,15 +1006,16 @@ func (c *Command) AddCommand(cmds ...*Command) { if nameLen > c.commandsMaxNameLen { c.commandsMaxNameLen = nameLen } - // If glabal normalization function exists, update all children + // If global normalization function exists, update all children if c.globNormFunc != nil { x.SetGlobalNormalizationFunc(c.globNormFunc) } c.commands = append(c.commands, x) + c.commandsAreSorted = false } } -// AddCommand removes one or more commands from a parent command. +// RemoveCommand removes one or more commands from a parent command. func (c *Command) RemoveCommand(cmds ...*Command) { commands := []*Command{} main: @@ -653,72 +1049,48 @@ main: } } -// Convenience method to Print to the defined output +// Print is a convenience method to Print to the defined output, fallback to Stderr if not set. func (c *Command) Print(i ...interface{}) { - fmt.Fprint(c.Out(), i...) + fmt.Fprint(c.OutOrStderr(), i...) } -// Convenience method to Println to the defined output +// Println is a convenience method to Println to the defined output, fallback to Stderr if not set. func (c *Command) Println(i ...interface{}) { - str := fmt.Sprintln(i...) - c.Print(str) + c.Print(fmt.Sprintln(i...)) } -// Convenience method to Printf to the defined output +// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set. func (c *Command) Printf(format string, i ...interface{}) { - str := fmt.Sprintf(format, i...) - c.Print(str) -} - -// Output the usage for the command -// Used when a user provides invalid input -// Can be defined by user by overriding UsageFunc -func (c *Command) Usage() error { - c.mergePersistentFlags() - err := c.UsageFunc()(c) - return err -} - -// Output the help for the command -// Used when a user calls help [command] -// by the default HelpFunc in the commander -func (c *Command) Help() error { - c.mergePersistentFlags() - err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c) - return err -} - -func (c *Command) UsageString() string { - tmpOutput := c.output - bb := new(bytes.Buffer) - c.SetOutput(bb) - c.Usage() - c.output = tmpOutput - return bb.String() + c.Print(fmt.Sprintf(format, i...)) } // CommandPath returns the full path to this command. func (c *Command) CommandPath() string { - str := c.Name() - x := c - for x.HasParent() { - str = x.parent.Name() + " " + str - x = x.parent - } - return str -} - -//The full usage for a given command (including parents) -func (c *Command) UseLine() string { - str := "" if c.HasParent() { - str = c.parent.CommandPath() + " " + return c.Parent().CommandPath() + " " + c.Name() } - return str + c.Use + return c.Name() } -// For use in determining which flags have been assigned to which commands -// and which persist +// UseLine puts out the full usage for a given command (including parents). +func (c *Command) UseLine() string { + var useline string + if c.HasParent() { + useline = c.parent.CommandPath() + " " + c.Use + } else { + useline = c.Use + } + if c.DisableFlagsInUseLine { + return useline + } + if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") { + useline += " [flags]" + } + return useline +} + +// DebugFlags used to determine which flags have been assigned to which commands +// and which persist. func (c *Command) DebugFlags() { c.Println("DebugFlags called on", c.Name()) var debugflags func(*Command) @@ -729,12 +1101,8 @@ func (c *Command) DebugFlags() { } if x.HasFlags() { x.flags.VisitAll(func(f *flag.Flag) { - if x.HasPersistentFlags() { - if x.persistentFlag(f.Name) == nil { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]") - } else { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]") - } + if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil { + c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]") } else { c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]") } @@ -764,9 +1132,6 @@ func (c *Command) DebugFlags() { // Name returns the command's name: the first word in the use line. func (c *Command) Name() string { - if c.name != "" { - return c.name - } name := c.Use i := strings.Index(name, " ") if i >= 0 { @@ -775,7 +1140,7 @@ func (c *Command) Name() string { return name } -// Determine if a given string is an alias of the command. +// HasAlias determines if a given string is an alias of the command. func (c *Command) HasAlias(s string) bool { for _, a := range c.Aliases { if a == s { @@ -785,74 +1150,134 @@ func (c *Command) HasAlias(s string) bool { return false } +// CalledAs returns the command name or alias that was used to invoke +// this command or an empty string if the command has not been called. +func (c *Command) CalledAs() string { + if c.commandCalledAs.called { + return c.commandCalledAs.name + } + return "" +} + +// hasNameOrAliasPrefix returns true if the Name or any of aliases start +// with prefix +func (c *Command) hasNameOrAliasPrefix(prefix string) bool { + if strings.HasPrefix(c.Name(), prefix) { + c.commandCalledAs.name = c.Name() + return true + } + for _, alias := range c.Aliases { + if strings.HasPrefix(alias, prefix) { + c.commandCalledAs.name = alias + return true + } + } + return false +} + +// NameAndAliases returns a list of the command name and all aliases func (c *Command) NameAndAliases() string { return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ") } +// HasExample determines if the command has example. func (c *Command) HasExample() bool { return len(c.Example) > 0 } -// Determine if the command is itself runnable +// Runnable determines if the command is itself runnable. func (c *Command) Runnable() bool { - return c.Run != nil + return c.Run != nil || c.RunE != nil } -// Determine if the command has children commands +// HasSubCommands determines if the command has children commands. func (c *Command) HasSubCommands() bool { return len(c.commands) > 0 } -func (c *Command) IsHelpCommand() bool { - if c.Runnable() { +// IsAvailableCommand determines if a command is available as a non-help command +// (this includes all non deprecated/hidden commands). +func (c *Command) IsAvailableCommand() bool { + if len(c.Deprecated) != 0 || c.Hidden { return false } + + if c.HasParent() && c.Parent().helpCommand == c { + return false + } + + if c.Runnable() || c.HasAvailableSubCommands() { + return true + } + + return false +} + +// IsAdditionalHelpTopicCommand determines if a command is an additional +// help topic command; additional help topic command is determined by the +// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that +// are runnable/hidden/deprecated. +// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924. +func (c *Command) IsAdditionalHelpTopicCommand() bool { + // if a command is runnable, deprecated, or hidden it is not a 'help' command + if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden { + return false + } + + // if any non-help sub commands are found, the command is not a 'help' command for _, sub := range c.commands { - if len(sub.Deprecated) != 0 { - continue - } - if !sub.IsHelpCommand() { + if !sub.IsAdditionalHelpTopicCommand() { return false } } + + // the command either has no sub commands, or no non-help sub commands return true } +// HasHelpSubCommands determines if a command has any available 'help' sub commands +// that need to be shown in the usage/help default template under 'additional help +// topics'. func (c *Command) HasHelpSubCommands() bool { + // return true on the first found available 'help' sub command for _, sub := range c.commands { - if len(sub.Deprecated) != 0 { - continue - } - if sub.IsHelpCommand() { + if sub.IsAdditionalHelpTopicCommand() { return true } } + + // the command either has no sub commands, or no available 'help' sub commands return false } -func (c *Command) HasNonHelpSubCommands() bool { +// HasAvailableSubCommands determines if a command has available sub commands that +// need to be shown in the usage/help default template under 'available commands'. +func (c *Command) HasAvailableSubCommands() bool { + // return true on the first found available (non deprecated/help/hidden) + // sub command for _, sub := range c.commands { - if len(sub.Deprecated) != 0 { - continue - } - if !sub.IsHelpCommand() { + if sub.IsAvailableCommand() { return true } } + + // the command either has no sub commands, or no available (non deprecated/help/hidden) + // sub commands return false } -// Determine if the command is a child command +// HasParent determines if the command is a child command. func (c *Command) HasParent() bool { return c.parent != nil } -// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists +// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist. func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName { return c.globNormFunc } -// Get the complete FlagSet that applies to this command (local and persistent declared here and by all parents) +// Flags returns the complete FlagSet that applies +// to this command (local and persistent declared here and by all parents). func (c *Command) Flags() *flag.FlagSet { if c.flags == nil { c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) @@ -860,57 +1285,81 @@ func (c *Command) Flags() *flag.FlagSet { c.flagErrorBuf = new(bytes.Buffer) } c.flags.SetOutput(c.flagErrorBuf) - c.PersistentFlags().BoolVarP(&c.helpFlagVal, "help", "h", false, "help for "+c.Name()) } + return c.flags } -// Get the local FlagSet specifically set in the current command +// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands. +func (c *Command) LocalNonPersistentFlags() *flag.FlagSet { + persistentFlags := c.PersistentFlags() + + out := flag.NewFlagSet(c.Name(), flag.ContinueOnError) + c.LocalFlags().VisitAll(func(f *flag.Flag) { + if persistentFlags.Lookup(f.Name) == nil { + out.AddFlag(f) + } + }) + return out +} + +// LocalFlags returns the local FlagSet specifically set in the current command. func (c *Command) LocalFlags() *flag.FlagSet { c.mergePersistentFlags() - local := flag.NewFlagSet(c.Name(), flag.ContinueOnError) - c.lflags.VisitAll(func(f *flag.Flag) { - local.AddFlag(f) - }) - return local + if c.lflags == nil { + c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) + if c.flagErrorBuf == nil { + c.flagErrorBuf = new(bytes.Buffer) + } + c.lflags.SetOutput(c.flagErrorBuf) + } + c.lflags.SortFlags = c.Flags().SortFlags + if c.globNormFunc != nil { + c.lflags.SetNormalizeFunc(c.globNormFunc) + } + + addToLocal := func(f *flag.Flag) { + if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil { + c.lflags.AddFlag(f) + } + } + c.Flags().VisitAll(addToLocal) + c.PersistentFlags().VisitAll(addToLocal) + return c.lflags } -// All Flags which were inherited from parents commands +// InheritedFlags returns all flags which were inherited from parents commands. func (c *Command) InheritedFlags() *flag.FlagSet { c.mergePersistentFlags() - inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError) + 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() - - var rmerge func(x *Command) - - rmerge = func(x *Command) { - if x.HasPersistentFlags() { - x.PersistentFlags().VisitAll(func(f *flag.Flag) { - if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil { - inherited.AddFlag(f) - } - }) - } - if x.HasParent() { - rmerge(x.parent) - } + if c.globNormFunc != nil { + c.iflags.SetNormalizeFunc(c.globNormFunc) } - if c.HasParent() { - rmerge(c.parent) - } - - return inherited + c.parentsPflags.VisitAll(func(f *flag.Flag) { + if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil { + c.iflags.AddFlag(f) + } + }) + return c.iflags } -// All Flags which were not inherited from parent commands +// NonInheritedFlags returns all flags which were not inherited from parent commands. func (c *Command) NonInheritedFlags() *flag.FlagSet { return c.LocalFlags() } -// Get the Persistent FlagSet specifically set in the current command +// PersistentFlags returns the persistent FlagSet specifically set in the current command. func (c *Command) PersistentFlags() *flag.FlagSet { if c.pflags == nil { c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) @@ -922,7 +1371,7 @@ func (c *Command) PersistentFlags() *flag.FlagSet { return c.pflags } -// For use in testing +// ResetFlags deletes all flags from command. func (c *Command) ResetFlags() { c.flagErrorBuf = new(bytes.Buffer) c.flagErrorBuf.Reset() @@ -930,28 +1379,56 @@ func (c *Command) ResetFlags() { c.flags.SetOutput(c.flagErrorBuf) c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) c.pflags.SetOutput(c.flagErrorBuf) + + c.lflags = nil + c.iflags = nil + c.parentsPflags = nil } -// Does the command contain any flags (local plus persistent from the entire structure) +// HasFlags checks if the command contains any flags (local plus persistent from the entire structure). func (c *Command) HasFlags() bool { return c.Flags().HasFlags() } -// Does the command contain persistent flags +// HasPersistentFlags checks if the command contains persistent flags. func (c *Command) HasPersistentFlags() bool { return c.PersistentFlags().HasFlags() } -// Does the command has flags specifically declared locally +// HasLocalFlags checks if the command has flags specifically declared locally. func (c *Command) HasLocalFlags() bool { return c.LocalFlags().HasFlags() } +// HasInheritedFlags checks if the command has flags inherited from its parent command. func (c *Command) HasInheritedFlags() bool { return c.InheritedFlags().HasFlags() } -// Climbs up the command tree looking for matching flag +// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire +// structure) which are not hidden or deprecated. +func (c *Command) HasAvailableFlags() bool { + return c.Flags().HasAvailableFlags() +} + +// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated. +func (c *Command) HasAvailablePersistentFlags() bool { + return c.PersistentFlags().HasAvailableFlags() +} + +// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden +// or deprecated. +func (c *Command) HasAvailableLocalFlags() bool { + return c.LocalFlags().HasAvailableFlags() +} + +// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are +// not hidden or deprecated. +func (c *Command) HasAvailableInheritedFlags() bool { + return c.InheritedFlags().HasAvailableFlags() +} + +// Flag climbs up the command tree looking for matching flag. func (c *Command) Flag(name string) (flag *flag.Flag) { flag = c.Flags().Lookup(name) @@ -962,64 +1439,69 @@ func (c *Command) Flag(name string) (flag *flag.Flag) { return } -// recursively find matching persistent flag +// Recursively find matching persistent flag. func (c *Command) persistentFlag(name string) (flag *flag.Flag) { if c.HasPersistentFlags() { flag = c.PersistentFlags().Lookup(name) } - if flag == nil && c.HasParent() { - flag = c.parent.persistentFlag(name) + if flag == nil { + c.updateParentsPflags() + flag = c.parentsPflags.Lookup(name) } return } -// Parses persistent flag tree & local flags -func (c *Command) ParseFlags(args []string) (err error) { +// ParseFlags parses persistent flag tree and local flags. +func (c *Command) ParseFlags(args []string) error { + if c.DisableFlagParsing { + return nil + } + + if c.flagErrorBuf == nil { + c.flagErrorBuf = new(bytes.Buffer) + } + beforeErrorBufLen := c.flagErrorBuf.Len() c.mergePersistentFlags() - err = c.Flags().Parse(args) - return + err := c.Flags().Parse(args) + // Print warnings if they occurred (e.g. deprecated flag messages). + if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil { + c.Print(c.flagErrorBuf.String()) + } + + return err } +// Parent returns a commands parent command. func (c *Command) Parent() *Command { return c.parent } +// mergePersistentFlags merges c.PersistentFlags() to c.Flags() +// and adds missing persistent flags of all parents. func (c *Command) mergePersistentFlags() { - var rmerge func(x *Command) - - // Save the set of local flags - if c.lflags == nil { - c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - c.lflags.SetOutput(c.flagErrorBuf) - addtolocal := func(f *flag.Flag) { - c.lflags.AddFlag(f) - } - c.Flags().VisitAll(addtolocal) - c.PersistentFlags().VisitAll(addtolocal) - } - rmerge = func(x *Command) { - if !x.HasParent() { - flag.CommandLine.VisitAll(func(f *flag.Flag) { - if x.PersistentFlags().Lookup(f.Name) == nil { - x.PersistentFlags().AddFlag(f) - } - }) - } - if x.HasPersistentFlags() { - x.PersistentFlags().VisitAll(func(f *flag.Flag) { - if c.Flags().Lookup(f.Name) == nil { - c.Flags().AddFlag(f) - } - }) - } - if x.HasParent() { - rmerge(x.parent) - } - } - - rmerge(c) + c.updateParentsPflags() + c.Flags().AddFlagSet(c.PersistentFlags()) + c.Flags().AddFlagSet(c.parentsPflags) +} + +// updateParentsPflags updates c.parentsPflags by adding +// new persistent flags of all parents. +// If c.parentsPflags == nil, it makes new. +func (c *Command) updateParentsPflags() { + if c.parentsPflags == nil { + c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) + c.parentsPflags.SetOutput(c.flagErrorBuf) + c.parentsPflags.SortFlags = false + } + + if c.globNormFunc != nil { + c.parentsPflags.SetNormalizeFunc(c.globNormFunc) + } + + c.Root().PersistentFlags().AddFlagSet(flag.CommandLine) + + c.VisitParents(func(parent *Command) { + c.parentsPflags.AddFlagSet(parent.PersistentFlags()) + }) } diff --git a/vendor/github.com/spf13/cobra/command_notwin.go b/vendor/github.com/spf13/cobra/command_notwin.go new file mode 100644 index 00000000..6159c1cc --- /dev/null +++ b/vendor/github.com/spf13/cobra/command_notwin.go @@ -0,0 +1,5 @@ +// +build !windows + +package cobra + +var preExecHookFn func(*Command) diff --git a/vendor/github.com/spf13/cobra/command_test.go b/vendor/github.com/spf13/cobra/command_test.go index 477d84e7..d874a9a5 100644 --- a/vendor/github.com/spf13/cobra/command_test.go +++ b/vendor/github.com/spf13/cobra/command_test.go @@ -1,10 +1,463 @@ package cobra import ( + "bytes" + "fmt" + "os" "reflect" + "strings" "testing" + + "github.com/spf13/pflag" ) +func emptyRun(*Command, []string) {} + +func executeCommand(root *Command, args ...string) (output string, err error) { + _, output, err = executeCommandC(root, args...) + return output, err +} + +func executeCommandC(root *Command, args ...string) (c *Command, output string, err error) { + buf := new(bytes.Buffer) + root.SetOutput(buf) + root.SetArgs(args) + + c, err = root.ExecuteC() + + return c, buf.String(), err +} + +func resetCommandLineFlagSet() { + pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError) +} + +func checkStringContains(t *testing.T, got, expected string) { + if !strings.Contains(got, expected) { + t.Errorf("Expected to contain: \n %v\nGot:\n %v\n", expected, got) + } +} + +func checkStringOmits(t *testing.T, got, expected string) { + if strings.Contains(got, expected) { + t.Errorf("Expected to not contain: \n %v\nGot: %v", expected, got) + } +} + +func TestSingleCommand(t *testing.T) { + var rootCmdArgs []string + rootCmd := &Command{ + Use: "root", + Args: ExactArgs(2), + Run: func(_ *Command, args []string) { rootCmdArgs = args }, + } + aCmd := &Command{Use: "a", Args: NoArgs, Run: emptyRun} + bCmd := &Command{Use: "b", Args: NoArgs, Run: emptyRun} + rootCmd.AddCommand(aCmd, bCmd) + + output, err := executeCommand(rootCmd, "one", "two") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + got := strings.Join(rootCmdArgs, " ") + expected := "one two" + if got != expected { + t.Errorf("rootCmdArgs expected: %q, got: %q", expected, got) + } +} + +func TestChildCommand(t *testing.T) { + var child1CmdArgs []string + rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} + child1Cmd := &Command{ + Use: "child1", + Args: ExactArgs(2), + Run: func(_ *Command, args []string) { child1CmdArgs = args }, + } + child2Cmd := &Command{Use: "child2", Args: NoArgs, Run: emptyRun} + rootCmd.AddCommand(child1Cmd, child2Cmd) + + output, err := executeCommand(rootCmd, "child1", "one", "two") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + got := strings.Join(child1CmdArgs, " ") + expected := "one two" + if got != expected { + t.Errorf("child1CmdArgs expected: %q, got: %q", expected, got) + } +} + +func TestCallCommandWithoutSubcommands(t *testing.T) { + rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} + _, err := executeCommand(rootCmd) + if err != nil { + t.Errorf("Calling command without subcommands should not have error: %v", err) + } +} + +func TestRootExecuteUnknownCommand(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun}) + + output, _ := executeCommand(rootCmd, "unknown") + + expected := "Error: unknown command \"unknown\" for \"root\"\nRun 'root --help' for usage.\n" + + if output != expected { + t.Errorf("Expected:\n %q\nGot:\n %q\n", expected, output) + } +} + +func TestSubcommandExecuteC(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + childCmd := &Command{Use: "child", Run: emptyRun} + rootCmd.AddCommand(childCmd) + + c, output, err := executeCommandC(rootCmd, "child") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + if c.Name() != "child" { + t.Errorf(`invalid command returned from ExecuteC: expected "child"', got %q`, c.Name()) + } +} + +func TestRootUnknownCommandSilenced(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + rootCmd.SilenceErrors = true + rootCmd.SilenceUsage = true + rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun}) + + output, _ := executeCommand(rootCmd, "unknown") + if output != "" { + t.Errorf("Expected blank output, because of silenced usage.\nGot:\n %q\n", output) + } +} + +func TestCommandAlias(t *testing.T) { + var timesCmdArgs []string + rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} + echoCmd := &Command{ + Use: "echo", + Aliases: []string{"say", "tell"}, + Args: NoArgs, + Run: emptyRun, + } + timesCmd := &Command{ + Use: "times", + Args: ExactArgs(2), + Run: func(_ *Command, args []string) { timesCmdArgs = args }, + } + echoCmd.AddCommand(timesCmd) + rootCmd.AddCommand(echoCmd) + + output, err := executeCommand(rootCmd, "tell", "times", "one", "two") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + got := strings.Join(timesCmdArgs, " ") + expected := "one two" + if got != expected { + t.Errorf("timesCmdArgs expected: %v, got: %v", expected, got) + } +} + +func TestEnablePrefixMatching(t *testing.T) { + EnablePrefixMatching = true + + var aCmdArgs []string + rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} + aCmd := &Command{ + Use: "aCmd", + Args: ExactArgs(2), + Run: func(_ *Command, args []string) { aCmdArgs = args }, + } + bCmd := &Command{Use: "bCmd", Args: NoArgs, Run: emptyRun} + rootCmd.AddCommand(aCmd, bCmd) + + output, err := executeCommand(rootCmd, "a", "one", "two") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + got := strings.Join(aCmdArgs, " ") + expected := "one two" + if got != expected { + t.Errorf("aCmdArgs expected: %q, got: %q", expected, got) + } + + EnablePrefixMatching = false +} + +func TestAliasPrefixMatching(t *testing.T) { + EnablePrefixMatching = true + + var timesCmdArgs []string + rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} + echoCmd := &Command{ + Use: "echo", + Aliases: []string{"say", "tell"}, + Args: NoArgs, + Run: emptyRun, + } + timesCmd := &Command{ + Use: "times", + Args: ExactArgs(2), + Run: func(_ *Command, args []string) { timesCmdArgs = args }, + } + echoCmd.AddCommand(timesCmd) + rootCmd.AddCommand(echoCmd) + + output, err := executeCommand(rootCmd, "sa", "times", "one", "two") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + got := strings.Join(timesCmdArgs, " ") + expected := "one two" + if got != expected { + t.Errorf("timesCmdArgs expected: %v, got: %v", expected, got) + } + + EnablePrefixMatching = false +} + +// TestChildSameName checks the correct behaviour of cobra in cases, +// when an application with name "foo" and with subcommand "foo" +// is executed with args "foo foo". +func TestChildSameName(t *testing.T) { + var fooCmdArgs []string + rootCmd := &Command{Use: "foo", Args: NoArgs, Run: emptyRun} + fooCmd := &Command{ + Use: "foo", + Args: ExactArgs(2), + Run: func(_ *Command, args []string) { fooCmdArgs = args }, + } + barCmd := &Command{Use: "bar", Args: NoArgs, Run: emptyRun} + rootCmd.AddCommand(fooCmd, barCmd) + + output, err := executeCommand(rootCmd, "foo", "one", "two") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + got := strings.Join(fooCmdArgs, " ") + expected := "one two" + if got != expected { + t.Errorf("fooCmdArgs expected: %v, got: %v", expected, got) + } +} + +// TestGrandChildSameName checks the correct behaviour of cobra in cases, +// when user has a root command and a grand child +// with the same name. +func TestGrandChildSameName(t *testing.T) { + var fooCmdArgs []string + rootCmd := &Command{Use: "foo", Args: NoArgs, Run: emptyRun} + barCmd := &Command{Use: "bar", Args: NoArgs, Run: emptyRun} + fooCmd := &Command{ + Use: "foo", + Args: ExactArgs(2), + Run: func(_ *Command, args []string) { fooCmdArgs = args }, + } + barCmd.AddCommand(fooCmd) + rootCmd.AddCommand(barCmd) + + output, err := executeCommand(rootCmd, "bar", "foo", "one", "two") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + got := strings.Join(fooCmdArgs, " ") + expected := "one two" + if got != expected { + t.Errorf("fooCmdArgs expected: %v, got: %v", expected, got) + } +} + +func TestFlagLong(t *testing.T) { + var cArgs []string + c := &Command{ + Use: "c", + Args: ArbitraryArgs, + Run: func(_ *Command, args []string) { cArgs = args }, + } + + var intFlagValue int + var stringFlagValue string + c.Flags().IntVar(&intFlagValue, "intf", -1, "") + c.Flags().StringVar(&stringFlagValue, "sf", "", "") + + output, err := executeCommand(c, "--intf=7", "--sf=abc", "one", "--", "two") + if output != "" { + t.Errorf("Unexpected output: %v", err) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + if c.ArgsLenAtDash() != 1 { + t.Errorf("Expected ArgsLenAtDash: %v but got %v", 1, c.ArgsLenAtDash()) + } + if intFlagValue != 7 { + t.Errorf("Expected intFlagValue: %v, got %v", 7, intFlagValue) + } + if stringFlagValue != "abc" { + t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue) + } + + got := strings.Join(cArgs, " ") + expected := "one two" + if got != expected { + t.Errorf("Expected arguments: %q, got %q", expected, got) + } +} + +func TestFlagShort(t *testing.T) { + var cArgs []string + c := &Command{ + Use: "c", + Args: ArbitraryArgs, + Run: func(_ *Command, args []string) { cArgs = args }, + } + + var intFlagValue int + var stringFlagValue string + c.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "") + c.Flags().StringVarP(&stringFlagValue, "sf", "s", "", "") + + output, err := executeCommand(c, "-i", "7", "-sabc", "one", "two") + if output != "" { + t.Errorf("Unexpected output: %v", err) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + if intFlagValue != 7 { + t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue) + } + if stringFlagValue != "abc" { + t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue) + } + + got := strings.Join(cArgs, " ") + expected := "one two" + if got != expected { + t.Errorf("Expected arguments: %q, got %q", expected, got) + } +} + +func TestChildFlag(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + childCmd := &Command{Use: "child", Run: emptyRun} + rootCmd.AddCommand(childCmd) + + var intFlagValue int + childCmd.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "") + + output, err := executeCommand(rootCmd, "child", "-i7") + if output != "" { + t.Errorf("Unexpected output: %v", err) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + if intFlagValue != 7 { + t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue) + } +} + +func TestChildFlagWithParentLocalFlag(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + childCmd := &Command{Use: "child", Run: emptyRun} + rootCmd.AddCommand(childCmd) + + var intFlagValue int + rootCmd.Flags().StringP("sf", "s", "", "") + childCmd.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "") + + _, err := executeCommand(rootCmd, "child", "-i7", "-sabc") + if err == nil { + t.Errorf("Invalid flag should generate error") + } + + checkStringContains(t, err.Error(), "unknown shorthand") + + if intFlagValue != 7 { + t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue) + } +} + +func TestFlagInvalidInput(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + rootCmd.Flags().IntP("intf", "i", -1, "") + + _, err := executeCommand(rootCmd, "-iabc") + if err == nil { + t.Errorf("Invalid flag value should generate error") + } + + checkStringContains(t, err.Error(), "invalid syntax") +} + +func TestFlagBeforeCommand(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + childCmd := &Command{Use: "child", Run: emptyRun} + rootCmd.AddCommand(childCmd) + + var flagValue int + childCmd.Flags().IntVarP(&flagValue, "intf", "i", -1, "") + + // With short flag. + _, err := executeCommand(rootCmd, "-i7", "child") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + if flagValue != 7 { + t.Errorf("Expected flag value: %v, got %v", 7, flagValue) + } + + // With long flag. + _, err = executeCommand(rootCmd, "--intf=8", "child") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + if flagValue != 8 { + t.Errorf("Expected flag value: %v, got %v", 9, flagValue) + } +} + func TestStripFlags(t *testing.T) { tests := []struct { input []string @@ -15,11 +468,11 @@ func TestStripFlags(t *testing.T) { []string{"foo", "bar"}, }, { - []string{"foo", "--bar", "-b"}, + []string{"foo", "--str", "-s"}, []string{"foo"}, }, { - []string{"-b", "foo", "--bar", "bar"}, + []string{"-s", "foo", "--str", "bar"}, []string{}, }, { @@ -35,7 +488,7 @@ func TestStripFlags(t *testing.T) { []string{"echo"}, }, { - []string{"-ib", "echo", "-bfoo", "baz"}, + []string{"-ib", "echo", "-sfoo", "baz"}, []string{"echo", "baz"}, }, { @@ -43,15 +496,15 @@ func TestStripFlags(t *testing.T) { []string{"bar", "blah"}, }, { - []string{"--int=baz", "-bbar", "-i", "foo", "blah"}, + []string{"--int=baz", "-sbar", "-i", "foo", "blah"}, []string{"blah"}, }, { - []string{"--cat", "bar", "-i", "foo", "blah"}, + []string{"--bool", "bar", "-i", "foo", "blah"}, []string{"bar", "blah"}, }, { - []string{"-c", "bar", "-i", "foo", "blah"}, + []string{"-b", "bar", "-i", "foo", "blah"}, []string{"bar", "blah"}, }, { @@ -64,27 +517,1112 @@ func TestStripFlags(t *testing.T) { }, } - cmdPrint := &Command{ - Use: "print [string to print]", - Short: "Print anything to the screen", - Long: `an utterly useless command for testing.`, - Run: func(cmd *Command, args []string) { - tp = args - }, - } + c := &Command{Use: "c", Run: emptyRun} + c.PersistentFlags().BoolP("persist", "p", false, "") + c.Flags().IntP("int", "i", -1, "") + c.Flags().StringP("str", "s", "", "") + c.Flags().BoolP("bool", "b", false, "") - var flagi int - var flagstr string - var flagbool bool - cmdPrint.PersistentFlags().BoolVarP(&flagbool, "persist", "p", false, "help for persistent one") - cmdPrint.Flags().IntVarP(&flagi, "int", "i", 345, "help message for flag int") - cmdPrint.Flags().StringVarP(&flagstr, "bar", "b", "bar", "help message for flag string") - cmdPrint.Flags().BoolVarP(&flagbool, "cat", "c", false, "help message for flag bool") - - for _, test := range tests { - output := stripFlags(test.input, cmdPrint) - if !reflect.DeepEqual(test.output, output) { - t.Errorf("expected: %v, got: %v", test.output, output) + for i, test := range tests { + got := stripFlags(test.input, c) + if !reflect.DeepEqual(test.output, got) { + t.Errorf("(%v) Expected: %v, got: %v", i, test.output, got) } } } + +func TestDisableFlagParsing(t *testing.T) { + var cArgs []string + c := &Command{ + Use: "c", + DisableFlagParsing: true, + Run: func(_ *Command, args []string) { + cArgs = args + }, + } + + args := []string{"cmd", "-v", "-race", "-file", "foo.go"} + output, err := executeCommand(c, args...) + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + if !reflect.DeepEqual(args, cArgs) { + t.Errorf("Expected: %v, got: %v", args, cArgs) + } +} + +func TestPersistentFlagsOnSameCommand(t *testing.T) { + var rootCmdArgs []string + rootCmd := &Command{ + Use: "root", + Args: ArbitraryArgs, + Run: func(_ *Command, args []string) { rootCmdArgs = args }, + } + + var flagValue int + rootCmd.PersistentFlags().IntVarP(&flagValue, "intf", "i", -1, "") + + output, err := executeCommand(rootCmd, "-i7", "one", "two") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + got := strings.Join(rootCmdArgs, " ") + expected := "one two" + if got != expected { + t.Errorf("rootCmdArgs expected: %q, got %q", expected, got) + } + if flagValue != 7 { + t.Errorf("flagValue expected: %v, got %v", 7, flagValue) + } +} + +// TestEmptyInputs checks, +// if flags correctly parsed with blank strings in args. +func TestEmptyInputs(t *testing.T) { + c := &Command{Use: "c", Run: emptyRun} + + var flagValue int + c.Flags().IntVarP(&flagValue, "intf", "i", -1, "") + + output, err := executeCommand(c, "", "-i7", "") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + if flagValue != 7 { + t.Errorf("flagValue expected: %v, got %v", 7, flagValue) + } +} + +func TestOverwrittenFlag(t *testing.T) { + // TODO: This test fails, but should work. + t.Skip() + + parent := &Command{Use: "parent", Run: emptyRun} + child := &Command{Use: "child", Run: emptyRun} + + parent.PersistentFlags().Bool("boolf", false, "") + parent.PersistentFlags().Int("intf", -1, "") + child.Flags().String("strf", "", "") + child.Flags().Int("intf", -1, "") + + parent.AddCommand(child) + + childInherited := child.InheritedFlags() + childLocal := child.LocalFlags() + + if childLocal.Lookup("strf") == nil { + t.Error(`LocalFlags expected to contain "strf", got "nil"`) + } + if childInherited.Lookup("boolf") == nil { + t.Error(`InheritedFlags expected to contain "boolf", got "nil"`) + } + + if childInherited.Lookup("intf") != nil { + t.Errorf(`InheritedFlags should not contain overwritten flag "intf"`) + } + if childLocal.Lookup("intf") == nil { + t.Error(`LocalFlags expected to contain "intf", got "nil"`) + } +} + +func TestPersistentFlagsOnChild(t *testing.T) { + var childCmdArgs []string + rootCmd := &Command{Use: "root", Run: emptyRun} + childCmd := &Command{ + Use: "child", + Args: ArbitraryArgs, + Run: func(_ *Command, args []string) { childCmdArgs = args }, + } + rootCmd.AddCommand(childCmd) + + var parentFlagValue int + var childFlagValue int + rootCmd.PersistentFlags().IntVarP(&parentFlagValue, "parentf", "p", -1, "") + childCmd.Flags().IntVarP(&childFlagValue, "childf", "c", -1, "") + + output, err := executeCommand(rootCmd, "child", "-c7", "-p8", "one", "two") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + got := strings.Join(childCmdArgs, " ") + expected := "one two" + if got != expected { + t.Errorf("childCmdArgs expected: %q, got %q", expected, got) + } + if parentFlagValue != 8 { + t.Errorf("parentFlagValue expected: %v, got %v", 8, parentFlagValue) + } + if childFlagValue != 7 { + t.Errorf("childFlagValue expected: %v, got %v", 7, childFlagValue) + } +} + +func TestRequiredFlags(t *testing.T) { + c := &Command{Use: "c", Run: emptyRun} + c.Flags().String("foo1", "", "") + c.MarkFlagRequired("foo1") + c.Flags().String("foo2", "", "") + c.MarkFlagRequired("foo2") + c.Flags().String("bar", "", "") + + expected := fmt.Sprintf("required flag(s) %q, %q not set", "foo1", "foo2") + + _, err := executeCommand(c) + got := err.Error() + + if got != expected { + t.Errorf("Expected error: %q, got: %q", expected, got) + } +} + +func TestPersistentRequiredFlags(t *testing.T) { + parent := &Command{Use: "parent", Run: emptyRun} + parent.PersistentFlags().String("foo1", "", "") + parent.MarkPersistentFlagRequired("foo1") + parent.PersistentFlags().String("foo2", "", "") + parent.MarkPersistentFlagRequired("foo2") + parent.Flags().String("foo3", "", "") + + child := &Command{Use: "child", Run: emptyRun} + child.Flags().String("bar1", "", "") + child.MarkFlagRequired("bar1") + child.Flags().String("bar2", "", "") + child.MarkFlagRequired("bar2") + child.Flags().String("bar3", "", "") + + parent.AddCommand(child) + + expected := fmt.Sprintf("required flag(s) %q, %q, %q, %q not set", "bar1", "bar2", "foo1", "foo2") + + _, err := executeCommand(parent, "child") + if err.Error() != expected { + t.Errorf("Expected %q, got %q", expected, err.Error()) + } +} + +func TestInitHelpFlagMergesFlags(t *testing.T) { + usage := "custom flag" + rootCmd := &Command{Use: "root"} + rootCmd.PersistentFlags().Bool("help", false, "custom flag") + childCmd := &Command{Use: "child"} + rootCmd.AddCommand(childCmd) + + childCmd.InitDefaultHelpFlag() + got := childCmd.Flags().Lookup("help").Usage + if got != usage { + t.Errorf("Expected the help flag from the root command with usage: %v\nGot the default with usage: %v", usage, got) + } +} + +func TestHelpCommandExecuted(t *testing.T) { + rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun} + rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun}) + + output, err := executeCommand(rootCmd, "help") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, rootCmd.Long) +} + +func TestHelpCommandExecutedOnChild(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + childCmd := &Command{Use: "child", Long: "Long description", Run: emptyRun} + rootCmd.AddCommand(childCmd) + + output, err := executeCommand(rootCmd, "help", "child") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, childCmd.Long) +} + +func TestSetHelpCommand(t *testing.T) { + c := &Command{Use: "c", Run: emptyRun} + c.AddCommand(&Command{Use: "empty", Run: emptyRun}) + + expected := "WORKS" + c.SetHelpCommand(&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.`, + Run: func(c *Command, _ []string) { c.Print(expected) }, + }) + + got, err := executeCommand(c, "help") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + if got != expected { + t.Errorf("Expected to contain %q, got %q", expected, got) + } +} + +func TestHelpFlagExecuted(t *testing.T) { + rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun} + + output, err := executeCommand(rootCmd, "--help") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, rootCmd.Long) +} + +func TestHelpFlagExecutedOnChild(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + childCmd := &Command{Use: "child", Long: "Long description", Run: emptyRun} + rootCmd.AddCommand(childCmd) + + output, err := executeCommand(rootCmd, "child", "--help") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, childCmd.Long) +} + +// TestHelpFlagInHelp checks, +// if '--help' flag is shown in help for child (executing `parent help child`), +// that has no other flags. +// Related to https://github.com/spf13/cobra/issues/302. +func TestHelpFlagInHelp(t *testing.T) { + parentCmd := &Command{Use: "parent", Run: func(*Command, []string) {}} + + childCmd := &Command{Use: "child", Run: func(*Command, []string) {}} + parentCmd.AddCommand(childCmd) + + output, err := executeCommand(parentCmd, "help", "child") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, "[flags]") +} + +func TestFlagsInUsage(t *testing.T) { + rootCmd := &Command{Use: "root", Args: NoArgs, Run: func(*Command, []string) {}} + output, err := executeCommand(rootCmd, "--help") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, "[flags]") +} + +func TestHelpExecutedOnNonRunnableChild(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + childCmd := &Command{Use: "child", Long: "Long description"} + rootCmd.AddCommand(childCmd) + + output, err := executeCommand(rootCmd, "child") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, childCmd.Long) +} + +func TestVersionFlagExecuted(t *testing.T) { + rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun} + + output, err := executeCommand(rootCmd, "--version", "arg1") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, "root version 1.0.0") +} + +func TestVersionTemplate(t *testing.T) { + rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun} + rootCmd.SetVersionTemplate(`customized version: {{.Version}}`) + + output, err := executeCommand(rootCmd, "--version", "arg1") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, "customized version: 1.0.0") +} + +func TestVersionFlagExecutedOnSubcommand(t *testing.T) { + rootCmd := &Command{Use: "root", Version: "1.0.0"} + rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun}) + + output, err := executeCommand(rootCmd, "--version", "sub") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, "root version 1.0.0") +} + +func TestVersionFlagOnlyAddedToRoot(t *testing.T) { + rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun} + rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun}) + + _, err := executeCommand(rootCmd, "sub", "--version") + if err == nil { + t.Errorf("Expected error") + } + + checkStringContains(t, err.Error(), "unknown flag: --version") +} + +func TestVersionFlagOnlyExistsIfVersionNonEmpty(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + + _, err := executeCommand(rootCmd, "--version") + if err == nil { + t.Errorf("Expected error") + } + checkStringContains(t, err.Error(), "unknown flag: --version") +} + +func TestUsageIsNotPrintedTwice(t *testing.T) { + var cmd = &Command{Use: "root"} + var sub = &Command{Use: "sub"} + cmd.AddCommand(sub) + + output, _ := executeCommand(cmd, "") + if strings.Count(output, "Usage:") != 1 { + t.Error("Usage output is not printed exactly once") + } +} + +func TestVisitParents(t *testing.T) { + c := &Command{Use: "app"} + sub := &Command{Use: "sub"} + dsub := &Command{Use: "dsub"} + sub.AddCommand(dsub) + c.AddCommand(sub) + + total := 0 + add := func(x *Command) { + total++ + } + sub.VisitParents(add) + if total != 1 { + t.Errorf("Should have visited 1 parent but visited %d", total) + } + + total = 0 + dsub.VisitParents(add) + if total != 2 { + t.Errorf("Should have visited 2 parents but visited %d", total) + } + + total = 0 + c.VisitParents(add) + if total != 0 { + t.Errorf("Should have visited no parents but visited %d", total) + } +} + +func TestSuggestions(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + timesCmd := &Command{ + Use: "times", + SuggestFor: []string{"counts"}, + Run: emptyRun, + } + rootCmd.AddCommand(timesCmd) + + templateWithSuggestions := "Error: unknown command \"%s\" for \"root\"\n\nDid you mean this?\n\t%s\n\nRun 'root --help' for usage.\n" + templateWithoutSuggestions := "Error: unknown command \"%s\" for \"root\"\nRun 'root --help' for usage.\n" + + tests := map[string]string{ + "time": "times", + "tiems": "times", + "tims": "times", + "timeS": "times", + "rimes": "times", + "ti": "times", + "t": "times", + "timely": "times", + "ri": "", + "timezone": "", + "foo": "", + "counts": "times", + } + + for typo, suggestion := range tests { + for _, suggestionsDisabled := range []bool{true, false} { + rootCmd.DisableSuggestions = suggestionsDisabled + + var expected string + output, _ := executeCommand(rootCmd, typo) + + if suggestion == "" || suggestionsDisabled { + expected = fmt.Sprintf(templateWithoutSuggestions, typo) + } else { + expected = fmt.Sprintf(templateWithSuggestions, typo, suggestion) + } + + if output != expected { + t.Errorf("Unexpected response.\nExpected:\n %q\nGot:\n %q\n", expected, output) + } + } + } +} + +func TestRemoveCommand(t *testing.T) { + rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} + childCmd := &Command{Use: "child", Run: emptyRun} + rootCmd.AddCommand(childCmd) + rootCmd.RemoveCommand(childCmd) + + _, err := executeCommand(rootCmd, "child") + if err == nil { + t.Error("Expected error on calling removed command. Got nil.") + } +} + +func TestReplaceCommandWithRemove(t *testing.T) { + childUsed := 0 + rootCmd := &Command{Use: "root", Run: emptyRun} + child1Cmd := &Command{ + Use: "child", + Run: func(*Command, []string) { childUsed = 1 }, + } + child2Cmd := &Command{ + Use: "child", + Run: func(*Command, []string) { childUsed = 2 }, + } + rootCmd.AddCommand(child1Cmd) + rootCmd.RemoveCommand(child1Cmd) + rootCmd.AddCommand(child2Cmd) + + output, err := executeCommand(rootCmd, "child") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + if childUsed == 1 { + t.Error("Removed command shouldn't be called") + } + if childUsed != 2 { + t.Error("Replacing command should have been called but didn't") + } +} + +func TestDeprecatedCommand(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + deprecatedCmd := &Command{ + Use: "deprecated", + Deprecated: "This command is deprecated", + Run: emptyRun, + } + rootCmd.AddCommand(deprecatedCmd) + + output, err := executeCommand(rootCmd, "deprecated") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + checkStringContains(t, output, deprecatedCmd.Deprecated) +} + +func TestHooks(t *testing.T) { + var ( + persPreArgs string + preArgs string + runArgs string + postArgs string + persPostArgs string + ) + + c := &Command{ + Use: "c", + PersistentPreRun: func(_ *Command, args []string) { + persPreArgs = strings.Join(args, " ") + }, + PreRun: func(_ *Command, args []string) { + preArgs = strings.Join(args, " ") + }, + Run: func(_ *Command, args []string) { + runArgs = strings.Join(args, " ") + }, + PostRun: func(_ *Command, args []string) { + postArgs = strings.Join(args, " ") + }, + PersistentPostRun: func(_ *Command, args []string) { + persPostArgs = strings.Join(args, " ") + }, + } + + output, err := executeCommand(c, "one", "two") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + if persPreArgs != "one two" { + t.Errorf("Expected persPreArgs %q, got %q", "one two", persPreArgs) + } + if preArgs != "one two" { + t.Errorf("Expected preArgs %q, got %q", "one two", preArgs) + } + if runArgs != "one two" { + t.Errorf("Expected runArgs %q, got %q", "one two", runArgs) + } + if postArgs != "one two" { + t.Errorf("Expected postArgs %q, got %q", "one two", postArgs) + } + if persPostArgs != "one two" { + t.Errorf("Expected persPostArgs %q, got %q", "one two", persPostArgs) + } +} + +func TestPersistentHooks(t *testing.T) { + var ( + parentPersPreArgs string + parentPreArgs string + parentRunArgs string + parentPostArgs string + parentPersPostArgs string + ) + + var ( + childPersPreArgs string + childPreArgs string + childRunArgs string + childPostArgs string + childPersPostArgs string + ) + + parentCmd := &Command{ + Use: "parent", + PersistentPreRun: func(_ *Command, args []string) { + parentPersPreArgs = strings.Join(args, " ") + }, + PreRun: func(_ *Command, args []string) { + parentPreArgs = strings.Join(args, " ") + }, + Run: func(_ *Command, args []string) { + parentRunArgs = strings.Join(args, " ") + }, + PostRun: func(_ *Command, args []string) { + parentPostArgs = strings.Join(args, " ") + }, + PersistentPostRun: func(_ *Command, args []string) { + parentPersPostArgs = strings.Join(args, " ") + }, + } + + childCmd := &Command{ + Use: "child", + PersistentPreRun: func(_ *Command, args []string) { + childPersPreArgs = strings.Join(args, " ") + }, + PreRun: func(_ *Command, args []string) { + childPreArgs = strings.Join(args, " ") + }, + Run: func(_ *Command, args []string) { + childRunArgs = strings.Join(args, " ") + }, + PostRun: func(_ *Command, args []string) { + childPostArgs = strings.Join(args, " ") + }, + PersistentPostRun: func(_ *Command, args []string) { + childPersPostArgs = strings.Join(args, " ") + }, + } + parentCmd.AddCommand(childCmd) + + output, err := executeCommand(parentCmd, "child", "one", "two") + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + // TODO: This test fails, but should not. + // Related to https://github.com/spf13/cobra/issues/252. + // + // if parentPersPreArgs != "one two" { + // t.Errorf("Expected parentPersPreArgs %q, got %q", "one two", parentPersPreArgs) + // } + if parentPreArgs != "" { + t.Errorf("Expected blank parentPreArgs, got %q", parentPreArgs) + } + if parentRunArgs != "" { + t.Errorf("Expected blank parentRunArgs, got %q", parentRunArgs) + } + if parentPostArgs != "" { + t.Errorf("Expected blank parentPostArgs, got %q", parentPostArgs) + } + // TODO: This test fails, but should not. + // Related to https://github.com/spf13/cobra/issues/252. + // + // if parentPersPostArgs != "one two" { + // t.Errorf("Expected parentPersPostArgs %q, got %q", "one two", parentPersPostArgs) + // } + + if childPersPreArgs != "one two" { + t.Errorf("Expected childPersPreArgs %q, got %q", "one two", childPersPreArgs) + } + if childPreArgs != "one two" { + t.Errorf("Expected childPreArgs %q, got %q", "one two", childPreArgs) + } + if childRunArgs != "one two" { + t.Errorf("Expected childRunArgs %q, got %q", "one two", childRunArgs) + } + if childPostArgs != "one two" { + t.Errorf("Expected childPostArgs %q, got %q", "one two", childPostArgs) + } + if childPersPostArgs != "one two" { + t.Errorf("Expected childPersPostArgs %q, got %q", "one two", childPersPostArgs) + } +} + +// Related to https://github.com/spf13/cobra/issues/521. +func TestGlobalNormFuncPropagation(t *testing.T) { + normFunc := func(f *pflag.FlagSet, name string) pflag.NormalizedName { + return pflag.NormalizedName(name) + } + + rootCmd := &Command{Use: "root", Run: emptyRun} + childCmd := &Command{Use: "child", Run: emptyRun} + rootCmd.AddCommand(childCmd) + + rootCmd.SetGlobalNormalizationFunc(normFunc) + if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() { + t.Error("rootCmd seems to have a wrong normalization function") + } + + if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(childCmd.GlobalNormalizationFunc()).Pointer() { + t.Error("childCmd should have had the normalization function of rootCmd") + } +} + +// Related to https://github.com/spf13/cobra/issues/521. +func TestNormPassedOnLocal(t *testing.T) { + toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName { + return pflag.NormalizedName(strings.ToUpper(name)) + } + + c := &Command{} + c.Flags().Bool("flagname", true, "this is a dummy flag") + c.SetGlobalNormalizationFunc(toUpper) + if c.LocalFlags().Lookup("flagname") != c.LocalFlags().Lookup("FLAGNAME") { + t.Error("Normalization function should be passed on to Local flag set") + } +} + +// Related to https://github.com/spf13/cobra/issues/521. +func TestNormPassedOnInherited(t *testing.T) { + toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName { + return pflag.NormalizedName(strings.ToUpper(name)) + } + + c := &Command{} + c.SetGlobalNormalizationFunc(toUpper) + + child1 := &Command{} + c.AddCommand(child1) + + c.PersistentFlags().Bool("flagname", true, "") + + child2 := &Command{} + c.AddCommand(child2) + + inherited := child1.InheritedFlags() + if inherited.Lookup("flagname") == nil || inherited.Lookup("flagname") != inherited.Lookup("FLAGNAME") { + t.Error("Normalization function should be passed on to inherited flag set in command added before flag") + } + + inherited = child2.InheritedFlags() + if inherited.Lookup("flagname") == nil || inherited.Lookup("flagname") != inherited.Lookup("FLAGNAME") { + t.Error("Normalization function should be passed on to inherited flag set in command added after flag") + } +} + +// Related to https://github.com/spf13/cobra/issues/521. +func TestConsistentNormalizedName(t *testing.T) { + toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName { + return pflag.NormalizedName(strings.ToUpper(name)) + } + n := func(f *pflag.FlagSet, name string) pflag.NormalizedName { + return pflag.NormalizedName(name) + } + + c := &Command{} + c.Flags().Bool("flagname", true, "") + c.SetGlobalNormalizationFunc(toUpper) + c.SetGlobalNormalizationFunc(n) + + if c.LocalFlags().Lookup("flagname") == c.LocalFlags().Lookup("FLAGNAME") { + t.Error("Normalizing flag names should not result in duplicate flags") + } +} + +func TestFlagOnPflagCommandLine(t *testing.T) { + flagName := "flagOnCommandLine" + pflag.String(flagName, "", "about my flag") + + c := &Command{Use: "c", Run: emptyRun} + c.AddCommand(&Command{Use: "child", Run: emptyRun}) + + output, _ := executeCommand(c, "--help") + checkStringContains(t, output, flagName) + + resetCommandLineFlagSet() +} + +// TestHiddenCommandExecutes checks, +// if hidden commands run as intended. +func TestHiddenCommandExecutes(t *testing.T) { + executed := false + c := &Command{ + Use: "c", + Hidden: true, + Run: func(*Command, []string) { executed = true }, + } + + output, err := executeCommand(c) + if output != "" { + t.Errorf("Unexpected output: %v", output) + } + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + if !executed { + t.Error("Hidden command should have been executed") + } +} + +// test to ensure hidden commands do not show up in usage/help text +func TestHiddenCommandIsHidden(t *testing.T) { + c := &Command{Use: "c", Hidden: true, Run: emptyRun} + if c.IsAvailableCommand() { + t.Errorf("Hidden command should be unavailable") + } +} + +func TestCommandsAreSorted(t *testing.T) { + EnableCommandSorting = true + + originalNames := []string{"middle", "zlast", "afirst"} + expectedNames := []string{"afirst", "middle", "zlast"} + + var rootCmd = &Command{Use: "root"} + + for _, name := range originalNames { + rootCmd.AddCommand(&Command{Use: name}) + } + + for i, c := range rootCmd.Commands() { + got := c.Name() + if expectedNames[i] != got { + t.Errorf("Expected: %s, got: %s", expectedNames[i], got) + } + } + + EnableCommandSorting = true +} + +func TestEnableCommandSortingIsDisabled(t *testing.T) { + EnableCommandSorting = false + + originalNames := []string{"middle", "zlast", "afirst"} + + var rootCmd = &Command{Use: "root"} + + for _, name := range originalNames { + rootCmd.AddCommand(&Command{Use: name}) + } + + for i, c := range rootCmd.Commands() { + got := c.Name() + if originalNames[i] != got { + t.Errorf("expected: %s, got: %s", originalNames[i], got) + } + } + + EnableCommandSorting = true +} + +func TestSetOutput(t *testing.T) { + c := &Command{} + c.SetOutput(nil) + if out := c.OutOrStdout(); out != os.Stdout { + t.Errorf("Expected setting output to nil to revert back to stdout") + } +} + +func TestFlagErrorFunc(t *testing.T) { + c := &Command{Use: "c", Run: emptyRun} + + expectedFmt := "This is expected: %v" + c.SetFlagErrorFunc(func(_ *Command, err error) error { + return fmt.Errorf(expectedFmt, err) + }) + + _, err := executeCommand(c, "--unknown-flag") + + got := err.Error() + expected := fmt.Sprintf(expectedFmt, "unknown flag: --unknown-flag") + if got != expected { + t.Errorf("Expected %v, got %v", expected, got) + } +} + +// TestSortedFlags checks, +// if cmd.LocalFlags() is unsorted when cmd.Flags().SortFlags set to false. +// Related to https://github.com/spf13/cobra/issues/404. +func TestSortedFlags(t *testing.T) { + c := &Command{} + c.Flags().SortFlags = false + names := []string{"C", "B", "A", "D"} + for _, name := range names { + c.Flags().Bool(name, false, "") + } + + i := 0 + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + if i == len(names) { + return + } + if stringInSlice(f.Name, names) { + if names[i] != f.Name { + t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name) + } + i++ + } + }) +} + +// 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: emptyRun} + c.mergePersistentFlags() + if c.Flags().Lookup("boolflag") == nil { + t.Fatal("Expecting to have flag from CommandLine in c.Flags()") + } + + resetCommandLineFlagSet() +} + +// TestUseDeprecatedFlags checks, +// if cobra.Execute() prints a message, if a deprecated flag is used. +// Related to https://github.com/spf13/cobra/issues/463. +func TestUseDeprecatedFlags(t *testing.T) { + c := &Command{Use: "c", Run: emptyRun} + c.Flags().BoolP("deprecated", "d", false, "deprecated flag") + c.Flags().MarkDeprecated("deprecated", "This flag is deprecated") + + output, err := executeCommand(c, "c", "-d") + if err != nil { + t.Error("Unexpected error:", err) + } + checkStringContains(t, output, "This flag is deprecated") +} + +func TestTraverseWithParentFlags(t *testing.T) { + rootCmd := &Command{Use: "root", TraverseChildren: true} + rootCmd.Flags().String("str", "", "") + rootCmd.Flags().BoolP("bool", "b", false, "") + + childCmd := &Command{Use: "child"} + childCmd.Flags().Int("int", -1, "") + + rootCmd.AddCommand(childCmd) + + c, args, err := rootCmd.Traverse([]string{"-b", "--str", "ok", "child", "--int"}) + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + if len(args) != 1 && args[0] != "--add" { + t.Errorf("Wrong args: %v", args) + } + if c.Name() != childCmd.Name() { + t.Errorf("Expected command: %q, got: %q", childCmd.Name(), c.Name()) + } +} + +func TestTraverseNoParentFlags(t *testing.T) { + rootCmd := &Command{Use: "root", TraverseChildren: true} + rootCmd.Flags().String("foo", "", "foo things") + + childCmd := &Command{Use: "child"} + childCmd.Flags().String("str", "", "") + rootCmd.AddCommand(childCmd) + + c, args, err := rootCmd.Traverse([]string{"child"}) + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + if len(args) != 0 { + t.Errorf("Wrong args %v", args) + } + if c.Name() != childCmd.Name() { + t.Errorf("Expected command: %q, got: %q", childCmd.Name(), c.Name()) + } +} + +func TestTraverseWithBadParentFlags(t *testing.T) { + rootCmd := &Command{Use: "root", TraverseChildren: true} + + childCmd := &Command{Use: "child"} + childCmd.Flags().String("str", "", "") + rootCmd.AddCommand(childCmd) + + expected := "unknown flag: --str" + + c, _, err := rootCmd.Traverse([]string{"--str", "ok", "child"}) + if err == nil || !strings.Contains(err.Error(), expected) { + t.Errorf("Expected error, %q, got %q", expected, err) + } + if c != nil { + t.Errorf("Expected nil command") + } +} + +func TestTraverseWithBadChildFlag(t *testing.T) { + rootCmd := &Command{Use: "root", TraverseChildren: true} + rootCmd.Flags().String("str", "", "") + + childCmd := &Command{Use: "child"} + rootCmd.AddCommand(childCmd) + + // Expect no error because the last commands args shouldn't be parsed in + // Traverse. + c, args, err := rootCmd.Traverse([]string{"child", "--str"}) + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + if len(args) != 1 && args[0] != "--str" { + t.Errorf("Wrong args: %v", args) + } + if c.Name() != childCmd.Name() { + t.Errorf("Expected command %q, got: %q", childCmd.Name(), c.Name()) + } +} + +func TestTraverseWithTwoSubcommands(t *testing.T) { + rootCmd := &Command{Use: "root", TraverseChildren: true} + + subCmd := &Command{Use: "sub", TraverseChildren: true} + rootCmd.AddCommand(subCmd) + + subsubCmd := &Command{ + Use: "subsub", + } + subCmd.AddCommand(subsubCmd) + + c, _, err := rootCmd.Traverse([]string{"sub", "subsub"}) + if err != nil { + t.Fatalf("Unexpected error: %v", err) + } + if c.Name() != subsubCmd.Name() { + t.Fatalf("Expected command: %q, got %q", subsubCmd.Name(), c.Name()) + } +} + +// TestUpdateName checks if c.Name() updates on changed c.Use. +// Related to https://github.com/spf13/cobra/pull/422#discussion_r143918343. +func TestUpdateName(t *testing.T) { + c := &Command{Use: "name xyz"} + originalName := c.Name() + + c.Use = "changedName abc" + if originalName == c.Name() || c.Name() != "changedName" { + t.Error("c.Name() should be updated on changed c.Use") + } +} + +type calledAsTestcase struct { + args []string + call string + want string + epm bool + tc bool +} + +func (tc *calledAsTestcase) test(t *testing.T) { + defer func(ov bool) { EnablePrefixMatching = ov }(EnablePrefixMatching) + EnablePrefixMatching = tc.epm + + var called *Command + run := func(c *Command, _ []string) { t.Logf("called: %q", c.Name()); called = c } + + parent := &Command{Use: "parent", Run: run} + child1 := &Command{Use: "child1", Run: run, Aliases: []string{"this"}} + child2 := &Command{Use: "child2", Run: run, Aliases: []string{"that"}} + + parent.AddCommand(child1) + parent.AddCommand(child2) + parent.SetArgs(tc.args) + + output := new(bytes.Buffer) + parent.SetOutput(output) + + parent.Execute() + + if called == nil { + if tc.call != "" { + t.Errorf("missing expected call to command: %s", tc.call) + } + return + } + + if called.Name() != tc.call { + t.Errorf("called command == %q; Wanted %q", called.Name(), tc.call) + } else if got := called.CalledAs(); got != tc.want { + t.Errorf("%s.CalledAs() == %q; Wanted: %q", tc.call, got, tc.want) + } +} + +func TestCalledAs(t *testing.T) { + tests := map[string]calledAsTestcase{ + "find/no-args": {nil, "parent", "parent", false, false}, + "find/real-name": {[]string{"child1"}, "child1", "child1", false, false}, + "find/full-alias": {[]string{"that"}, "child2", "that", false, false}, + "find/part-no-prefix": {[]string{"thi"}, "", "", false, false}, + "find/part-alias": {[]string{"thi"}, "child1", "this", true, false}, + "find/conflict": {[]string{"th"}, "", "", true, false}, + "traverse/no-args": {nil, "parent", "parent", false, true}, + "traverse/real-name": {[]string{"child1"}, "child1", "child1", false, true}, + "traverse/full-alias": {[]string{"that"}, "child2", "that", false, true}, + "traverse/part-no-prefix": {[]string{"thi"}, "", "", false, true}, + "traverse/part-alias": {[]string{"thi"}, "child1", "this", true, true}, + "traverse/conflict": {[]string{"th"}, "", "", true, true}, + } + + for name, tc := range tests { + t.Run(name, tc.test) + } +} diff --git a/vendor/github.com/spf13/cobra/command_win.go b/vendor/github.com/spf13/cobra/command_win.go new file mode 100644 index 00000000..edec728e --- /dev/null +++ b/vendor/github.com/spf13/cobra/command_win.go @@ -0,0 +1,20 @@ +// +build windows + +package cobra + +import ( + "os" + "time" + + "github.com/inconshreveable/mousetrap" +) + +var preExecHookFn = preExecHook + +func preExecHook(c *Command) { + if MousetrapHelpText != "" && mousetrap.StartedByExplorer() { + c.Print(MousetrapHelpText) + time.Sleep(5 * time.Second) + os.Exit(1) + } +} diff --git a/vendor/github.com/spf13/cobra/doc/cmd_test.go b/vendor/github.com/spf13/cobra/doc/cmd_test.go new file mode 100644 index 00000000..d29c577d --- /dev/null +++ b/vendor/github.com/spf13/cobra/doc/cmd_test.go @@ -0,0 +1,86 @@ +package doc + +import ( + "strings" + "testing" + + "github.com/spf13/cobra" +) + +func emptyRun(*cobra.Command, []string) {} + +func init() { + rootCmd.PersistentFlags().StringP("rootflag", "r", "two", "") + rootCmd.PersistentFlags().StringP("strtwo", "t", "two", "help message for parent flag strtwo") + + echoCmd.PersistentFlags().StringP("strone", "s", "one", "help message for flag strone") + echoCmd.PersistentFlags().BoolP("persistentbool", "p", false, "help message for flag persistentbool") + echoCmd.Flags().IntP("intone", "i", 123, "help message for flag intone") + echoCmd.Flags().BoolP("boolone", "b", true, "help message for flag boolone") + + timesCmd.PersistentFlags().StringP("strtwo", "t", "2", "help message for child flag strtwo") + timesCmd.Flags().IntP("inttwo", "j", 234, "help message for flag inttwo") + timesCmd.Flags().BoolP("booltwo", "c", false, "help message for flag booltwo") + + printCmd.PersistentFlags().StringP("strthree", "s", "three", "help message for flag strthree") + printCmd.Flags().IntP("intthree", "i", 345, "help message for flag intthree") + printCmd.Flags().BoolP("boolthree", "b", true, "help message for flag boolthree") + + echoCmd.AddCommand(timesCmd, echoSubCmd, deprecatedCmd) + rootCmd.AddCommand(printCmd, echoCmd) +} + +var rootCmd = &cobra.Command{ + Use: "root", + Short: "Root short description", + Long: "Root long description", + Run: emptyRun, +} + +var echoCmd = &cobra.Command{ + Use: "echo [string to echo]", + Aliases: []string{"say"}, + Short: "Echo anything to the screen", + Long: "an utterly useless command for testing", + Example: "Just run cobra-test echo", +} + +var echoSubCmd = &cobra.Command{ + Use: "echosub [string to print]", + Short: "second sub command for echo", + Long: "an absolutely utterly useless command for testing gendocs!.", + Run: emptyRun, +} + +var timesCmd = &cobra.Command{ + Use: "times [# times] [string to echo]", + SuggestFor: []string{"counts"}, + Short: "Echo anything to the screen more times", + Long: `a slightly useless command for testing.`, + Run: emptyRun, +} + +var deprecatedCmd = &cobra.Command{ + Use: "deprecated [can't do anything here]", + Short: "A command which is deprecated", + Long: `an absolutely utterly useless command for testing deprecation!.`, + Deprecated: "Please use echo instead", +} + +var printCmd = &cobra.Command{ + Use: "print [string to print]", + Short: "Print anything to the screen", + Long: `an absolutely utterly useless command for testing.`, +} + +func checkStringContains(t *testing.T, got, expected string) { + if !strings.Contains(got, expected) { + t.Errorf("Expected to contain: \n %v\nGot:\n %v\n", expected, got) + } +} + +func checkStringOmits(t *testing.T, got, expected string) { + if strings.Contains(got, expected) { + t.Errorf("Expected to not contain: \n %v\nGot: %v", expected, got) + } +} diff --git a/vendor/github.com/spf13/cobra/doc/man_docs.go b/vendor/github.com/spf13/cobra/doc/man_docs.go new file mode 100644 index 00000000..ce92332d --- /dev/null +++ b/vendor/github.com/spf13/cobra/doc/man_docs.go @@ -0,0 +1,236 @@ +// Copyright 2015 Red Hat Inc. All rights reserved. +// +// 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 doc + +import ( + "bytes" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/cpuguy83/go-md2man/md2man" + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +// GenManTree will generate a man page for this command and all descendants +// in the directory given. The header may be nil. This function may not work +// correctly if your command names have `-` in them. If you have `cmd` with two +// subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third` +// it is undefined which help output will be in the file `cmd-sub-third.1`. +func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error { + return GenManTreeFromOpts(cmd, GenManTreeOptions{ + Header: header, + Path: dir, + CommandSeparator: "-", + }) +} + +// GenManTreeFromOpts generates a man page for the command and all descendants. +// The pages are written to the opts.Path directory. +func GenManTreeFromOpts(cmd *cobra.Command, opts GenManTreeOptions) error { + header := opts.Header + if header == nil { + header = &GenManHeader{} + } + for _, c := range cmd.Commands() { + if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() { + continue + } + if err := GenManTreeFromOpts(c, opts); err != nil { + return err + } + } + section := "1" + if header.Section != "" { + section = header.Section + } + + separator := "_" + if opts.CommandSeparator != "" { + separator = opts.CommandSeparator + } + basename := strings.Replace(cmd.CommandPath(), " ", separator, -1) + filename := filepath.Join(opts.Path, basename+"."+section) + f, err := os.Create(filename) + if err != nil { + return err + } + defer f.Close() + + headerCopy := *header + 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 + CommandSeparator string +} + +// GenManHeader is a lot like the .TH header at the start of man pages. These +// include the title, section, date, source, and manual. We will use the +// current time if Date if unset and will use "Auto generated by spf13/cobra" +// if the Source is unset. +type GenManHeader struct { + Title string + Section string + Date *time.Time + date string + Source string + Manual string +} + +// GenMan will generate a man page for the given command and write it to +// w. The header argument may be nil, however obviously w may not. +func GenMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error { + if header == nil { + header = &GenManHeader{} + } + fillHeader(header, cmd.CommandPath()) + + b := genMan(cmd, header) + _, err := w.Write(md2man.Render(b)) + return err +} + +func fillHeader(header *GenManHeader, name string) { + if header.Title == "" { + header.Title = strings.ToUpper(strings.Replace(name, " ", "\\-", -1)) + } + if header.Section == "" { + header.Section = "1" + } + if header.Date == nil { + now := time.Now() + header.Date = &now + } + header.date = (*header.Date).Format("Jan 2006") + if header.Source == "" { + header.Source = "Auto generated by spf13/cobra" + } +} + +func manPreamble(buf *bytes.Buffer, header *GenManHeader, cmd *cobra.Command, dashedName string) { + description := cmd.Long + if len(description) == 0 { + description = cmd.Short + } + + buf.WriteString(fmt.Sprintf(`%% %s(%s)%s +%% %s +%% %s +# NAME +`, header.Title, header.Section, header.date, header.Source, header.Manual)) + buf.WriteString(fmt.Sprintf("%s \\- %s\n\n", dashedName, cmd.Short)) + buf.WriteString("# SYNOPSIS\n") + buf.WriteString(fmt.Sprintf("**%s**\n\n", cmd.UseLine())) + buf.WriteString("# DESCRIPTION\n") + buf.WriteString(description + "\n\n") +} + +func manPrintFlags(buf *bytes.Buffer, flags *pflag.FlagSet) { + flags.VisitAll(func(flag *pflag.Flag) { + if len(flag.Deprecated) > 0 || flag.Hidden { + return + } + format := "" + if len(flag.Shorthand) > 0 && len(flag.ShorthandDeprecated) == 0 { + format = fmt.Sprintf("**-%s**, **--%s**", flag.Shorthand, flag.Name) + } else { + format = fmt.Sprintf("**--%s**", flag.Name) + } + if len(flag.NoOptDefVal) > 0 { + format += "[" + } + if flag.Value.Type() == "string" { + // put quotes on the value + format += "=%q" + } else { + format += "=%s" + } + if len(flag.NoOptDefVal) > 0 { + format += "]" + } + format += "\n\t%s\n\n" + buf.WriteString(fmt.Sprintf(format, flag.DefValue, flag.Usage)) + }) +} + +func manPrintOptions(buf *bytes.Buffer, command *cobra.Command) { + flags := command.NonInheritedFlags() + if flags.HasFlags() { + buf.WriteString("# OPTIONS\n") + manPrintFlags(buf, flags) + buf.WriteString("\n") + } + flags = command.InheritedFlags() + if flags.HasFlags() { + buf.WriteString("# OPTIONS INHERITED FROM PARENT COMMANDS\n") + manPrintFlags(buf, flags) + buf.WriteString("\n") + } +} + +func genMan(cmd *cobra.Command, header *GenManHeader) []byte { + cmd.InitDefaultHelpCmd() + cmd.InitDefaultHelpFlag() + + // something like `rootcmd-subcmd1-subcmd2` + dashCommandName := strings.Replace(cmd.CommandPath(), " ", "-", -1) + + buf := new(bytes.Buffer) + + manPreamble(buf, header, cmd, dashCommandName) + manPrintOptions(buf, cmd) + if len(cmd.Example) > 0 { + buf.WriteString("# EXAMPLE\n") + buf.WriteString(fmt.Sprintf("```\n%s\n```\n", cmd.Example)) + } + if hasSeeAlso(cmd) { + buf.WriteString("# SEE ALSO\n") + seealsos := make([]string, 0) + if cmd.HasParent() { + parentPath := cmd.Parent().CommandPath() + dashParentPath := strings.Replace(parentPath, " ", "-", -1) + seealso := fmt.Sprintf("**%s(%s)**", dashParentPath, header.Section) + seealsos = append(seealsos, seealso) + cmd.VisitParents(func(c *cobra.Command) { + if c.DisableAutoGenTag { + cmd.DisableAutoGenTag = c.DisableAutoGenTag + } + }) + } + children := cmd.Commands() + sort.Sort(byName(children)) + for _, c := range children { + if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() { + continue + } + seealso := fmt.Sprintf("**%s-%s(%s)**", dashCommandName, c.Name(), header.Section) + seealsos = append(seealsos, seealso) + } + buf.WriteString(strings.Join(seealsos, ", ") + "\n") + } + if !cmd.DisableAutoGenTag { + buf.WriteString(fmt.Sprintf("# HISTORY\n%s Auto generated by spf13/cobra\n", header.Date.Format("2-Jan-2006"))) + } + return buf.Bytes() +} diff --git a/vendor/github.com/spf13/cobra/doc/man_docs.md b/vendor/github.com/spf13/cobra/doc/man_docs.md new file mode 100644 index 00000000..3709160f --- /dev/null +++ b/vendor/github.com/spf13/cobra/doc/man_docs.md @@ -0,0 +1,31 @@ +# Generating Man Pages For Your Own cobra.Command + +Generating man pages from a cobra command is incredibly easy. An example is as follows: + +```go +package main + +import ( + "log" + + "github.com/spf13/cobra" + "github.com/spf13/cobra/doc" +) + +func main() { + cmd := &cobra.Command{ + Use: "test", + Short: "my test program", + } + header := &doc.GenManHeader{ + Title: "MINE", + Section: "3", + } + err := doc.GenManTree(cmd, header, "/tmp") + if err != nil { + log.Fatal(err) + } +} +``` + +That will get you a man page `/tmp/test.3` diff --git a/vendor/github.com/spf13/cobra/doc/man_docs_test.go b/vendor/github.com/spf13/cobra/doc/man_docs_test.go new file mode 100644 index 00000000..62f85e47 --- /dev/null +++ b/vendor/github.com/spf13/cobra/doc/man_docs_test.go @@ -0,0 +1,177 @@ +package doc + +import ( + "bufio" + "bytes" + "fmt" + "io/ioutil" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/spf13/cobra" +) + +func translate(in string) string { + return strings.Replace(in, "-", "\\-", -1) +} + +func TestGenManDoc(t *testing.T) { + header := &GenManHeader{ + Title: "Project", + Section: "2", + } + + // We generate on a subcommand so we have both subcommands and parents + buf := new(bytes.Buffer) + if err := GenMan(echoCmd, header, buf); err != nil { + t.Fatal(err) + } + output := buf.String() + + // Make sure parent has - in CommandPath() in SEE ALSO: + parentPath := echoCmd.Parent().CommandPath() + dashParentPath := strings.Replace(parentPath, " ", "-", -1) + expected := translate(dashParentPath) + expected = expected + "(" + header.Section + ")" + checkStringContains(t, output, expected) + + checkStringContains(t, output, translate(echoCmd.Name())) + checkStringContains(t, output, translate(echoCmd.Name())) + checkStringContains(t, output, "boolone") + checkStringContains(t, output, "rootflag") + checkStringContains(t, output, translate(rootCmd.Name())) + checkStringContains(t, output, translate(echoSubCmd.Name())) + checkStringOmits(t, output, translate(deprecatedCmd.Name())) + checkStringContains(t, output, translate("Auto generated")) +} + +func TestGenManNoGenTag(t *testing.T) { + echoCmd.DisableAutoGenTag = true + defer func() { echoCmd.DisableAutoGenTag = false }() + + header := &GenManHeader{ + Title: "Project", + Section: "2", + } + + // We generate on a subcommand so we have both subcommands and parents + buf := new(bytes.Buffer) + if err := GenMan(echoCmd, header, buf); err != nil { + t.Fatal(err) + } + output := buf.String() + + unexpected := translate("#HISTORY") + checkStringOmits(t, output, unexpected) +} + +func TestGenManSeeAlso(t *testing.T) { + rootCmd := &cobra.Command{Use: "root", Run: emptyRun} + aCmd := &cobra.Command{Use: "aaa", Run: emptyRun, Hidden: true} // #229 + bCmd := &cobra.Command{Use: "bbb", Run: emptyRun} + cCmd := &cobra.Command{Use: "ccc", Run: emptyRun} + rootCmd.AddCommand(aCmd, bCmd, cCmd) + + buf := new(bytes.Buffer) + header := &GenManHeader{} + if err := GenMan(rootCmd, header, buf); err != nil { + t.Fatal(err) + } + scanner := bufio.NewScanner(buf) + + if err := assertLineFound(scanner, ".SH SEE ALSO"); err != nil { + t.Fatalf("Couldn't find SEE ALSO section header: %v", err) + } + if err := assertNextLineEquals(scanner, ".PP"); err != nil { + t.Fatalf("First line after SEE ALSO wasn't break-indent: %v", err) + } + if err := assertNextLineEquals(scanner, `\fBroot\-bbb(1)\fP, \fBroot\-ccc(1)\fP`); err != nil { + t.Fatalf("Second line after SEE ALSO wasn't correct: %v", err) + } +} + +func TestManPrintFlagsHidesShortDeperecated(t *testing.T) { + c := &cobra.Command{} + c.Flags().StringP("foo", "f", "default", "Foo flag") + c.Flags().MarkShorthandDeprecated("foo", "don't use it no more") + + buf := new(bytes.Buffer) + manPrintFlags(buf, c.Flags()) + + got := buf.String() + expected := "**--foo**=\"default\"\n\tFoo flag\n\n" + if got != expected { + t.Errorf("Expected %v, got %v", expected, got) + } +} + +func TestGenManTree(t *testing.T) { + c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"} + header := &GenManHeader{Section: "2"} + tmpdir, err := ioutil.TempDir("", "test-gen-man-tree") + if err != nil { + t.Fatalf("Failed to create tmpdir: %s", err.Error()) + } + defer os.RemoveAll(tmpdir) + + if err := GenManTree(c, header, tmpdir); err != nil { + t.Fatalf("GenManTree failed: %s", err.Error()) + } + + if _, err := os.Stat(filepath.Join(tmpdir, "do.2")); err != nil { + t.Fatalf("Expected file 'do.2' to exist") + } + + if header.Title != "" { + t.Fatalf("Expected header.Title to be unmodified") + } +} + +func assertLineFound(scanner *bufio.Scanner, expectedLine string) error { + for scanner.Scan() { + line := scanner.Text() + if line == expectedLine { + return nil + } + } + + if err := scanner.Err(); err != nil { + return fmt.Errorf("scan failed: %s", err) + } + + return fmt.Errorf("hit EOF before finding %v", expectedLine) +} + +func assertNextLineEquals(scanner *bufio.Scanner, expectedLine string) error { + if scanner.Scan() { + line := scanner.Text() + if line == expectedLine { + return nil + } + return fmt.Errorf("got %v, not %v", line, expectedLine) + } + + if err := scanner.Err(); err != nil { + return fmt.Errorf("scan failed: %v", err) + } + + return fmt.Errorf("hit EOF before finding %v", expectedLine) +} + +func BenchmarkGenManToFile(b *testing.B) { + file, err := ioutil.TempFile("", "") + if err != nil { + b.Fatal(err) + } + defer os.Remove(file.Name()) + defer file.Close() + + b.ResetTimer() + for i := 0; i < b.N; i++ { + if err := GenMan(rootCmd, nil, file); err != nil { + b.Fatal(err) + } + } +} diff --git a/vendor/github.com/spf13/cobra/doc/man_examples_test.go b/vendor/github.com/spf13/cobra/doc/man_examples_test.go new file mode 100644 index 00000000..db660426 --- /dev/null +++ b/vendor/github.com/spf13/cobra/doc/man_examples_test.go @@ -0,0 +1,35 @@ +package doc_test + +import ( + "bytes" + "fmt" + + "github.com/spf13/cobra" + "github.com/spf13/cobra/doc" +) + +func ExampleGenManTree() { + cmd := &cobra.Command{ + Use: "test", + Short: "my test program", + } + header := &doc.GenManHeader{ + Title: "MINE", + Section: "3", + } + doc.GenManTree(cmd, header, "/tmp") +} + +func ExampleGenMan() { + cmd := &cobra.Command{ + Use: "test", + Short: "my test program", + } + header := &doc.GenManHeader{ + Title: "MINE", + Section: "3", + } + out := new(bytes.Buffer) + doc.GenMan(cmd, header, out) + fmt.Print(out.String()) +} diff --git a/vendor/github.com/spf13/cobra/doc/md_docs.go b/vendor/github.com/spf13/cobra/doc/md_docs.go new file mode 100644 index 00000000..d7a2c2b6 --- /dev/null +++ b/vendor/github.com/spf13/cobra/doc/md_docs.go @@ -0,0 +1,159 @@ +//Copyright 2015 Red Hat Inc. All rights reserved. +// +// 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 doc + +import ( + "bytes" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/spf13/cobra" +) + +func printOptions(buf *bytes.Buffer, cmd *cobra.Command, name string) error { + flags := cmd.NonInheritedFlags() + flags.SetOutput(buf) + if flags.HasFlags() { + buf.WriteString("### Options\n\n```\n") + flags.PrintDefaults() + buf.WriteString("```\n\n") + } + + parentFlags := cmd.InheritedFlags() + parentFlags.SetOutput(buf) + if parentFlags.HasFlags() { + buf.WriteString("### Options inherited from parent commands\n\n```\n") + parentFlags.PrintDefaults() + buf.WriteString("```\n\n") + } + return nil +} + +// GenMarkdown creates markdown output. +func GenMarkdown(cmd *cobra.Command, w io.Writer) error { + return GenMarkdownCustom(cmd, w, func(s string) string { return s }) +} + +// GenMarkdownCustom creates custom markdown output. +func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error { + cmd.InitDefaultHelpCmd() + cmd.InitDefaultHelpFlag() + + buf := new(bytes.Buffer) + name := cmd.CommandPath() + + short := cmd.Short + long := cmd.Long + if len(long) == 0 { + long = short + } + + buf.WriteString("## " + name + "\n\n") + buf.WriteString(short + "\n\n") + buf.WriteString("### Synopsis\n\n") + buf.WriteString(long + "\n\n") + + if cmd.Runnable() { + buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.UseLine())) + } + + if len(cmd.Example) > 0 { + buf.WriteString("### Examples\n\n") + buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.Example)) + } + + if err := printOptions(buf, cmd, name); err != nil { + return err + } + if hasSeeAlso(cmd) { + buf.WriteString("### SEE ALSO\n\n") + if cmd.HasParent() { + parent := cmd.Parent() + pname := parent.CommandPath() + link := pname + ".md" + link = strings.Replace(link, " ", "_", -1) + buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short)) + cmd.VisitParents(func(c *cobra.Command) { + if c.DisableAutoGenTag { + cmd.DisableAutoGenTag = c.DisableAutoGenTag + } + }) + } + + children := cmd.Commands() + sort.Sort(byName(children)) + + for _, child := range children { + if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() { + continue + } + cname := name + " " + child.Name() + link := cname + ".md" + link = strings.Replace(link, " ", "_", -1) + buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short)) + } + buf.WriteString("\n") + } + if !cmd.DisableAutoGenTag { + buf.WriteString("###### Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "\n") + } + _, err := buf.WriteTo(w) + return err +} + +// GenMarkdownTree will generate a markdown page for this command and all +// descendants in the directory given. The header may be nil. +// This function may not work correctly if your command names have `-` in them. +// If you have `cmd` with two subcmds, `sub` and `sub-third`, +// and `sub` has a subcommand called `third`, it is undefined which +// help output will be in the file `cmd-sub-third.1`. +func GenMarkdownTree(cmd *cobra.Command, dir string) error { + identity := func(s string) string { return s } + emptyStr := func(s string) string { return "" } + 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() { + continue + } + if err := GenMarkdownTreeCustom(c, dir, filePrepender, linkHandler); err != nil { + return err + } + } + + basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".md" + filename := filepath.Join(dir, basename) + f, err := os.Create(filename) + if err != nil { + return err + } + defer f.Close() + + if _, err := io.WriteString(f, filePrepender(filename)); err != nil { + return err + } + if err := GenMarkdownCustom(cmd, f, linkHandler); err != nil { + return err + } + return nil +} diff --git a/vendor/github.com/spf13/cobra/md_docs.md b/vendor/github.com/spf13/cobra/doc/md_docs.md similarity index 69% rename from vendor/github.com/spf13/cobra/md_docs.md rename to vendor/github.com/spf13/cobra/doc/md_docs.md index 3a0d55ab..56ce9fe8 100644 --- a/vendor/github.com/spf13/cobra/md_docs.md +++ b/vendor/github.com/spf13/cobra/doc/md_docs.md @@ -1,5 +1,31 @@ # Generating Markdown Docs For Your Own cobra.Command +Generating man pages from a cobra command is incredibly easy. An example is as follows: + +```go +package main + +import ( + "log" + + "github.com/spf13/cobra" + "github.com/spf13/cobra/doc" +) + +func main() { + cmd := &cobra.Command{ + Use: "test", + Short: "my test program", + } + err := doc.GenMarkdownTree(cmd, "/tmp") + if err != nil { + log.Fatal(err) + } +} +``` + +That will get you a Markdown document `/tmp/test.md` + ## Generate markdown docs for the entire command tree This program can actually generate docs for the kubectl command in the kubernetes project @@ -8,16 +34,22 @@ This program can actually generate docs for the kubectl command in the kubernete package main import ( + "log" "io/ioutil" "os" - "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd" - "github.com/spf13/cobra" + "k8s.io/kubernetes/pkg/kubectl/cmd" + cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" + + "github.com/spf13/cobra/doc" ) func main() { - kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard) - cobra.GenMarkdownTree(kubectl, "./") + kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard) + err := doc.GenMarkdownTree(kubectl, "./") + if err != nil { + log.Fatal(err) + } } ``` @@ -29,7 +61,10 @@ You may wish to have more control over the output, or only generate for a single ```go out := new(bytes.Buffer) - cobra.GenMarkdown(cmd, out) + err := doc.GenMarkdown(cmd, out) + if err != nil { + log.Fatal(err) + } ``` This will write the markdown doc for ONLY "cmd" into the out, buffer. @@ -39,14 +74,14 @@ This will write the markdown doc for ONLY "cmd" into the out, buffer. Both `GenMarkdown` and `GenMarkdownTree` have alternate versions with callbacks to get some control of the output: ```go -func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string) string) { - //... +func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error { + //... } ``` ```go -func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) { - //... +func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error { + //... } ``` @@ -78,4 +113,3 @@ linkHandler := func(name string) string { return "/commands/" + strings.ToLower(base) + "/" } ``` - diff --git a/vendor/github.com/spf13/cobra/doc/md_docs_test.go b/vendor/github.com/spf13/cobra/doc/md_docs_test.go new file mode 100644 index 00000000..b0fa68c0 --- /dev/null +++ b/vendor/github.com/spf13/cobra/doc/md_docs_test.go @@ -0,0 +1,74 @@ +package doc + +import ( + "bytes" + "io/ioutil" + "os" + "path/filepath" + "testing" + + "github.com/spf13/cobra" +) + +func TestGenMdDoc(t *testing.T) { + // We generate on subcommand so we have both subcommands and parents. + buf := new(bytes.Buffer) + if err := GenMarkdown(echoCmd, buf); err != nil { + t.Fatal(err) + } + output := buf.String() + + checkStringContains(t, output, echoCmd.Long) + checkStringContains(t, output, echoCmd.Example) + checkStringContains(t, output, "boolone") + checkStringContains(t, output, "rootflag") + checkStringContains(t, output, rootCmd.Short) + checkStringContains(t, output, echoSubCmd.Short) + checkStringOmits(t, output, deprecatedCmd.Short) +} + +func TestGenMdNoTag(t *testing.T) { + rootCmd.DisableAutoGenTag = true + defer func() { rootCmd.DisableAutoGenTag = false }() + + buf := new(bytes.Buffer) + if err := GenMarkdown(rootCmd, buf); err != nil { + t.Fatal(err) + } + output := buf.String() + + checkStringOmits(t, output, "Auto generated") +} + +func TestGenMdTree(t *testing.T) { + c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"} + tmpdir, err := ioutil.TempDir("", "test-gen-md-tree") + if err != nil { + t.Fatalf("Failed to create tmpdir: %v", err) + } + defer os.RemoveAll(tmpdir) + + if err := GenMarkdownTree(c, tmpdir); err != nil { + t.Fatalf("GenMarkdownTree failed: %v", err) + } + + if _, err := os.Stat(filepath.Join(tmpdir, "do.md")); err != nil { + t.Fatalf("Expected file 'do.md' to exist") + } +} + +func BenchmarkGenMarkdownToFile(b *testing.B) { + file, err := ioutil.TempFile("", "") + if err != nil { + b.Fatal(err) + } + defer os.Remove(file.Name()) + defer file.Close() + + b.ResetTimer() + for i := 0; i < b.N; i++ { + if err := GenMarkdown(rootCmd, file); err != nil { + b.Fatal(err) + } + } +} diff --git a/vendor/github.com/spf13/cobra/doc/rest_docs.go b/vendor/github.com/spf13/cobra/doc/rest_docs.go new file mode 100644 index 00000000..4913e3ee --- /dev/null +++ b/vendor/github.com/spf13/cobra/doc/rest_docs.go @@ -0,0 +1,185 @@ +//Copyright 2015 Red Hat Inc. All rights reserved. +// +// 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 doc + +import ( + "bytes" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/spf13/cobra" +) + +func printOptionsReST(buf *bytes.Buffer, cmd *cobra.Command, name string) error { + flags := cmd.NonInheritedFlags() + flags.SetOutput(buf) + if flags.HasFlags() { + buf.WriteString("Options\n") + buf.WriteString("~~~~~~~\n\n::\n\n") + flags.PrintDefaults() + buf.WriteString("\n") + } + + parentFlags := cmd.InheritedFlags() + parentFlags.SetOutput(buf) + if parentFlags.HasFlags() { + buf.WriteString("Options inherited from parent commands\n") + buf.WriteString("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n::\n\n") + parentFlags.PrintDefaults() + buf.WriteString("\n") + } + return nil +} + +// linkHandler for default ReST hyperlink markup +func defaultLinkHandler(name, ref string) string { + return fmt.Sprintf("`%s <%s.rst>`_", name, ref) +} + +// GenReST creates reStructured Text output. +func GenReST(cmd *cobra.Command, w io.Writer) error { + return GenReSTCustom(cmd, w, defaultLinkHandler) +} + +// GenReSTCustom creates custom reStructured Text output. +func GenReSTCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string, string) string) error { + cmd.InitDefaultHelpCmd() + cmd.InitDefaultHelpFlag() + + buf := new(bytes.Buffer) + name := cmd.CommandPath() + + short := cmd.Short + long := cmd.Long + if len(long) == 0 { + long = short + } + ref := strings.Replace(name, " ", "_", -1) + + buf.WriteString(".. _" + ref + ":\n\n") + buf.WriteString(name + "\n") + buf.WriteString(strings.Repeat("-", len(name)) + "\n\n") + buf.WriteString(short + "\n\n") + buf.WriteString("Synopsis\n") + buf.WriteString("~~~~~~~~\n\n") + buf.WriteString("\n" + long + "\n\n") + + if cmd.Runnable() { + buf.WriteString(fmt.Sprintf("::\n\n %s\n\n", cmd.UseLine())) + } + + if len(cmd.Example) > 0 { + buf.WriteString("Examples\n") + buf.WriteString("~~~~~~~~\n\n") + buf.WriteString(fmt.Sprintf("::\n\n%s\n\n", indentString(cmd.Example, " "))) + } + + if err := printOptionsReST(buf, cmd, name); err != nil { + return err + } + if hasSeeAlso(cmd) { + buf.WriteString("SEE ALSO\n") + buf.WriteString("~~~~~~~~\n\n") + if cmd.HasParent() { + parent := cmd.Parent() + pname := parent.CommandPath() + ref = strings.Replace(pname, " ", "_", -1) + buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(pname, ref), parent.Short)) + cmd.VisitParents(func(c *cobra.Command) { + if c.DisableAutoGenTag { + cmd.DisableAutoGenTag = c.DisableAutoGenTag + } + }) + } + + children := cmd.Commands() + sort.Sort(byName(children)) + + for _, child := range children { + if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() { + continue + } + cname := name + " " + child.Name() + ref = strings.Replace(cname, " ", "_", -1) + buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(cname, ref), child.Short)) + } + buf.WriteString("\n") + } + if !cmd.DisableAutoGenTag { + buf.WriteString("*Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "*\n") + } + _, err := buf.WriteTo(w) + return err +} + +// GenReSTTree will generate a ReST page for this command and all +// descendants in the directory given. +// This function may not work correctly if your command names have `-` in them. +// If you have `cmd` with two subcmds, `sub` and `sub-third`, +// and `sub` has a subcommand called `third`, it is undefined which +// help output will be in the file `cmd-sub-third.1`. +func GenReSTTree(cmd *cobra.Command, dir string) error { + emptyStr := func(s string) string { return "" } + return GenReSTTreeCustom(cmd, dir, emptyStr, defaultLinkHandler) +} + +// GenReSTTreeCustom is the the same as GenReSTTree, but +// with custom filePrepender and linkHandler. +func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error { + for _, c := range cmd.Commands() { + if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() { + continue + } + if err := GenReSTTreeCustom(c, dir, filePrepender, linkHandler); err != nil { + return err + } + } + + basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".rst" + filename := filepath.Join(dir, basename) + f, err := os.Create(filename) + if err != nil { + return err + } + defer f.Close() + + if _, err := io.WriteString(f, filePrepender(filename)); err != nil { + return err + } + if err := GenReSTCustom(cmd, f, linkHandler); err != nil { + return err + } + return nil +} + +// adapted from: https://github.com/kr/text/blob/main/indent.go +func indentString(s, p string) string { + var res []byte + b := []byte(s) + prefix := []byte(p) + bol := true + for _, c := range b { + if bol && c != '\n' { + res = append(res, prefix...) + } + res = append(res, c) + bol = c == '\n' + } + return string(res) +} diff --git a/vendor/github.com/spf13/cobra/doc/rest_docs.md b/vendor/github.com/spf13/cobra/doc/rest_docs.md new file mode 100644 index 00000000..6098430e --- /dev/null +++ b/vendor/github.com/spf13/cobra/doc/rest_docs.md @@ -0,0 +1,114 @@ +# Generating ReStructured Text Docs For Your Own cobra.Command + +Generating ReST pages from a cobra command is incredibly easy. An example is as follows: + +```go +package main + +import ( + "log" + + "github.com/spf13/cobra" + "github.com/spf13/cobra/doc" +) + +func main() { + cmd := &cobra.Command{ + Use: "test", + Short: "my test program", + } + err := doc.GenReSTTree(cmd, "/tmp") + if err != nil { + log.Fatal(err) + } +} +``` + +That will get you a ReST document `/tmp/test.rst` + +## Generate ReST docs for the entire command tree + +This program can actually generate docs for the kubectl command in the kubernetes project + +```go +package main + +import ( + "log" + "io/ioutil" + "os" + + "k8s.io/kubernetes/pkg/kubectl/cmd" + cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" + + "github.com/spf13/cobra/doc" +) + +func main() { + kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard) + err := doc.GenReSTTree(kubectl, "./") + if err != nil { + log.Fatal(err) + } +} +``` + +This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./") + +## Generate ReST docs for a single command + +You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenReST` instead of `GenReSTTree` + +```go + out := new(bytes.Buffer) + err := doc.GenReST(cmd, out) + if err != nil { + log.Fatal(err) + } +``` + +This will write the ReST doc for ONLY "cmd" into the out, buffer. + +## Customize the output + +Both `GenReST` and `GenReSTTree` have alternate versions with callbacks to get some control of the output: + +```go +func GenReSTTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error { + //... +} +``` + +```go +func GenReSTCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string, string) string) error { + //... +} +``` + +The `filePrepender` will prepend the return value given the full filepath to the rendered ReST file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/): + +```go +const fmTemplate = `--- +date: %s +title: "%s" +slug: %s +url: %s +--- +` +filePrepender := func(filename string) string { + now := time.Now().Format(time.RFC3339) + name := filepath.Base(filename) + base := strings.TrimSuffix(name, path.Ext(name)) + url := "/commands/" + strings.ToLower(base) + "/" + return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url) +} +``` + +The `linkHandler` can be used to customize the rendered links to the commands, given a command name and reference. This is useful while converting rst to html or while generating documentation with tools like Sphinx where `:ref:` is used: + +```go +// Sphinx cross-referencing format +linkHandler := func(name, ref string) string { + return fmt.Sprintf(":ref:`%s <%s>`", name, ref) +} +``` diff --git a/vendor/github.com/spf13/cobra/doc/rest_docs_test.go b/vendor/github.com/spf13/cobra/doc/rest_docs_test.go new file mode 100644 index 00000000..aa3186e8 --- /dev/null +++ b/vendor/github.com/spf13/cobra/doc/rest_docs_test.go @@ -0,0 +1,76 @@ +package doc + +import ( + "bytes" + "io/ioutil" + "os" + "path/filepath" + "testing" + + "github.com/spf13/cobra" +) + +func TestGenRSTDoc(t *testing.T) { + // We generate on a subcommand so we have both subcommands and parents + buf := new(bytes.Buffer) + if err := GenReST(echoCmd, buf); err != nil { + t.Fatal(err) + } + output := buf.String() + + checkStringContains(t, output, echoCmd.Long) + checkStringContains(t, output, echoCmd.Example) + checkStringContains(t, output, "boolone") + checkStringContains(t, output, "rootflag") + checkStringContains(t, output, rootCmd.Short) + checkStringContains(t, output, echoSubCmd.Short) + checkStringOmits(t, output, deprecatedCmd.Short) +} + +func TestGenRSTNoTag(t *testing.T) { + rootCmd.DisableAutoGenTag = true + defer func() { rootCmd.DisableAutoGenTag = false }() + + buf := new(bytes.Buffer) + if err := GenReST(rootCmd, buf); err != nil { + t.Fatal(err) + } + output := buf.String() + + unexpected := "Auto generated" + checkStringOmits(t, output, unexpected) +} + +func TestGenRSTTree(t *testing.T) { + c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"} + + tmpdir, err := ioutil.TempDir("", "test-gen-rst-tree") + if err != nil { + t.Fatalf("Failed to create tmpdir: %s", err.Error()) + } + defer os.RemoveAll(tmpdir) + + if err := GenReSTTree(c, tmpdir); err != nil { + t.Fatalf("GenReSTTree failed: %s", err.Error()) + } + + if _, err := os.Stat(filepath.Join(tmpdir, "do.rst")); err != nil { + t.Fatalf("Expected file 'do.rst' to exist") + } +} + +func BenchmarkGenReSTToFile(b *testing.B) { + file, err := ioutil.TempFile("", "") + if err != nil { + b.Fatal(err) + } + defer os.Remove(file.Name()) + defer file.Close() + + b.ResetTimer() + for i := 0; i < b.N; i++ { + if err := GenReST(rootCmd, file); err != nil { + b.Fatal(err) + } + } +} diff --git a/vendor/github.com/spf13/cobra/doc/util.go b/vendor/github.com/spf13/cobra/doc/util.go new file mode 100644 index 00000000..8d3dbece --- /dev/null +++ b/vendor/github.com/spf13/cobra/doc/util.go @@ -0,0 +1,51 @@ +// Copyright 2015 Red Hat Inc. All rights reserved. +// +// 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 doc + +import ( + "strings" + + "github.com/spf13/cobra" +) + +// Test to see if we have a reason to print See Also information in docs +// Basically this is a test for a parent commend or a subcommand which is +// both not deprecated and not the autogenerated help command. +func hasSeeAlso(cmd *cobra.Command) bool { + if cmd.HasParent() { + return true + } + for _, c := range cmd.Commands() { + if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() { + continue + } + return true + } + return false +} + +// Temporary workaround for yaml lib generating incorrect yaml with long strings +// that do not contain \n. +func forceMultiLine(s string) string { + if len(s) > 60 && !strings.Contains(s, "\n") { + s = s + "\n" + } + return s +} + +type byName []*cobra.Command + +func (s byName) Len() int { return len(s) } +func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() } diff --git a/vendor/github.com/spf13/cobra/doc/yaml_docs.go b/vendor/github.com/spf13/cobra/doc/yaml_docs.go new file mode 100644 index 00000000..ea00af07 --- /dev/null +++ b/vendor/github.com/spf13/cobra/doc/yaml_docs.go @@ -0,0 +1,169 @@ +// Copyright 2016 French Ben. All rights reserved. +// +// 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 doc + +import ( + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + "gopkg.in/yaml.v2" +) + +type cmdOption struct { + Name string + Shorthand string `yaml:",omitempty"` + DefaultValue string `yaml:"default_value,omitempty"` + Usage string `yaml:",omitempty"` +} + +type cmdDoc struct { + Name string + Synopsis string `yaml:",omitempty"` + Description string `yaml:",omitempty"` + Options []cmdOption `yaml:",omitempty"` + InheritedOptions []cmdOption `yaml:"inherited_options,omitempty"` + Example string `yaml:",omitempty"` + SeeAlso []string `yaml:"see_also,omitempty"` +} + +// GenYamlTree creates yaml structured ref files for this command and all descendants +// in the directory given. This function may not work +// correctly if your command names have `-` in them. If you have `cmd` with two +// subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third` +// it is undefined which help output will be in the file `cmd-sub-third.1`. +func GenYamlTree(cmd *cobra.Command, dir string) error { + identity := func(s string) string { return s } + emptyStr := func(s string) string { return "" } + return GenYamlTreeCustom(cmd, dir, emptyStr, identity) +} + +// GenYamlTreeCustom creates yaml structured ref files. +func GenYamlTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error { + for _, c := range cmd.Commands() { + if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() { + continue + } + if err := GenYamlTreeCustom(c, dir, filePrepender, linkHandler); err != nil { + return err + } + } + + basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".yaml" + filename := filepath.Join(dir, basename) + f, err := os.Create(filename) + if err != nil { + return err + } + defer f.Close() + + if _, err := io.WriteString(f, filePrepender(filename)); err != nil { + return err + } + if err := GenYamlCustom(cmd, f, linkHandler); err != nil { + return err + } + return nil +} + +// GenYaml creates yaml output. +func GenYaml(cmd *cobra.Command, w io.Writer) error { + return GenYamlCustom(cmd, w, func(s string) string { return s }) +} + +// GenYamlCustom creates custom yaml output. +func GenYamlCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error { + cmd.InitDefaultHelpCmd() + cmd.InitDefaultHelpFlag() + + yamlDoc := cmdDoc{} + yamlDoc.Name = cmd.CommandPath() + + yamlDoc.Synopsis = forceMultiLine(cmd.Short) + yamlDoc.Description = forceMultiLine(cmd.Long) + + if len(cmd.Example) > 0 { + yamlDoc.Example = cmd.Example + } + + flags := cmd.NonInheritedFlags() + if flags.HasFlags() { + yamlDoc.Options = genFlagResult(flags) + } + flags = cmd.InheritedFlags() + if flags.HasFlags() { + yamlDoc.InheritedOptions = genFlagResult(flags) + } + + if hasSeeAlso(cmd) { + result := []string{} + if cmd.HasParent() { + parent := cmd.Parent() + result = append(result, parent.CommandPath()+" - "+parent.Short) + } + children := cmd.Commands() + sort.Sort(byName(children)) + for _, child := range children { + if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() { + continue + } + result = append(result, child.Name()+" - "+child.Short) + } + yamlDoc.SeeAlso = result + } + + final, err := yaml.Marshal(&yamlDoc) + if err != nil { + fmt.Println(err) + os.Exit(1) + } + + if _, err := w.Write(final); err != nil { + return err + } + return nil +} + +func genFlagResult(flags *pflag.FlagSet) []cmdOption { + var result []cmdOption + + flags.VisitAll(func(flag *pflag.Flag) { + // Todo, when we mark a shorthand is deprecated, but specify an empty message. + // The flag.ShorthandDeprecated is empty as the shorthand is deprecated. + // Using len(flag.ShorthandDeprecated) > 0 can't handle this, others are ok. + if !(len(flag.ShorthandDeprecated) > 0) && len(flag.Shorthand) > 0 { + opt := cmdOption{ + flag.Name, + flag.Shorthand, + flag.DefValue, + forceMultiLine(flag.Usage), + } + result = append(result, opt) + } else { + opt := cmdOption{ + Name: flag.Name, + DefaultValue: forceMultiLine(flag.DefValue), + Usage: forceMultiLine(flag.Usage), + } + result = append(result, opt) + } + }) + + return result +} diff --git a/vendor/github.com/spf13/cobra/doc/yaml_docs.md b/vendor/github.com/spf13/cobra/doc/yaml_docs.md new file mode 100644 index 00000000..1a9b7c6a --- /dev/null +++ b/vendor/github.com/spf13/cobra/doc/yaml_docs.md @@ -0,0 +1,112 @@ +# Generating Yaml Docs For Your Own cobra.Command + +Generating yaml files from a cobra command is incredibly easy. An example is as follows: + +```go +package main + +import ( + "log" + + "github.com/spf13/cobra" + "github.com/spf13/cobra/doc" +) + +func main() { + cmd := &cobra.Command{ + Use: "test", + Short: "my test program", + } + err := doc.GenYamlTree(cmd, "/tmp") + if err != nil { + log.Fatal(err) + } +} +``` + +That will get you a Yaml document `/tmp/test.yaml` + +## Generate yaml docs for the entire command tree + +This program can actually generate docs for the kubectl command in the kubernetes project + +```go +package main + +import ( + "io/ioutil" + "log" + "os" + + "k8s.io/kubernetes/pkg/kubectl/cmd" + cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" + + "github.com/spf13/cobra/doc" +) + +func main() { + kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard) + err := doc.GenYamlTree(kubectl, "./") + if err != nil { + log.Fatal(err) + } +} +``` + +This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./") + +## Generate yaml docs for a single command + +You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenYaml` instead of `GenYamlTree` + +```go + out := new(bytes.Buffer) + doc.GenYaml(cmd, out) +``` + +This will write the yaml doc for ONLY "cmd" into the out, buffer. + +## Customize the output + +Both `GenYaml` and `GenYamlTree` have alternate versions with callbacks to get some control of the output: + +```go +func GenYamlTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error { + //... +} +``` + +```go +func GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error { + //... +} +``` + +The `filePrepender` will prepend the return value given the full filepath to the rendered Yaml file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/): + +```go +const fmTemplate = `--- +date: %s +title: "%s" +slug: %s +url: %s +--- +` + +filePrepender := func(filename string) string { + now := time.Now().Format(time.RFC3339) + name := filepath.Base(filename) + base := strings.TrimSuffix(name, path.Ext(name)) + url := "/commands/" + strings.ToLower(base) + "/" + return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url) +} +``` + +The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename: + +```go +linkHandler := func(name string) string { + base := strings.TrimSuffix(name, path.Ext(name)) + return "/commands/" + strings.ToLower(base) + "/" +} +``` diff --git a/vendor/github.com/spf13/cobra/doc/yaml_docs_test.go b/vendor/github.com/spf13/cobra/doc/yaml_docs_test.go new file mode 100644 index 00000000..c5a63594 --- /dev/null +++ b/vendor/github.com/spf13/cobra/doc/yaml_docs_test.go @@ -0,0 +1,74 @@ +package doc + +import ( + "bytes" + "io/ioutil" + "os" + "path/filepath" + "testing" + + "github.com/spf13/cobra" +) + +func TestGenYamlDoc(t *testing.T) { + // We generate on s subcommand so we have both subcommands and parents + buf := new(bytes.Buffer) + if err := GenYaml(echoCmd, buf); err != nil { + t.Fatal(err) + } + output := buf.String() + + checkStringContains(t, output, echoCmd.Long) + checkStringContains(t, output, echoCmd.Example) + checkStringContains(t, output, "boolone") + checkStringContains(t, output, "rootflag") + checkStringContains(t, output, rootCmd.Short) + checkStringContains(t, output, echoSubCmd.Short) +} + +func TestGenYamlNoTag(t *testing.T) { + rootCmd.DisableAutoGenTag = true + defer func() { rootCmd.DisableAutoGenTag = false }() + + buf := new(bytes.Buffer) + if err := GenYaml(rootCmd, buf); err != nil { + t.Fatal(err) + } + output := buf.String() + + checkStringOmits(t, output, "Auto generated") +} + +func TestGenYamlTree(t *testing.T) { + c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"} + + tmpdir, err := ioutil.TempDir("", "test-gen-yaml-tree") + if err != nil { + t.Fatalf("Failed to create tmpdir: %s", err.Error()) + } + defer os.RemoveAll(tmpdir) + + if err := GenYamlTree(c, tmpdir); err != nil { + t.Fatalf("GenYamlTree failed: %s", err.Error()) + } + + if _, err := os.Stat(filepath.Join(tmpdir, "do.yaml")); err != nil { + t.Fatalf("Expected file 'do.yaml' to exist") + } +} + +func BenchmarkGenYamlToFile(b *testing.B) { + file, err := ioutil.TempFile("", "") + if err != nil { + b.Fatal(err) + } + defer os.Remove(file.Name()) + defer file.Close() + + b.ResetTimer() + for i := 0; i < b.N; i++ { + if err := GenYaml(rootCmd, file); err != nil { + b.Fatal(err) + } + } +} diff --git a/vendor/github.com/spf13/cobra/md_docs.go b/vendor/github.com/spf13/cobra/md_docs.go deleted file mode 100644 index 6092c85a..00000000 --- a/vendor/github.com/spf13/cobra/md_docs.go +++ /dev/null @@ -1,138 +0,0 @@ -//Copyright 2015 Red Hat Inc. All rights reserved. -// -// 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 cobra - -import ( - "bytes" - "fmt" - "os" - "sort" - "strings" - "time" -) - -func printOptions(out *bytes.Buffer, cmd *Command, name string) { - flags := cmd.NonInheritedFlags() - flags.SetOutput(out) - if flags.HasFlags() { - fmt.Fprintf(out, "### Options\n\n```\n") - flags.PrintDefaults() - fmt.Fprintf(out, "```\n\n") - } - - parentFlags := cmd.InheritedFlags() - parentFlags.SetOutput(out) - if parentFlags.HasFlags() { - fmt.Fprintf(out, "### Options inherited from parent commands\n\n```\n") - parentFlags.PrintDefaults() - fmt.Fprintf(out, "```\n\n") - } -} - -type byName []*Command - -func (s byName) Len() int { return len(s) } -func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() } - -func GenMarkdown(cmd *Command, out *bytes.Buffer) { - GenMarkdownCustom(cmd, out, func(s string) string { return s }) -} - -func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) { - name := cmd.CommandPath() - - short := cmd.Short - long := cmd.Long - if len(long) == 0 { - long = short - } - - fmt.Fprintf(out, "## %s\n\n", name) - fmt.Fprintf(out, "%s\n\n", short) - fmt.Fprintf(out, "### Synopsis\n\n") - fmt.Fprintf(out, "\n%s\n\n", long) - - if cmd.Runnable() { - fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.UseLine()) - } - - if len(cmd.Example) > 0 { - fmt.Fprintf(out, "### Examples\n\n") - fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.Example) - } - - printOptions(out, cmd, name) - - if len(cmd.Commands()) > 0 || cmd.HasParent() { - fmt.Fprintf(out, "### SEE ALSO\n") - if cmd.HasParent() { - parent := cmd.Parent() - pname := parent.CommandPath() - link := pname + ".md" - link = strings.Replace(link, " ", "_", -1) - fmt.Fprintf(out, "* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short) - } - - children := cmd.Commands() - sort.Sort(byName(children)) - - for _, child := range children { - if len(child.Deprecated) > 0 { - continue - } - cname := name + " " + child.Name() - link := cname + ".md" - link = strings.Replace(link, " ", "_", -1) - fmt.Fprintf(out, "* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short) - } - fmt.Fprintf(out, "\n") - } - - fmt.Fprintf(out, "###### Auto generated by spf13/cobra at %s\n", time.Now().UTC()) -} - -func GenMarkdownTree(cmd *Command, dir string) { - identity := func(s string) string { return s } - emptyStr := func(s string) string { return "" } - GenMarkdownTreeCustom(cmd, dir, emptyStr, identity) -} - -func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string) string) { - for _, c := range cmd.Commands() { - GenMarkdownTreeCustom(c, dir, filePrepender, linkHandler) - } - out := new(bytes.Buffer) - - GenMarkdownCustom(cmd, out, linkHandler) - - filename := cmd.CommandPath() - filename = dir + strings.Replace(filename, " ", "_", -1) + ".md" - outFile, err := os.Create(filename) - if err != nil { - fmt.Println(err) - os.Exit(1) - } - defer outFile.Close() - _, err = outFile.WriteString(filePrepender(filename)) - if err != nil { - fmt.Println(err) - os.Exit(1) - } - _, err = outFile.Write(out.Bytes()) - if err != nil { - fmt.Println(err) - os.Exit(1) - } -} diff --git a/vendor/github.com/spf13/cobra/md_docs_test.go b/vendor/github.com/spf13/cobra/md_docs_test.go deleted file mode 100644 index defc9411..00000000 --- a/vendor/github.com/spf13/cobra/md_docs_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "os" - "strings" - "testing" -) - -var _ = fmt.Println -var _ = os.Stderr - -func TestGenMdDoc(t *testing.T) { - c := initializeWithRootCmd() - // Need two commands to run the command alphabetical sort - cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated) - c.AddCommand(cmdPrint, cmdEcho) - cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp) - - out := new(bytes.Buffer) - - // We generate on s subcommand so we have both subcommands and parents - GenMarkdown(cmdEcho, out) - found := out.String() - - // Our description - expected := cmdEcho.Long - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } - - // Better have our example - expected = cmdEcho.Example - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } - - // A local flag - expected = "boolone" - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } - - // persistent flag on parent - expected = "rootflag" - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } - - // We better output info about our parent - expected = cmdRootWithRun.Short - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } - - // And about subcommands - expected = cmdEchoSub.Short - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } - - unexpected := cmdDeprecated.Short - if strings.Contains(found, unexpected) { - t.Errorf("Unexpected response.\nFound: %v\nBut should not have!!\n", unexpected) - } -} diff --git a/vendor/github.com/spf13/cobra/zsh_completions.go b/vendor/github.com/spf13/cobra/zsh_completions.go new file mode 100644 index 00000000..889c22e2 --- /dev/null +++ b/vendor/github.com/spf13/cobra/zsh_completions.go @@ -0,0 +1,126 @@ +package cobra + +import ( + "bytes" + "fmt" + "io" + "os" + "strings" +) + +// GenZshCompletionFile generates zsh completion file. +func (c *Command) GenZshCompletionFile(filename string) error { + outFile, err := os.Create(filename) + if err != nil { + return err + } + defer outFile.Close() + + return c.GenZshCompletion(outFile) +} + +// GenZshCompletion generates a zsh completion file and writes to the passed writer. +func (c *Command) GenZshCompletion(w io.Writer) error { + buf := new(bytes.Buffer) + + writeHeader(buf, c) + maxDepth := maxDepth(c) + writeLevelMapping(buf, maxDepth) + writeLevelCases(buf, maxDepth, c) + + _, err := buf.WriteTo(w) + return err +} + +func writeHeader(w io.Writer, cmd *Command) { + fmt.Fprintf(w, "#compdef %s\n\n", cmd.Name()) +} + +func maxDepth(c *Command) int { + if len(c.Commands()) == 0 { + return 0 + } + maxDepthSub := 0 + for _, s := range c.Commands() { + subDepth := maxDepth(s) + if subDepth > maxDepthSub { + maxDepthSub = subDepth + } + } + return 1 + maxDepthSub +} + +func writeLevelMapping(w io.Writer, numLevels int) { + fmt.Fprintln(w, `_arguments \`) + for i := 1; i <= numLevels; i++ { + fmt.Fprintf(w, ` '%d: :->level%d' \`, i, i) + fmt.Fprintln(w) + } + fmt.Fprintf(w, ` '%d: :%s'`, numLevels+1, "_files") + fmt.Fprintln(w) +} + +func writeLevelCases(w io.Writer, maxDepth int, root *Command) { + fmt.Fprintln(w, "case $state in") + defer fmt.Fprintln(w, "esac") + + for i := 1; i <= maxDepth; i++ { + fmt.Fprintf(w, " level%d)\n", i) + writeLevel(w, root, i) + fmt.Fprintln(w, " ;;") + } + fmt.Fprintln(w, " *)") + fmt.Fprintln(w, " _arguments '*: :_files'") + fmt.Fprintln(w, " ;;") +} + +func writeLevel(w io.Writer, root *Command, i int) { + fmt.Fprintf(w, " case $words[%d] in\n", i) + defer fmt.Fprintln(w, " esac") + + commands := filterByLevel(root, i) + byParent := groupByParent(commands) + + for p, c := range byParent { + names := names(c) + fmt.Fprintf(w, " %s)\n", p) + fmt.Fprintf(w, " _arguments '%d: :(%s)'\n", i, strings.Join(names, " ")) + fmt.Fprintln(w, " ;;") + } + fmt.Fprintln(w, " *)") + fmt.Fprintln(w, " _arguments '*: :_files'") + fmt.Fprintln(w, " ;;") + +} + +func filterByLevel(c *Command, l int) []*Command { + cs := make([]*Command, 0) + if l == 0 { + cs = append(cs, c) + return cs + } + for _, s := range c.Commands() { + cs = append(cs, filterByLevel(s, l-1)...) + } + return cs +} + +func groupByParent(commands []*Command) map[string][]*Command { + m := make(map[string][]*Command) + for _, c := range commands { + parent := c.Parent() + if parent == nil { + continue + } + m[parent.Name()] = append(m[parent.Name()], c) + } + return m +} + +func names(commands []*Command) []string { + ns := make([]string, len(commands)) + for i, c := range commands { + ns[i] = c.Name() + } + return ns +} diff --git a/vendor/github.com/spf13/cobra/zsh_completions_test.go b/vendor/github.com/spf13/cobra/zsh_completions_test.go new file mode 100644 index 00000000..34e69496 --- /dev/null +++ b/vendor/github.com/spf13/cobra/zsh_completions_test.go @@ -0,0 +1,89 @@ +package cobra + +import ( + "bytes" + "strings" + "testing" +) + +func TestZshCompletion(t *testing.T) { + tcs := []struct { + name string + root *Command + expectedExpressions []string + }{ + { + name: "trivial", + root: &Command{Use: "trivialapp"}, + expectedExpressions: []string{"#compdef trivial"}, + }, + { + name: "linear", + root: func() *Command { + r := &Command{Use: "linear"} + + sub1 := &Command{Use: "sub1"} + r.AddCommand(sub1) + + sub2 := &Command{Use: "sub2"} + sub1.AddCommand(sub2) + + sub3 := &Command{Use: "sub3"} + sub2.AddCommand(sub3) + return r + }(), + expectedExpressions: []string{"sub1", "sub2", "sub3"}, + }, + { + name: "flat", + root: func() *Command { + r := &Command{Use: "flat"} + r.AddCommand(&Command{Use: "c1"}) + r.AddCommand(&Command{Use: "c2"}) + return r + }(), + expectedExpressions: []string{"(c1 c2)"}, + }, + { + name: "tree", + root: func() *Command { + r := &Command{Use: "tree"} + + sub1 := &Command{Use: "sub1"} + r.AddCommand(sub1) + + sub11 := &Command{Use: "sub11"} + sub12 := &Command{Use: "sub12"} + + sub1.AddCommand(sub11) + sub1.AddCommand(sub12) + + sub2 := &Command{Use: "sub2"} + r.AddCommand(sub2) + + sub21 := &Command{Use: "sub21"} + sub22 := &Command{Use: "sub22"} + + sub2.AddCommand(sub21) + sub2.AddCommand(sub22) + + return r + }(), + expectedExpressions: []string{"(sub11 sub12)", "(sub21 sub22)"}, + }, + } + + for _, tc := range tcs { + t.Run(tc.name, func(t *testing.T) { + buf := new(bytes.Buffer) + tc.root.GenZshCompletion(buf) + output := buf.String() + + for _, expectedExpression := range tc.expectedExpressions { + if !strings.Contains(output, expectedExpression) { + t.Errorf("Expected completion to contain %q somewhere; got %q", expectedExpression, output) + } + } + }) + } +} From e37c8bb2233f5b361fd56db1ea13b68b7290d451 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Thu, 12 Apr 2018 11:45:54 -0700 Subject: [PATCH 28/94] commands: make --version a synonym for 'version' --- commands/run.go | 5 +++++ test/test-version.sh | 23 +++++++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100755 test/test-version.sh diff --git a/commands/run.go b/commands/run.go index 6cc5faea..5196fc3a 100644 --- a/commands/run.go +++ b/commands/run.go @@ -10,6 +10,7 @@ import ( "time" "github.com/git-lfs/git-lfs/config" + "github.com/git-lfs/git-lfs/lfsapi" "github.com/spf13/cobra" ) @@ -55,6 +56,10 @@ func Run() { root := NewCommand("git-lfs", gitlfsCommand) root.PreRun = nil + // Set up --version flag to be a synonym of version sub-command. + root.SetVersionTemplate("{{ .Version }}\n") + root.Version = lfsapi.UserAgent + // Set up help/usage funcs based on manpage text root.SetHelpTemplate("{{.UsageString}}") root.SetHelpFunc(helpCommand) diff --git a/test/test-version.sh b/test/test-version.sh new file mode 100755 index 00000000..31dfdb7f --- /dev/null +++ b/test/test-version.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +. "test/testlib.sh" + +begin_test "git lfs --version is a synonym of git lfs version" +( + set -e + + reponame="git-lfs-version-synonymous" + mkdir "$reponame" + cd "$reponame" + + git lfs version 2>&1 >version.log + git lfs --version 2>&1 >flag.log + + if [ "$(cat version.log)" != "$(cat flag.log)" ]; then + echo >&2 "fatal: expected 'git lfs version' and 'git lfs --version' to" + echo >&2 "produce identical output ..." + + diff -u {version,flag}.log + fi +) +end_test From 3379c0c1614fa1ddb9e7925796b32906bd2aa42e Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Thu, 12 Apr 2018 12:16:07 -0700 Subject: [PATCH 29/94] commands/run.go: teach Run() to return an exit code --- commands/run.go | 6 +++++- git-lfs.go | 3 ++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/commands/run.go b/commands/run.go index 6cc5faea..9a78f0d8 100644 --- a/commands/run.go +++ b/commands/run.go @@ -49,7 +49,9 @@ func RegisterCommand(name string, runFn func(cmd *cobra.Command, args []string), // Run initializes the 'git-lfs' command and runs it with the given stdin and // command line args. -func Run() { +// +// It returns an exit code. +func Run() int { log.SetOutput(ErrorWriter) root := NewCommand("git-lfs", gitlfsCommand) @@ -70,6 +72,8 @@ func Run() { root.Execute() closeAPIClient() + + return 0 } func gitlfsCommand(cmd *cobra.Command, args []string) { diff --git a/git-lfs.go b/git-lfs.go index c185eea0..d8d66b41 100644 --- a/git-lfs.go +++ b/git-lfs.go @@ -32,6 +32,7 @@ func main() { } }() - commands.Run() + code := commands.Run() once.Do(commands.Cleanup) + os.Exit(code) } From a4dfae7ccdf80c9aaf38de7db4687cf6d2fbb7bb Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Thu, 12 Apr 2018 12:16:24 -0700 Subject: [PATCH 30/94] commands/run.go: return 127 from an unknown sub-command --- commands/run.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/commands/run.go b/commands/run.go index 9a78f0d8..de7409a0 100644 --- a/commands/run.go +++ b/commands/run.go @@ -70,9 +70,12 @@ func Run() int { } } - root.Execute() + err := root.Execute() closeAPIClient() + if err != nil { + return 127 + } return 0 } From 987c1377f7931040a49f4323109605f6afa7ed08 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Wed, 18 Apr 2018 15:14:50 -0700 Subject: [PATCH 31/94] git: include SHA1 in ref-less revisions --- git/git.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/git/git.go b/git/git.go index bd5b931f..fd542571 100644 --- a/git/git.go +++ b/git/git.go @@ -245,7 +245,8 @@ func ResolveRef(ref string) (*Ref, error) { if len(lines) == 1 { // ref is a sha1 and has no symbolic-full-name - fullref.Name = lines[0] // fullref.Sha + fullref.Name = lines[0] + fullref.Sha = lines[0] fullref.Type = RefTypeOther return fullref, nil } From 68da2113044d57d84bc128e44302f01af14ecff2 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Wed, 18 Apr 2018 15:21:59 -0700 Subject: [PATCH 32/94] commands/uninstall: do not log about global hooks with --local --- commands/command_uninstall.go | 4 +++- test/test-uninstall.sh | 7 ++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/commands/command_uninstall.go b/commands/command_uninstall.go index b27336cc..bdea8267 100644 --- a/commands/command_uninstall.go +++ b/commands/command_uninstall.go @@ -14,7 +14,9 @@ func uninstallCommand(cmd *cobra.Command, args []string) { uninstallHooksCommand(cmd, args) } - Print("Global Git LFS configuration has been removed.") + if !localInstall { + Print("Global Git LFS configuration has been removed.") + } } // uninstallHooksCmd removes any hooks created by Git LFS. diff --git a/test/test-uninstall.sh b/test/test-uninstall.sh index 4d588bc0..82b07346 100755 --- a/test/test-uninstall.sh +++ b/test/test-uninstall.sh @@ -169,7 +169,12 @@ begin_test "uninstall --local" [ "global clean" = "$(git config --global filter.lfs.clean)" ] [ "global filter" = "$(git config --global filter.lfs.process)" ] - git lfs uninstall --local + git lfs uninstall --local 2>&1 | tee uninstall.log + if [ ${PIPESTATUS[0]} -ne 0 ]; then + echo >&2 "fatal: expected 'git lfs uninstall --local' to succeed" + exit 1 + fi + grep -v "Global Git LFS configuration has been removed." uninstall.log # global configs [ "global smudge" = "$(git config --global filter.lfs.smudge)" ] From c5da1713e08dcb925967c494d23781d3e3e4a802 Mon Sep 17 00:00:00 2001 From: Jerry Chong Date: Fri, 27 Apr 2018 11:19:39 +0800 Subject: [PATCH 33/94] .gitattributes link is broken The link that points to gitattributes' documentation appears to be broken, should've been https://git-scm.com/docs/gitattributes --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f8005055..8bc3c65b 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ $ git lfs track "*.psd" (Where `*.psd` is the pattern of filenames that you wish to track. You can read more about this pattern syntax -[here](https://git-scm.org/docs/git-attribute://git-scm.com/docs/gitattributes)). +[here](https://git-scm.com/docs/gitattributes)). After any invocation of `git-lfs-track(1)` or `git-lfs-untrack(1)`, you _must commit changes to your `.gitattributes` file_. This can be done by running: From e12a8b6b386560f485ca86e1d2b594d6b07216ff Mon Sep 17 00:00:00 2001 From: Patrick Marlier Date: Sat, 14 Apr 2018 11:47:20 +0200 Subject: [PATCH 34/94] Do not migrate the symlinks to LFS objects. --- git/githistory/rewriter.go | 6 ++++++ test/test-migrate-fixtures.sh | 23 ++++++++++++++++++++++- test/test-migrate-import.sh | 20 ++++++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/git/githistory/rewriter.go b/git/githistory/rewriter.go index 2ba0c533..dd545f08 100644 --- a/git/githistory/rewriter.go +++ b/git/githistory/rewriter.go @@ -341,6 +341,12 @@ func (r *Rewriter) rewriteTree(commitOID []byte, treeOID []byte, path string, fn continue } + // If this is a symlink, skip it + if entry.Filemode == 0120000 { + entries = append(entries, copyEntry(entry)) + continue + } + if cached := r.uncacheEntry(entry); cached != nil { entries = append(entries, copyEntry(cached)) continue diff --git a/test/test-migrate-fixtures.sh b/test/test-migrate-fixtures.sh index 9be71f4d..4fbb8799 100755 --- a/test/test-migrate-fixtures.sh +++ b/test/test-migrate-fixtures.sh @@ -18,7 +18,7 @@ assert_ref_unmoved() { fi } -# setup_multiple_local_branches creates a repository as follows: +# setup_local_branch_with_gitattrs creates a repository as follows: # # A---B # \ @@ -261,6 +261,27 @@ setup_single_local_branch_deep_trees() { git commit -m "initial commit" } +# setup_local_branch_with_symlink creates a repository as follows: +# +# A +# \ +# refs/heads/master +# +# - Commit 'A' has 120, in a.txt, and a symbolic link link.txt to a.txt. +setup_local_branch_with_symlink() { + set -e + + reponame="migrate-single-local-branch-with-symlink" + + remove_and_create_local_repo "$reponame" + + base64 < /dev/urandom | head -c 120 > a.txt + ln -s a.txt link.txt + + git add a.txt link.txt + git commit -m "initial commit" +} + # make_bare converts the existing full checkout of a repository into a bare one, # and then `cd`'s into it. make_bare() { diff --git a/test/test-migrate-import.sh b/test/test-migrate-import.sh index fc2b902a..8785f0f9 100755 --- a/test/test-migrate-import.sh +++ b/test/test-migrate-import.sh @@ -652,4 +652,24 @@ begin_test "migrate import (--include with space)" sed -e 's/^/ /g' < .gitattributes >&2 exit 1 fi +) +end_test + +begin_test "migrate import (handle symbolic link)" +( + set -e + + setup_local_branch_with_symlink + + txt_oid="$(calc_oid "$(git cat-file -p :a.txt)")" + link_oid="$(calc_oid "$(git cat-file -p :link.txt)")" + + git lfs migrate import --include="*.txt" + + assert_pointer "refs/heads/master" "a.txt" "$txt_oid" "120" + + assert_local_object "$txt_oid" "120" + # "link.txt" is a symbolic link so it should be not in LFS + refute_local_object "$link_oid" "5" +) end_test From f7349b43cc1188a2a3fd36a4438adba17639842e Mon Sep 17 00:00:00 2001 From: Patrick Marlier Date: Fri, 27 Apr 2018 08:33:29 +0200 Subject: [PATCH 35/94] Add and use helper to add symbolic link In Windows, "ln -s" might not create a symbolic link depending on the configuration. --- test/test-migrate-fixtures.sh | 6 ++++-- test/testhelpers.sh | 11 +++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/test/test-migrate-fixtures.sh b/test/test-migrate-fixtures.sh index 4fbb8799..6d3408fa 100755 --- a/test/test-migrate-fixtures.sh +++ b/test/test-migrate-fixtures.sh @@ -276,10 +276,12 @@ setup_local_branch_with_symlink() { remove_and_create_local_repo "$reponame" base64 < /dev/urandom | head -c 120 > a.txt - ln -s a.txt link.txt - git add a.txt link.txt + git add a.txt git commit -m "initial commit" + + add_symlink "a.txt" "link.txt" + git commit -m "add symlink" } # make_bare converts the existing full checkout of a repository into a bare one, diff --git a/test/testhelpers.sh b/test/testhelpers.sh index bb8fdf81..40180933 100644 --- a/test/testhelpers.sh +++ b/test/testhelpers.sh @@ -738,3 +738,14 @@ has_test_dir() { exit 0 fi } + +add_symlink() { + local src=$1 + local dest=$2 + + prefix=`git rev-parse --show-prefix` + hashsrc=`printf "$src" | git hash-object -w --stdin` + + git update-index --add --cacheinfo 120000 "$hashsrc" "$prefix$dest" + git checkout -- "$dest" +} From b3509e1e8f2896d5e82e184f561677797a6192af Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 4 May 2018 09:07:25 -0700 Subject: [PATCH 36/94] lfs/attribute.go: remove default value from upgradeables --- lfs/attribute.go | 48 ++++++++++++++++++++++++++------------------ test/test-install.sh | 15 +++++++++----- 2 files changed, 39 insertions(+), 24 deletions(-) diff --git a/lfs/attribute.go b/lfs/attribute.go index fee511ab..bbe6f521 100644 --- a/lfs/attribute.go +++ b/lfs/attribute.go @@ -56,7 +56,21 @@ func filterAttribute() *Attribute { "process": "git-lfs filter-process", "required": "true", }, - Upgradeables: upgradeables(), + Upgradeables: map[string][]string{ + "clean": []string{ + "git-lfs clean %f", + }, + "smudge": []string{ + "git-lfs smudge %f", + "git-lfs smudge --skip %f", + "git-lfs smudge --skip -- %f", + }, + "process": []string{ + "git-lfs filter", + "git-lfs filter --skip", + "git-lfs filter-process --skip", + }, + }, } } @@ -69,24 +83,20 @@ func skipSmudgeFilterAttribute() *Attribute { "process": "git-lfs filter-process --skip", "required": "true", }, - Upgradeables: upgradeables(), - } -} - -func upgradeables() map[string][]string { - return map[string][]string{ - "clean": []string{"git-lfs clean %f"}, - "smudge": []string{ - "git-lfs smudge %f", - "git-lfs smudge --skip %f", - "git-lfs smudge -- %f", - "git-lfs smudge --skip -- %f", - }, - "process": []string{ - "git-lfs filter", - "git-lfs filter --skip", - "git-lfs filter-process", - "git-lfs filter-process --skip", + Upgradeables: map[string][]string{ + "clean": []string{ + "git-lfs clean -- %f", + }, + "smudge": []string{ + "git-lfs smudge %f", + "git-lfs smudge --skip %f", + "git-lfs smudge -- %f", + }, + "process": []string{ + "git-lfs filter", + "git-lfs filter --skip", + "git-lfs filter-process", + }, }, } } diff --git a/test/test-install.sh b/test/test-install.sh index d4ef864d..abc8f641 100755 --- a/test/test-install.sh +++ b/test/test-install.sh @@ -4,17 +4,22 @@ begin_test "install again" ( - set -e + set -eo pipefail smudge="$(git config filter.lfs.smudge)" clean="$(git config filter.lfs.clean)" filter="$(git config filter.lfs.process)" - printf "$smudge" | grep "git-lfs smudge" - printf "$clean" | grep "git-lfs clean" - printf "$filter" | grep "git-lfs filter-process" + [ "$smudge" = "git-lfs smudge -- %f" ] + [ "$clean" = "git-lfs clean -- %f" ] + [ "$filter" = "git-lfs filter-process" ] - git lfs install + GIT_TRACE=1 git lfs install --skip-repo 2>&1 | tee install.log + + if grep -q "--replace-all" install.log; then + echo >&2 "fatal: unexpected git config --replace-all via 'git lfs install'" + exit 1 + fi [ "$smudge" = "$(git config filter.lfs.smudge)" ] [ "$clean" = "$(git config filter.lfs.clean)" ] From c8b3160d9f0cb23de2c172c0cf2ab63f90bdfc66 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 4 May 2018 14:48:34 -0700 Subject: [PATCH 37/94] test/test-lock.sh: fix misquoting --- test/test-lock.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/test-lock.sh b/test/test-lock.sh index 5b90e501..46a72582 100755 --- a/test/test-lock.sh +++ b/test/test-lock.sh @@ -12,7 +12,7 @@ begin_test "lock with good ref" git lfs lock "a.dat" --json 2>&1 | tee lock.json if [ "0" -ne "${PIPESTATUS[0]}" ]; then - echo >&2 "fatal: expected 'git lfs lock \'a.dat\'' to succeed" + echo >&2 "fatal: expected \'git lfs lock \'a.dat\'\' to succeed" exit 1 fi @@ -40,7 +40,7 @@ begin_test "lock with good tracked ref" git lfs lock "a.dat" --json 2>&1 | tee lock.json if [ "0" -ne "${PIPESTATUS[0]}" ]; then - echo >&2 "fatal: expected 'git lfs lock \'a.dat\'' to succeed" + echo >&2 "fatal: expected \'git lfs lock \'a.dat\'\' to succeed" exit 1 fi @@ -65,7 +65,7 @@ begin_test "lock with bad ref" GIT_CURL_VERBOSE=1 git lfs lock "a.dat" 2>&1 | tee lock.json if [ "0" -eq "${PIPESTATUS[0]}" ]; then - echo >&2 "fatal: expected 'git lfs lock \'a.dat\'' to fail" + echo >&2 "fatal: expected \'git lfs lock \'a.dat\'\' to fail" exit 1 fi @@ -187,7 +187,7 @@ begin_test "creating a lock (within subdirectory)" git lfs lock --json "a.dat" | tee lock.json if [ "0" -ne "${PIPESTATUS[0]}" ]; then - echo >&2 "fatal: expected 'git lfs lock \'a.dat\'' to succeed" + echo >&2 "fatal: expected \'git lfs lock \'a.dat\'\' to succeed" exit 1 fi From 5dc2532cc75994ec70f8c722976cb87d0e027dd8 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 4 May 2018 15:03:35 -0700 Subject: [PATCH 38/94] commands/command_lock: resolve symbolic links in cwd --- commands/command_lock.go | 5 +++++ test/test-lock.sh | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/commands/command_lock.go b/commands/command_lock.go index eb06104b..ab88d7de 100644 --- a/commands/command_lock.go +++ b/commands/command_lock.go @@ -79,6 +79,11 @@ func lockPath(file string) (string, error) { if err != nil { return "", err } + wd, err = filepath.EvalSymlinks(wd) + if err != nil { + return "", errors.Wrapf(err, + "could not follow symlinks for %s", wd) + } abs := filepath.Join(wd, file) path := strings.TrimPrefix(abs, repo) diff --git a/test/test-lock.sh b/test/test-lock.sh index 46a72582..bd82b4f0 100755 --- a/test/test-lock.sh +++ b/test/test-lock.sh @@ -195,3 +195,37 @@ begin_test "creating a lock (within subdirectory)" assert_server_lock "$reponame" "$id" ) end_test + +begin_test "creating a lock (symlinked working directory)" +( + set -eo pipefail + + if [[ $(uname) == *"MINGW"* ]]; then + echo >&2 "info: skipped on Windows ..." + exit 0 + fi + + reponame="lock-in-symlinked-working-directory" + setup_remote_repo "$reponame" + clone_repo "$reponame" "$reponame" + + git lfs track -l "*.dat" + mkdir -p folder1 folder2 + printf "hello" > folder2/a.dat + add_symlink "../folder2" "folder1/folder2" + + git add --all . + git commit -m "initial commit" + git push origin master + + pushd "$TRASHDIR" > /dev/null + ln -s "$reponame" "$reponame-symlink" + cd "$reponame-symlink" + + git lfs lock --json folder1/folder2/a.dat 2>&1 | tee lock.json + + id="$(assert_lock lock.json folder1/folder2/a.dat)" + assert_server_lock "$reponame" "$id" master + popd > /dev/null +) +end_test From b265385a7e8f24a2bafded5f1e92b1f04d26789a Mon Sep 17 00:00:00 2001 From: Evan Zacks Date: Fri, 4 May 2018 16:41:34 -0700 Subject: [PATCH 39/94] remove reference to CLA from contributor's guide --- CONTRIBUTING.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index dd24e8bc..166d0911 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -63,7 +63,6 @@ In general, contributors should develop on branches based off of `master` and pu 0. Create a new branch based on `master`: `git checkout -b master` 0. Make your change, add tests, and make sure the tests still pass 0. Push to your fork and [submit a pull request][pr] from your branch to `master` -0. Accept the [GitHub CLA][cla] 0. Pat yourself on the back and wait for your pull request to be reviewed Here are a few things you can do that will increase the likelihood of your pull request being accepted: @@ -161,4 +160,3 @@ v1.5 just shipped, set the version in master to `1.6-pre`, for example. [fork]: https://github.com/git-lfs/git-lfs/fork [pr]: https://github.com/git-lfs/git-lfs/compare [style]: https://github.com/golang/go/wiki/CodeReviewComments -[cla]: https://cla.github.com/git-lfs/git-lfs/accept From b2bd164b325c5bcf38fce70e0c9f90816b9bee64 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Wed, 16 May 2018 20:48:46 -0700 Subject: [PATCH 40/94] lfsapi: canonicalize extra HTTP headers --- lfsapi/auth.go | 2 ++ lfsapi/client.go | 8 ++++++++ test/test-extra-header.sh | 39 ++++++++++++++++++++++++++++++++++++++- 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/lfsapi/auth.go b/lfsapi/auth.go index d4bcc4ad..837e217b 100644 --- a/lfsapi/auth.go +++ b/lfsapi/auth.go @@ -270,6 +270,8 @@ func hasScheme(what string) bool { } func requestHasAuth(req *http.Request) bool { + // The "Authorization" string constant is safe, since we assume that all + // request headers have been canonicalized. if len(req.Header.Get("Authorization")) > 0 { return true } diff --git a/lfsapi/client.go b/lfsapi/client.go index de69d70a..222a9a5c 100644 --- a/lfsapi/client.go +++ b/lfsapi/client.go @@ -7,6 +7,7 @@ import ( "io" "net" "net/http" + "net/textproto" "net/url" "os" "regexp" @@ -147,6 +148,13 @@ func (c *Client) extraHeaders(u *url.URL) map[string][]string { } k, v := parts[0], strings.TrimSpace(parts[1]) + // If header keys are given in non-canonicalized form (e.g., + // "AUTHORIZATION" as opposed to "Authorization") they will not + // be returned in calls to net/http.Header.Get(). + // + // So, we avoid this problem by first canonicalizing header keys + // for extra headers. + k = textproto.CanonicalMIMEHeaderKey(k) m[k] = append(m[k], v) } diff --git a/test/test-extra-header.sh b/test/test-extra-header.sh index 1dbcfe30..9baae72d 100755 --- a/test/test-extra-header.sh +++ b/test/test-extra-header.sh @@ -34,7 +34,7 @@ begin_test "http..extraHeader with authorization" setup_remote_repo "$reponame" clone_repo "$reponame" "$reponame" - # See: test/cmd/lfstest-gitserver.go:1176. + # See: test/cmd/lfstest-gitserver.go:missingRequiredCreds(). user="requirecreds" pass="pass" auth="Basic $(echo -n $user:$pass | base64)" @@ -59,3 +59,40 @@ begin_test "http..extraHeader with authorization" [ "0" -eq "$(grep -c "creds: git credential reject" curl.log)" ] ) end_test + +begin_test "http..extraHeader with authorization (casing)" +( + set -e + + reponame="requirecreds-extraHeaderCasing" + setup_remote_repo "$reponame" + clone_repo "$reponame" "$reponame" + + # See: test/cmd/lfstest-gitserver.go:missingRequiredCreds(). + user="requirecreds" + pass="pass" + auth="Basic $(echo -n $user:$pass | base64)" + + git config --add lfs.access basic + # N.B.: "AUTHORIZATION" is not the correct casing, and is therefore the + # subject of this test. See lfsapi.Client.extraHeaders() for more. + git config --add "http.extraHeader" "AUTHORIZATION: $auth" + + git lfs track "*.dat" + printf "contents" > a.dat + git add .gitattributes a.dat + git commit -m "initial commit" + + git push origin master 2>&1 | tee curl.log + if [ "0" -ne "${PIPESTATUS[0]}" ]; then + echo >&2 "expected \`git push origin master\` to succeed, didn't" + exit 1 + fi + + [ "0" -eq "$(grep -c "creds: filling with GIT_ASKPASS" curl.log)" ] + [ "0" -eq "$(grep -c "creds: git credential approve" curl.log)" ] + [ "0" -eq "$(grep -c "creds: git credential cache" curl.log)" ] + [ "0" -eq "$(grep -c "creds: git credential fill" curl.log)" ] + [ "0" -eq "$(grep -c "creds: git credential reject" curl.log)" ] +) +end_test From 4e1f75d6a557e63a605f06165467ae342d538893 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 18 May 2018 15:28:15 -0700 Subject: [PATCH 41/94] test/test-extra-header.sh: run git config with --local --- test/test-extra-header.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test-extra-header.sh b/test/test-extra-header.sh index 9baae72d..b3a5f919 100755 --- a/test/test-extra-header.sh +++ b/test/test-extra-header.sh @@ -73,10 +73,10 @@ begin_test "http..extraHeader with authorization (casing)" pass="pass" auth="Basic $(echo -n $user:$pass | base64)" - git config --add lfs.access basic + git config --local --add lfs.access basic # N.B.: "AUTHORIZATION" is not the correct casing, and is therefore the # subject of this test. See lfsapi.Client.extraHeaders() for more. - git config --add "http.extraHeader" "AUTHORIZATION: $auth" + git config --local --add "http.extraHeader" "AUTHORIZATION: $auth" git lfs track "*.dat" printf "contents" > a.dat From 138024f4f8a5fc1a1aea84796fee2506742c0b19 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 21 May 2018 13:51:10 -0700 Subject: [PATCH 42/94] test/test-env: skip comparing GIT_EXEC_PATH --- test/test-env.sh | 62 ++++++++++++++++++++++++++---------------------- 1 file changed, 34 insertions(+), 28 deletions(-) diff --git a/test/test-env.sh b/test/test-env.sh index 5879bff0..2a3047e2 100755 --- a/test/test-env.sh +++ b/test/test-env.sh @@ -50,7 +50,7 @@ UploadTransfers=basic %s %s ' "$(git lfs version)" "$(git version)" "$localwd" "$localgit" "$localgitstore" "$localmedia" "$tempdir" "$lfsstorage" "$envVars" "$envInitConfig") - actual=$(git lfs env) + actual=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected" "$actual" ) @@ -102,12 +102,12 @@ UploadTransfers=basic %s %s ' "$(git lfs version)" "$(git version)" "$endpoint" "$localwd" "$localgit" "$localgitstore" "$localmedia" "$tempdir" "$lfsstorage" "$envVars" "$envInitConfig") - actual=$(git lfs env) + actual=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected" "$actual" cd .git expected2=$(echo "$expected" | sed -e 's/LocalWorkingDir=.*/LocalWorkingDir=/') - actual2=$(git lfs env) + actual2=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected2" "$actual2" ) end_test @@ -161,12 +161,12 @@ UploadTransfers=basic %s %s ' "$(git lfs version)" "$(git version)" "$endpoint" "$endpoint2" "$localwd" "$localgit" "$localgitstore" "$localmedia" "$tempdir" "$lfsstorage" "$envVars" "$envInitConfig") - actual=$(git lfs env) + actual=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected" "$actual" cd .git expected2=$(echo "$expected" | sed -e 's/LocalWorkingDir=.*/LocalWorkingDir=/') - actual2=$(git lfs env) + actual2=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected2" "$actual2" ) end_test @@ -218,12 +218,12 @@ UploadTransfers=basic %s %s ' "$(git lfs version)" "$(git version)" "$endpoint" "$localwd" "$localgit" "$localgitstore" "$localmedia" "$tempdir" "$lfsstorage" "$envVars" "$envInitConfig") - actual=$(git lfs env) + actual=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected" "$actual" cd .git expected2=$(echo "$expected" | sed -e 's/LocalWorkingDir=.*/LocalWorkingDir=/') - actual2=$(git lfs env) + actual2=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected2" "$actual2" ) end_test @@ -277,12 +277,12 @@ UploadTransfers=basic %s %s ' "$(git lfs version)" "$(git version)" "$endpoint" "$localwd" "$localgit" "$localgitstore" "$localmedia" "$tempdir" "$lfsstorage" "$envVars" "$envInitConfig") - actual=$(git lfs env) + actual=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected" "$actual" cd .git expected2=$(echo "$expected" | sed -e 's/LocalWorkingDir=.*/LocalWorkingDir=/') - actual2=$(git lfs env) + actual2=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected2" "$actual2" ) end_test @@ -337,12 +337,12 @@ UploadTransfers=basic %s %s ' "$(git lfs version)" "$(git version)" "$localwd" "$localgit" "$localgitstore" "$localmedia" "$tempdir" "$lfsstorage" "$envVars" "$envInitConfig") - actual=$(git lfs env) + actual=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected" "$actual" cd .git expected2=$(echo "$expected" | sed -e 's/LocalWorkingDir=.*/LocalWorkingDir=/') - actual2=$(git lfs env) + actual2=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected2" "$actual2" ) end_test @@ -398,12 +398,12 @@ UploadTransfers=basic %s %s ' "$(git lfs version)" "$(git version)" "$localwd" "$localgit" "$localgitstore" "$localmedia" "$tempdir" "$lfsstorage" "$envVars" "$envInitConfig") - actual=$(git lfs env) + actual=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected" "$actual" cd .git expected2=$(echo "$expected" | sed -e 's/LocalWorkingDir=.*/LocalWorkingDir=/') - actual2=$(git lfs env) + actual2=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected2" "$actual2" ) end_test @@ -466,12 +466,12 @@ UploadTransfers=basic %s %s ' "$(git lfs version)" "$(git version)" "$localwd" "$localgit" "$localgitstore" "$localmedia" "$tempdir" "$lfsstorage" "$envVars" "$envInitConfig") - actual=$(git lfs env) + actual=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected" "$actual" mkdir a cd a - actual2=$(git lfs env) + actual2=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected" "$actual2" ) end_test @@ -522,19 +522,23 @@ UploadTransfers=basic %s ' "$(git lfs version)" "$(git version)" "$localwd" "$localgit" "$localgitstore" "$localmedia" "$tempdir" "$lfsstorage" "$envVars" "$envInitConfig") - actual=$(GIT_DIR=$gitDir GIT_WORK_TREE=$workTree git lfs env) + actual=$(GIT_DIR=$gitDir GIT_WORK_TREE=$workTree git lfs env \ + | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected" "$actual" cd $TRASHDIR/$reponame - actual2=$(GIT_DIR=$gitDir GIT_WORK_TREE=$workTree git lfs env) + actual2=$(GIT_DIR=$gitDir GIT_WORK_TREE=$workTree git lfs env \ + | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected" "$actual2" cd $TRASHDIR/$reponame/.git - actual3=$(GIT_DIR=$gitDir GIT_WORK_TREE=$workTree git lfs env) + actual3=$(GIT_DIR=$gitDir GIT_WORK_TREE=$workTree git lfs env \ + | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected" "$actual3" cd $TRASHDIR/$reponame/a/b/c - actual4=$(GIT_DIR=$gitDir GIT_WORK_TREE=$workTree git lfs env) + actual4=$(GIT_DIR=$gitDir GIT_WORK_TREE=$workTree git lfs env \ + | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected" "$actual4" envVars="$(GIT_DIR=$gitDir GIT_WORK_TREE=a/b env | grep "^GIT" | sort)" @@ -565,7 +569,8 @@ DownloadTransfers=basic UploadTransfers=basic %s ' "$(git lfs version)" "$(git version)" "$localwd" "$localgit" "$localgitstore" "$localmedia" "$tempdir" "$lfsstorage" "$envVars") - actual5=$(GIT_DIR=$gitDir GIT_WORK_TREE=a/b git lfs env) + actual5=$(GIT_DIR=$gitDir GIT_WORK_TREE=a/b git lfs env \ + | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected5" "$actual5" cd $TRASHDIR/$reponame/a/b @@ -598,7 +603,7 @@ UploadTransfers=basic %s %s ' "$(git lfs version)" "$(git version)" "$localwd" "$localgit" "$localgitstore" "$localmedia" "$tempdir" "$lfsstorage" "$envVars" "$envInitConfig") - actual7=$(GIT_DIR=$gitDir git lfs env) + actual7=$(GIT_DIR=$gitDir git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected7" "$actual7" cd $TRASHDIR/$reponame/a @@ -631,7 +636,7 @@ UploadTransfers=basic %s %s ' "$(git lfs version)" "$(git version)" "$localwd" "$localgit" "$localgitstore" "$localmedia" "$tempdir" "$lfsstorage" "$envVars" "$envInitConfig") - actual8=$(GIT_WORK_TREE=$workTree git lfs env) + actual8=$(GIT_WORK_TREE=$workTree git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected8" "$actual8" ) end_test @@ -676,7 +681,7 @@ UploadTransfers=basic %s %s " "$(git lfs version)" "$(git version)" "$localgit" "$localgitstore" "$localmedia" "$tempdir" "$lfsstorage" "$envVars" "$envInitConfig") - actual=$(git lfs env) + actual=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected" "$actual" ) @@ -698,7 +703,8 @@ Endpoint (other)=https://other-git-server.com/user/repo.git/info/lfs (auth=none) SSH=git@other-git-server.com:user/repo.git GIT_SSH=lfs-ssh-echo' - contains_same_elements "$expected" "$(git lfs env | grep -e "Endpoint" -e "SSH=")" + contains_same_elements "$expected" "$(git lfs env \ + | grep -v "^GIT_EXEC_PATH=" | grep -e "Endpoint" -e "SSH=")" ) end_test @@ -754,7 +760,7 @@ UploadTransfers=basic %s %s ' "$(git lfs version)" "$(git version)" "$localwd" "$localgit" "$localgitstore" "$localmedia" "$tempdir" "$lfsstorage" "$envVars" "$envInitConfig") - actual=$(git lfs env) + actual=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expectedenabled" "$actual" git config --unset lfs.skipdownloaderrors @@ -787,11 +793,11 @@ UploadTransfers=basic %s %s ' "$(git lfs version)" "$(git version)" "$localwd" "$localgit" "$localgitstore" "$localmedia" "$tempdir" "$lfsstorage" "$envVars" "$envInitConfig") - actual=$(git lfs env) + actual=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expecteddisabled" "$actual" # now enable via env var - actual=$(GIT_LFS_SKIP_DOWNLOAD_ERRORS=1 git lfs env) + actual=$(GIT_LFS_SKIP_DOWNLOAD_ERRORS=1 git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expectedenabled" "$actual" @@ -853,7 +859,7 @@ UploadTransfers=basic,supertransfer,tus %s %s ' "$(git lfs version)" "$(git version)" "$localwd" "$localgit" "$localgitstore" "$localmedia" "$tempdir" "$lfsstorage" "$envVars" "$envInitConfig") - actual=$(git lfs env) + actual=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expectedenabled" "$actual" ) From 13bfadd575e436a6230266c1a43a276a5aeb051d Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 21 May 2018 14:19:53 -0700 Subject: [PATCH 43/94] test/test-worktree.sh: ignore GIT_EXEC_PATH in tests --- test/test-worktree.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test-worktree.sh b/test/test-worktree.sh index 2b475361..d49f99a0 100755 --- a/test/test-worktree.sh +++ b/test/test-worktree.sh @@ -46,7 +46,7 @@ UploadTransfers=basic $(escape_path "$(env | grep "^GIT")") %s " "$(git lfs version)" "$(git version)" "$envInitConfig") - actual=$(git lfs env) + actual=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected" "$actual" worktreename="worktree-2" @@ -82,7 +82,7 @@ UploadTransfers=basic $(escape_path "$(env | grep "^GIT")") %s " "$(git lfs version)" "$(git version)" "$envInitConfig") - actual=$(git lfs env) + actual=$(git lfs env | grep -v "^GIT_EXEC_PATH=") contains_same_elements "$expected" "$actual" ) end_test From 6eb3d9009cdf12ff218c0a44b6404302c0fe8d81 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 21 May 2018 18:12:40 -0700 Subject: [PATCH 44/94] Revert "Merge pull request #2968 from git-lfs/root---version-flag" This reverts commit 8355d6c24f55212f8fba2dc34ad34b3e0894e2c5, reversing changes made to 1e995a7b06d6ecac33c227c295b8088261a56b5d. --- commands/run.go | 5 ----- test/test-version.sh | 23 ----------------------- 2 files changed, 28 deletions(-) delete mode 100755 test/test-version.sh diff --git a/commands/run.go b/commands/run.go index 18f3ef90..de7409a0 100644 --- a/commands/run.go +++ b/commands/run.go @@ -10,7 +10,6 @@ import ( "time" "github.com/git-lfs/git-lfs/config" - "github.com/git-lfs/git-lfs/lfsapi" "github.com/spf13/cobra" ) @@ -58,10 +57,6 @@ func Run() int { root := NewCommand("git-lfs", gitlfsCommand) root.PreRun = nil - // Set up --version flag to be a synonym of version sub-command. - root.SetVersionTemplate("{{ .Version }}\n") - root.Version = lfsapi.UserAgent - // Set up help/usage funcs based on manpage text root.SetHelpTemplate("{{.UsageString}}") root.SetHelpFunc(helpCommand) diff --git a/test/test-version.sh b/test/test-version.sh deleted file mode 100755 index 31dfdb7f..00000000 --- a/test/test-version.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env bash - -. "test/testlib.sh" - -begin_test "git lfs --version is a synonym of git lfs version" -( - set -e - - reponame="git-lfs-version-synonymous" - mkdir "$reponame" - cd "$reponame" - - git lfs version 2>&1 >version.log - git lfs --version 2>&1 >flag.log - - if [ "$(cat version.log)" != "$(cat flag.log)" ]; then - echo >&2 "fatal: expected 'git lfs version' and 'git lfs --version' to" - echo >&2 "produce identical output ..." - - diff -u {version,flag}.log - fi -) -end_test From 71f6f2ccdbf523bcd4d905c5b30fbde748335f18 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 21 May 2018 18:12:46 -0700 Subject: [PATCH 45/94] Revert "Merge pull request #2967 from git-lfs/cobra-pflag-update" This reverts commit 1e995a7b06d6ecac33c227c295b8088261a56b5d, reversing changes made to be8c46113637e3bfe158f673d6895ba01b21d462. --- glide.lock | 8 +- glide.yaml | 4 +- .../spf13/cobra/.circleci/config.yml | 38 - vendor/github.com/spf13/cobra/.gitignore | 12 - vendor/github.com/spf13/cobra/.mailmap | 3 - vendor/github.com/spf13/cobra/.travis.yml | 23 +- vendor/github.com/spf13/cobra/README.md | 879 ++++----- vendor/github.com/spf13/cobra/args.go | 89 - vendor/github.com/spf13/cobra/args_test.go | 241 --- .../spf13/cobra/bash_completions.go | 420 ++--- .../spf13/cobra/bash_completions.md | 88 +- .../spf13/cobra/bash_completions_test.go | 220 +-- vendor/github.com/spf13/cobra/cobra.go | 130 +- vendor/github.com/spf13/cobra/cobra/README.md | 94 - .../github.com/spf13/cobra/cobra/cmd/add.go | 179 -- .../spf13/cobra/cobra/cmd/add_test.go | 109 -- .../spf13/cobra/cobra/cmd/golden_test.go | 77 - .../spf13/cobra/cobra/cmd/helpers.go | 168 -- .../github.com/spf13/cobra/cobra/cmd/init.go | 234 --- .../spf13/cobra/cobra/cmd/init_test.go | 83 - .../spf13/cobra/cobra/cmd/license_agpl.go | 683 ------- .../spf13/cobra/cobra/cmd/license_apache_2.go | 238 --- .../cobra/cobra/cmd/license_bsd_clause_2.go | 71 - .../cobra/cobra/cmd/license_bsd_clause_3.go | 78 - .../spf13/cobra/cobra/cmd/license_gpl_2.go | 376 ---- .../spf13/cobra/cobra/cmd/license_gpl_3.go | 711 -------- .../spf13/cobra/cobra/cmd/license_lgpl.go | 186 -- .../spf13/cobra/cobra/cmd/license_mit.go | 63 - .../spf13/cobra/cobra/cmd/licenses.go | 118 -- .../spf13/cobra/cobra/cmd/project.go | 200 --- .../spf13/cobra/cobra/cmd/project_test.go | 24 - .../github.com/spf13/cobra/cobra/cmd/root.go | 79 - .../cobra/cobra/cmd/testdata/LICENSE.golden | 202 --- .../cobra/cobra/cmd/testdata/main.go.golden | 21 - .../cobra/cobra/cmd/testdata/root.go.golden | 89 - .../cobra/cobra/cmd/testdata/test.go.golden | 50 - vendor/github.com/spf13/cobra/cobra/main.go | 20 - vendor/github.com/spf13/cobra/cobra_test.go | 967 +++++++++- vendor/github.com/spf13/cobra/command.go | 1328 +++++--------- .../github.com/spf13/cobra/command_notwin.go | 5 - vendor/github.com/spf13/cobra/command_test.go | 1590 +---------------- vendor/github.com/spf13/cobra/command_win.go | 20 - vendor/github.com/spf13/cobra/doc/cmd_test.go | 86 - vendor/github.com/spf13/cobra/doc/man_docs.go | 236 --- vendor/github.com/spf13/cobra/doc/man_docs.md | 31 - .../spf13/cobra/doc/man_docs_test.go | 177 -- .../spf13/cobra/doc/man_examples_test.go | 35 - vendor/github.com/spf13/cobra/doc/md_docs.go | 159 -- .../spf13/cobra/doc/md_docs_test.go | 74 - .../github.com/spf13/cobra/doc/rest_docs.go | 185 -- .../github.com/spf13/cobra/doc/rest_docs.md | 114 -- .../spf13/cobra/doc/rest_docs_test.go | 76 - vendor/github.com/spf13/cobra/doc/util.go | 51 - .../github.com/spf13/cobra/doc/yaml_docs.go | 169 -- .../github.com/spf13/cobra/doc/yaml_docs.md | 112 -- .../spf13/cobra/doc/yaml_docs_test.go | 74 - vendor/github.com/spf13/cobra/md_docs.go | 138 ++ .../spf13/cobra/{doc => }/md_docs.md | 54 +- vendor/github.com/spf13/cobra/md_docs_test.go | 67 + .../github.com/spf13/cobra/zsh_completions.go | 126 -- .../spf13/cobra/zsh_completions_test.go | 89 - vendor/github.com/spf13/pflag/.gitignore | 2 - vendor/github.com/spf13/pflag/.travis.yml | 19 +- vendor/github.com/spf13/pflag/README.md | 80 +- vendor/github.com/spf13/pflag/bool.go | 15 +- vendor/github.com/spf13/pflag/bool_slice.go | 147 -- .../github.com/spf13/pflag/bool_slice_test.go | 215 --- vendor/github.com/spf13/pflag/bool_test.go | 7 +- vendor/github.com/spf13/pflag/bytes.go | 105 -- vendor/github.com/spf13/pflag/bytes_test.go | 72 - vendor/github.com/spf13/pflag/count.go | 34 +- vendor/github.com/spf13/pflag/count_test.go | 9 +- vendor/github.com/spf13/pflag/duration.go | 8 +- .../github.com/spf13/pflag/duration_slice.go | 128 -- .../spf13/pflag/duration_slice_test.go | 165 -- vendor/github.com/spf13/pflag/example_test.go | 79 +- vendor/github.com/spf13/pflag/flag.go | 865 +++------ vendor/github.com/spf13/pflag/flag_test.go | 512 +----- vendor/github.com/spf13/pflag/float32.go | 15 +- vendor/github.com/spf13/pflag/float64.go | 15 +- vendor/github.com/spf13/pflag/golangflag.go | 105 -- .../github.com/spf13/pflag/golangflag_test.go | 47 - vendor/github.com/spf13/pflag/int.go | 15 +- vendor/github.com/spf13/pflag/int16.go | 88 - vendor/github.com/spf13/pflag/int32.go | 15 +- vendor/github.com/spf13/pflag/int64.go | 15 +- vendor/github.com/spf13/pflag/int8.go | 15 +- vendor/github.com/spf13/pflag/int_slice.go | 12 +- .../github.com/spf13/pflag/int_slice_test.go | 13 +- vendor/github.com/spf13/pflag/ip.go | 10 +- vendor/github.com/spf13/pflag/ip_slice.go | 148 -- .../github.com/spf13/pflag/ip_slice_test.go | 222 --- vendor/github.com/spf13/pflag/ipmask.go | 10 +- vendor/github.com/spf13/pflag/ipnet.go | 24 +- .../github.com/spf13/pflag/printusage_test.go | 74 - vendor/github.com/spf13/pflag/string.go | 12 +- vendor/github.com/spf13/pflag/string_array.go | 103 -- .../spf13/pflag/string_array_test.go | 233 --- vendor/github.com/spf13/pflag/string_slice.go | 72 +- .../spf13/pflag/string_slice_test.go | 112 -- vendor/github.com/spf13/pflag/uint.go | 15 +- vendor/github.com/spf13/pflag/uint16.go | 17 +- vendor/github.com/spf13/pflag/uint32.go | 19 +- vendor/github.com/spf13/pflag/uint64.go | 15 +- vendor/github.com/spf13/pflag/uint8.go | 15 +- vendor/github.com/spf13/pflag/uint_slice.go | 126 -- .../github.com/spf13/pflag/uint_slice_test.go | 161 -- vendor/github.com/spf13/pflag/verify/all.sh | 69 - vendor/github.com/spf13/pflag/verify/gofmt.sh | 19 - .../github.com/spf13/pflag/verify/golint.sh | 15 - 110 files changed, 2619 insertions(+), 13960 deletions(-) delete mode 100644 vendor/github.com/spf13/cobra/.circleci/config.yml delete mode 100644 vendor/github.com/spf13/cobra/.mailmap delete mode 100644 vendor/github.com/spf13/cobra/args.go delete mode 100644 vendor/github.com/spf13/cobra/args_test.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/README.md delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/add.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/add_test.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/golden_test.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/helpers.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/init.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/init_test.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_agpl.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_apache_2.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_2.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_3.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_2.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_3.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_lgpl.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/license_mit.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/licenses.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/project.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/project_test.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/root.go delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/testdata/LICENSE.golden delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/testdata/main.go.golden delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden delete mode 100644 vendor/github.com/spf13/cobra/cobra/cmd/testdata/test.go.golden delete mode 100644 vendor/github.com/spf13/cobra/cobra/main.go delete mode 100644 vendor/github.com/spf13/cobra/command_notwin.go delete mode 100644 vendor/github.com/spf13/cobra/command_win.go delete mode 100644 vendor/github.com/spf13/cobra/doc/cmd_test.go delete mode 100644 vendor/github.com/spf13/cobra/doc/man_docs.go delete mode 100644 vendor/github.com/spf13/cobra/doc/man_docs.md delete mode 100644 vendor/github.com/spf13/cobra/doc/man_docs_test.go delete mode 100644 vendor/github.com/spf13/cobra/doc/man_examples_test.go delete mode 100644 vendor/github.com/spf13/cobra/doc/md_docs.go delete mode 100644 vendor/github.com/spf13/cobra/doc/md_docs_test.go delete mode 100644 vendor/github.com/spf13/cobra/doc/rest_docs.go delete mode 100644 vendor/github.com/spf13/cobra/doc/rest_docs.md delete mode 100644 vendor/github.com/spf13/cobra/doc/rest_docs_test.go delete mode 100644 vendor/github.com/spf13/cobra/doc/util.go delete mode 100644 vendor/github.com/spf13/cobra/doc/yaml_docs.go delete mode 100644 vendor/github.com/spf13/cobra/doc/yaml_docs.md delete mode 100644 vendor/github.com/spf13/cobra/doc/yaml_docs_test.go create mode 100644 vendor/github.com/spf13/cobra/md_docs.go rename vendor/github.com/spf13/cobra/{doc => }/md_docs.md (69%) create mode 100644 vendor/github.com/spf13/cobra/md_docs_test.go delete mode 100644 vendor/github.com/spf13/cobra/zsh_completions.go delete mode 100644 vendor/github.com/spf13/cobra/zsh_completions_test.go delete mode 100644 vendor/github.com/spf13/pflag/.gitignore delete mode 100644 vendor/github.com/spf13/pflag/bool_slice.go delete mode 100644 vendor/github.com/spf13/pflag/bool_slice_test.go delete mode 100644 vendor/github.com/spf13/pflag/bytes.go delete mode 100644 vendor/github.com/spf13/pflag/bytes_test.go delete mode 100644 vendor/github.com/spf13/pflag/duration_slice.go delete mode 100644 vendor/github.com/spf13/pflag/duration_slice_test.go delete mode 100644 vendor/github.com/spf13/pflag/golangflag.go delete mode 100644 vendor/github.com/spf13/pflag/golangflag_test.go delete mode 100644 vendor/github.com/spf13/pflag/int16.go delete mode 100644 vendor/github.com/spf13/pflag/ip_slice.go delete mode 100644 vendor/github.com/spf13/pflag/ip_slice_test.go delete mode 100644 vendor/github.com/spf13/pflag/printusage_test.go delete mode 100644 vendor/github.com/spf13/pflag/string_array.go delete mode 100644 vendor/github.com/spf13/pflag/string_array_test.go delete mode 100644 vendor/github.com/spf13/pflag/uint_slice.go delete mode 100644 vendor/github.com/spf13/pflag/uint_slice_test.go delete mode 100755 vendor/github.com/spf13/pflag/verify/all.sh delete mode 100755 vendor/github.com/spf13/pflag/verify/gofmt.sh delete mode 100755 vendor/github.com/spf13/pflag/verify/golint.sh diff --git a/glide.lock b/glide.lock index 02260093..a4cb1f48 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ -hash: 64732f6923719298bded0fd2aa6be97f2028aec75dd989a64021702474894849 -updated: 2018-04-12T11:45:29.473389-07:00 +hash: bad2138ca7787101a7a23af2464319cc580f4285e90c07d11eb9f90ad3bb9604 +updated: 2018-02-27T14:39:39.133796-08:00 imports: - name: github.com/alexbrainman/sspi version: 4729b3d4d8581b2db83864d1018926e4154f9406 @@ -30,9 +30,9 @@ imports: - name: github.com/rubyist/tracerx version: 787959303086f44a8c361240dfac53d3e9d53ed2 - name: github.com/spf13/cobra - version: a1f051bc3eba734da4772d60e2d677f47cf93ef4 + version: c55cdf33856a08e4822738728b41783292812889 - name: github.com/spf13/pflag - version: 583c0c0531f06d5278b7d917446061adc344b5cd + version: 580b9be06c33d8ba9dcc8757ea56b7642472c2f5 - name: github.com/stretchr/testify version: 6cb3b85ef5a0efef77caef88363ec4d4b5c0976d subpackages: diff --git a/glide.yaml b/glide.yaml index d2686c8c..eee8a77a 100644 --- a/glide.yaml +++ b/glide.yaml @@ -13,9 +13,9 @@ import: - package: github.com/rubyist/tracerx version: 787959303086f44a8c361240dfac53d3e9d53ed2 - package: github.com/spf13/cobra - version: a1f051bc3eba734da4772d60e2d677f47cf93ef4 + version: c55cdf33856a08e4822738728b41783292812889 - package: github.com/spf13/pflag - version: 583c0c0531f06d5278b7d917446061adc344b5cd + version: 580b9be06c33d8ba9dcc8757ea56b7642472c2f5 - package: github.com/stretchr/testify version: 6cb3b85ef5a0efef77caef88363ec4d4b5c0976d - package: github.com/ThomsonReutersEikon/go-ntlm diff --git a/vendor/github.com/spf13/cobra/.circleci/config.yml b/vendor/github.com/spf13/cobra/.circleci/config.yml deleted file mode 100644 index bbba32b7..00000000 --- a/vendor/github.com/spf13/cobra/.circleci/config.yml +++ /dev/null @@ -1,38 +0,0 @@ -workflows: - version: 2 - main: - jobs: - - go-current - - go-previous - - go-latest -base: &base - working_directory: /go/src/github.com/spf13/cobra - steps: - - checkout - - run: - name: "All Commands" - command: | - mkdir -p bin - curl -Lso bin/shellcheck https://github.com/caarlos0/shellcheck-docker/releases/download/v0.4.3/shellcheck - chmod +x bin/shellcheck - go get -t -v ./... - PATH=$PATH:$PWD/bin go test -v ./... - go build - diff -u <(echo -n) <(gofmt -d -s .) - if [ -z $NOVET ]; then - diff -u <(echo -n) <(go tool vet . 2>&1 | grep -vE 'ExampleCommand|bash_completions.*Fprint'); - fi -version: 2 -jobs: - go-current: - docker: - - image: circleci/golang:1.10.0 - <<: *base - go-previous: - docker: - - image: circleci/golang:1.9.4 - <<: *base - go-latest: - docker: - - image: circleci/golang:latest - <<: *base diff --git a/vendor/github.com/spf13/cobra/.gitignore b/vendor/github.com/spf13/cobra/.gitignore index 1b8c7c26..36d1a84d 100644 --- a/vendor/github.com/spf13/cobra/.gitignore +++ b/vendor/github.com/spf13/cobra/.gitignore @@ -19,18 +19,6 @@ _cgo_export.* _testmain.go -# Vim files https://github.com/github/gitignore/blob/master/Global/Vim.gitignore -# swap -[._]*.s[a-w][a-z] -[._]s[a-w][a-z] -# session -Session.vim -# temporary -.netrwhist -*~ -# auto-generated tag files -tags - *.exe cobra.test diff --git a/vendor/github.com/spf13/cobra/.mailmap b/vendor/github.com/spf13/cobra/.mailmap deleted file mode 100644 index 94ec5306..00000000 --- a/vendor/github.com/spf13/cobra/.mailmap +++ /dev/null @@ -1,3 +0,0 @@ -Steve Francia -Bjørn Erik Pedersen -Fabiano Franz diff --git a/vendor/github.com/spf13/cobra/.travis.yml b/vendor/github.com/spf13/cobra/.travis.yml index 5afcb209..dc43afd6 100644 --- a/vendor/github.com/spf13/cobra/.travis.yml +++ b/vendor/github.com/spf13/cobra/.travis.yml @@ -1,21 +1,8 @@ language: go - -matrix: - include: - - go: 1.9.4 - - go: 1.10.0 - - go: tip - allow_failures: - - go: tip - -before_install: - - mkdir -p bin - - curl -Lso bin/shellcheck https://github.com/caarlos0/shellcheck-docker/releases/download/v0.4.3/shellcheck - - chmod +x bin/shellcheck +go: + - 1.3 + - 1.4.2 + - tip script: - - PATH=$PATH:$PWD/bin go test -v ./... + - go test ./... - go build - - diff -u <(echo -n) <(gofmt -d -s .) - - if [ -z $NOVET ]; then - diff -u <(echo -n) <(go tool vet . 2>&1 | grep -vE 'ExampleCommand|bash_completions.*Fprint'); - fi diff --git a/vendor/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md index 851fcc08..b1fb0889 100644 --- a/vendor/github.com/spf13/cobra/README.md +++ b/vendor/github.com/spf13/cobra/README.md @@ -1,315 +1,122 @@ -![cobra logo](https://cloud.githubusercontent.com/assets/173412/10886352/ad566232-814f-11e5-9cd0-aa101788c117.png) +# Cobra -Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files. +A Commander for modern go CLI interactions -Many of the most widely used Go projects are built using Cobra including: +[![Build Status](https://travis-ci.org/spf13/cobra.svg)](https://travis-ci.org/spf13/cobra) -* [Kubernetes](http://kubernetes.io/) -* [Hugo](http://gohugo.io) -* [rkt](https://github.com/coreos/rkt) -* [etcd](https://github.com/coreos/etcd) -* [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) -* [GopherJS](http://www.gopherjs.org/) -* [CockroachDB](http://www.cockroachlabs.com/) -* [Bleve](http://www.blevesearch.com/) -* [ProjectAtomic (enterprise)](http://www.projectatomic.io/) -* [GiantSwarm's swarm](https://github.com/giantswarm/cli) -* [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack) -* [rclone](http://rclone.org/) -* [nehm](https://github.com/bogem/nehm) -* [Pouch](https://github.com/alibaba/pouch) +## Overview -[![Build Status](https://travis-ci.org/spf13/cobra.svg "Travis CI status")](https://travis-ci.org/spf13/cobra) -[![CircleCI status](https://circleci.com/gh/spf13/cobra.png?circle-token=:circle-token "CircleCI status")](https://circleci.com/gh/spf13/cobra) -[![GoDoc](https://godoc.org/github.com/spf13/cobra?status.svg)](https://godoc.org/github.com/spf13/cobra) +Cobra is a commander providing a simple interface to create powerful modern CLI +interfaces similar to git & go tools. In addition to providing an interface, Cobra +simultaneously provides a controller to organize your application code. -# Table of Contents +Inspired by go, go-Commander, gh and subcommand, Cobra improves on these by +providing **fully posix compliant flags** (including short & long versions), +**nesting commands**, and the ability to **define your own help and usage** for any or +all commands. -- [Overview](#overview) -- [Concepts](#concepts) - * [Commands](#commands) - * [Flags](#flags) -- [Installing](#installing) -- [Getting Started](#getting-started) - * [Using the Cobra Generator](#using-the-cobra-generator) - * [Using the Cobra Library](#using-the-cobra-library) - * [Working with Flags](#working-with-flags) - * [Positional and Custom Arguments](#positional-and-custom-arguments) - * [Example](#example) - * [Help Command](#help-command) - * [Usage Message](#usage-message) - * [PreRun and PostRun Hooks](#prerun-and-postrun-hooks) - * [Suggestions when "unknown command" happens](#suggestions-when-unknown-command-happens) - * [Generating documentation for your command](#generating-documentation-for-your-command) - * [Generating bash completions](#generating-bash-completions) -- [Contributing](#contributing) -- [License](#license) +Cobra has an exceptionally clean interface and simple design without needless +constructors or initialization methods. -# Overview +Applications built with Cobra commands are designed to be as user friendly as +possible. Flags can be placed before or after the command (as long as a +confusing space isn’t provided). Both short and long flags can be used. A +command need not even be fully typed. The shortest unambiguous string will +suffice. Help is automatically generated and available for the application or +for a specific command using either the help command or the --help flag. -Cobra is a library providing a simple interface to create powerful modern CLI -interfaces similar to git & go tools. +## Concepts -Cobra is also an application that will generate your application scaffolding to rapidly -develop a Cobra-based application. +Cobra is built on a structure of commands & flags. -Cobra provides: -* Easy subcommand-based CLIs: `app server`, `app fetch`, etc. -* Fully POSIX-compliant flags (including short & long versions) -* Nested subcommands -* Global, local and cascading flags -* Easy generation of applications & commands with `cobra init appname` & `cobra add cmdname` -* Intelligent suggestions (`app srver`... did you mean `app server`?) -* Automatic help generation for commands and flags -* Automatic help flag recognition of `-h`, `--help`, etc. -* 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 flexibility to define your own help, usage, etc. -* Optional tight integration with [viper](http://github.com/spf13/viper) for 12-factor apps +**Commands** represent actions and **Flags** are modifiers for those actions. -# Concepts - -Cobra is built on a structure of commands, arguments & flags. - -**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions. - -The best applications will read like sentences when used. Users will know how -to use the application because they will natively understand how to use it. - -The pattern to follow is -`APPNAME VERB NOUN --ADJECTIVE.` - or -`APPNAME COMMAND ARG --FLAG` - -A few good real world examples may better illustrate this point. - -In the following example, 'server' is a command, and 'port' is a flag: +In the following example 'server' is a command and 'port' is a flag. hugo server --port=1313 -In this command we are telling Git to clone the url bare. - - git clone URL --bare - -## Commands +### Commands Command is the central point of the application. Each interaction that the application supports will be contained in a Command. A command can have children commands and optionally run an action. -In the example above, 'server' is the command. +In the example above 'server' is the command -[More about cobra.Command](https://godoc.org/github.com/spf13/cobra#Command) +A Command has the following structure: -## Flags + type Command struct { + Use string // The one-line usage message. + Short string // The short description shown in the 'help' output. + Long string // The long message shown in the 'help ' output. + Run func(cmd *Command, args []string) // Run runs the command. + } -A flag is a way to modify the behavior of a command. Cobra supports -fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/). +### Flags + +A Flag is a way to modify the behavior of an command. Cobra supports +fully posix compliant flags as well as the go flag package. A Cobra command can define flags that persist through to children commands and flags that are only available to that command. -In the example above, 'port' is the flag. +In the example above 'port' is the flag. Flag functionality is provided by the [pflag -library](https://github.com/spf13/pflag), a fork of the flag standard library -which maintains the same interface while adding POSIX compliance. +library](https://github.com/ogier/pflag), a fork of the flag standard library +which maintains the same interface while adding posix compliance. -# Installing -Using Cobra is easy. First, use `go get` to install the latest version -of the library. This command will install the `cobra` generator executable -along with the library and its dependencies: +## Usage - go get -u github.com/spf13/cobra/cobra +Cobra works by creating a set of commands and then organizing them into a tree. +The tree defines the structure of the application. -Next, include Cobra in your application: +Once each command is defined with it's corresponding flags, then the +tree is assigned to the commander which is finally executed. -```go -import "github.com/spf13/cobra" -``` +### Installing +Using Cobra is easy. First use go get to install the latest version +of the library. -# Getting Started + $ go get github.com/spf13/cobra -While you are welcome to provide your own organization, typically a Cobra-based -application will follow the following organizational structure: +Next include cobra in your application. -``` - ▾ appName/ - ▾ cmd/ - add.go - your.go - commands.go - here.go - main.go -``` + import "github.com/spf13/cobra" -In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra. +### Create the root command -```go -package main - -import ( - "fmt" - "os" - - "{pathToYourApp}/cmd" -) - -func main() { - cmd.Execute() -} -``` - -## Using the Cobra Generator - -Cobra provides its own program that will create your application and add any -commands you want. It's the easiest way to incorporate Cobra into your application. - -[Here](https://github.com/spf13/cobra/blob/master/cobra/README.md) you can find more information about it. - -## Using the Cobra Library - -To manually implement Cobra you need to create a bare main.go file and a rootCmd file. -You will optionally provide additional commands as you see fit. - -### Create rootCmd +The root command represents your binary itself. Cobra doesn't require any special constructors. Simply create your commands. -Ideally you place this in app/cmd/root.go: - -```go -var rootCmd = &cobra.Command{ - Use: "hugo", - Short: "Hugo is a very fast static site generator", - Long: `A Fast and Flexible Static Site Generator built with + var HugoCmd = &cobra.Command{ + Use: "hugo", + Short: "Hugo is a very fast static site generator", + Long: `A Fast and Flexible Static Site Generator built with love by spf13 and friends in Go. Complete documentation is available at http://hugo.spf13.com`, - Run: func(cmd *cobra.Command, args []string) { - // Do Stuff Here - }, -} - -func Execute() { - if err := rootCmd.Execute(); err != nil { - fmt.Println(err) - os.Exit(1) - } -} -``` - -You will additionally define flags and handle configuration in your init() function. - -For example cmd/root.go: - -```go -import ( - "fmt" - "os" - - homedir "github.com/mitchellh/go-homedir" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -func init() { - cobra.OnInitialize(initConfig) - rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") - rootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory eg. 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 `licensetext` 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 ") - viper.SetDefault("license", "apache") -} - -func initConfig() { - // Don't forget to read config either from cfgFile or from home directory! - if cfgFile != "" { - // Use config file from the flag. - viper.SetConfigFile(cfgFile) - } else { - // Find home directory. - home, err := homedir.Dir() - if err != nil { - fmt.Println(err) - os.Exit(1) + Run: func(cmd *cobra.Command, args []string) { + // Do Stuff Here + }, } - // Search config in home directory with name ".cobra" (without extension). - viper.AddConfigPath(home) - viper.SetConfigName(".cobra") - } - - if err := viper.ReadInConfig(); err != nil { - fmt.Println("Can't read config:", err) - os.Exit(1) - } -} -``` - -### Create your main.go - -With the root command you need to have your main function execute it. -Execute should be run on the root for clarity, though it can be called on any command. - -In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra. - -```go -package main - -import ( - "fmt" - "os" - - "{pathToYourApp}/cmd" -) - -func main() { - cmd.Execute() -} -``` - ### Create additional commands -Additional commands can be defined and typically are each given their own file -inside of the cmd/ directory. +Additional commands can be defined. -If you wanted to create a version command you would create cmd/version.go and -populate it with the following: + var versionCmd = &cobra.Command{ + Use: "version", + Short: "Print the version number of Hugo", + Long: `All software has versions. This is Hugo's`, + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("Hugo Static Site Generator v0.9 -- HEAD") + }, + } -```go -package cmd +### Attach command to its parent +In this example we are attaching it to the root, but commands can be attached at any level. -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func init() { - rootCmd.AddCommand(versionCmd) -} - -var versionCmd = &cobra.Command{ - Use: "version", - Short: "Print the version number of Hugo", - Long: `All software has versions. This is Hugo's`, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hugo Static Site Generator v0.9 -- HEAD") - }, -} -``` - -## Working with Flags - -Flags provide modifiers to control how the action command operates. + HugoCmd.AddCommand(versionCmd) ### Assign flags to a command @@ -317,109 +124,43 @@ Since the flags are defined and used in different locations, we need to define a variable outside with the correct scope to assign the flag to work with. -```go -var Verbose bool -var Source string -``` + var Verbose bool + var Source string There are two different approaches to assign a flag. -### Persistent Flags +#### Persistent Flags A flag can be 'persistent' meaning that this flag will be available to the command it's assigned to as well as every command under that command. For -global flags, assign a flag as a persistent flag on the root. +global flags assign a flag as a persistent flag on the root. -```go -rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") -``` + HugoCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") -### Local Flags +#### Local Flags A flag can also be assigned locally which will only apply to that specific command. -```go -rootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from") -``` + HugoCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from") -### Local Flag on Parent Commands +### Remove a command from its parent -By default Cobra only parses local flags on the target command, any local flags on -parent commands are ignored. By enabling `Command.TraverseChildren` Cobra will -parse local flags on each command before executing the target command. +Removing a command is not a common action in simple programs but it allows 3rd parties to customize an existing command tree. -```go -command := cobra.Command{ - Use: "print [OPTIONS] [COMMANDS]", - TraverseChildren: true, -} -``` +In this example, we remove the existing `VersionCmd` command of an existing root command, and we replace it by our own version. -### Bind Flags with Config + mainlib.RootCmd.RemoveCommand(mainlib.VersionCmd) + mainlib.RootCmd.AddCommand(versionCmd) -You can also bind your flags with [viper](https://github.com/spf13/viper): -```go -var author string +### Once all commands and flags are defined, Execute the commands -func init() { - rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution") - viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) -} -``` +Execute should be run on the root for clarity, though it can be called on any command. -In this example the persistent flag `author` is bound with `viper`. -**Note**, that the variable `author` will not be set to the value from config, -when the `--author` flag is not provided by user. - -More in [viper documentation](https://github.com/spf13/viper#working-with-flags). - -### Required flags - -Flags are optional by default. If instead you wish your command to report an error -when a flag has not been set, mark it as required: -```go -rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)") -rootCmd.MarkFlagRequired("region") -``` - -## Positional and Custom Arguments - -Validation of positional arguments can be specified using the `Args` field -of `Command`. - -The following validators are built in: - -- `NoArgs` - the command will report an error if there are any positional args. -- `ArbitraryArgs` - the command will accept any args. -- `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the `ValidArgs` field of `Command`. -- `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args. -- `MaximumNArgs(int)` - the command will report an error if there are more than N positional args. -- `ExactArgs(int)` - the command will report an error if there are not exactly N positional args. -- `RangeArgs(min, max)` - the command will report an error if the number of args is not between the minimum and maximum number of expected args. - -An example of setting the custom validator: - -```go -var cmd = &cobra.Command{ - Short: "hello", - Args: func(cmd *cobra.Command, args []string) error { - if len(args) < 1 { - return errors.New("requires at least one arg") - } - if myapp.IsValidColor(args[0]) { - return nil - } - return fmt.Errorf("invalid color specified: %s", args[0]) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hello, World!") - }, -} -``` + HugoCmd.Execute() ## Example -In the example below, we have defined three commands. Two are at the top level +In the example below we have defined three commands. Two are at the top level and one (cmdTimes) is a child of one of the top commands. In this case the root is not executable meaning that a subcommand is required. This is accomplished by not providing a 'Run' for the 'rootCmd'. @@ -428,309 +169,317 @@ We have only defined one flag for a single command. More documentation about flags is available at https://github.com/spf13/pflag -```go -package main + import( + "github.com/spf13/cobra" + "fmt" + "strings" + ) -import ( - "fmt" - "strings" + func main() { - "github.com/spf13/cobra" -) + var echoTimes int -func main() { - var echoTimes int + var cmdPrint = &cobra.Command{ + Use: "print [string to print]", + Short: "Print anything to the screen", + Long: `print is for printing anything back to the screen. + For many years people have printed back to the screen. + `, + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("Print: " + strings.Join(args, " ")) + }, + } - var cmdPrint = &cobra.Command{ - Use: "print [string to print]", - Short: "Print anything to the screen", - Long: `print is for printing anything back to the screen. -For many years people have printed back to the screen.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Print: " + strings.Join(args, " ")) - }, - } + var cmdEcho = &cobra.Command{ + Use: "echo [string to echo]", + Short: "Echo anything to the screen", + Long: `echo is for echoing anything back. + Echo works a lot like print, except it has a child command. + `, + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("Print: " + strings.Join(args, " ")) + }, + } - var cmdEcho = &cobra.Command{ - Use: "echo [string to echo]", - Short: "Echo anything to the screen", - Long: `echo is for echoing anything back. -Echo works a lot like print, except it has a child command.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Print: " + strings.Join(args, " ")) - }, - } + var cmdTimes = &cobra.Command{ + Use: "times [# times] [string to echo]", + Short: "Echo anything to the screen more times", + Long: `echo things multiple times back to the user by providing + a count and a string.`, + Run: func(cmd *cobra.Command, args []string) { + for i:=0; i < echoTimes; i++ { + fmt.Println("Echo: " + strings.Join(args, " ")) + } + }, + } - var cmdTimes = &cobra.Command{ - Use: "times [# times] [string to echo]", - Short: "Echo anything to the screen more times", - Long: `echo things multiple times back to the user by providing -a count and a string.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - for i := 0; i < echoTimes; i++ { - fmt.Println("Echo: " + strings.Join(args, " ")) - } - }, - } + cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") - cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") + var rootCmd = &cobra.Command{Use: "app"} + rootCmd.AddCommand(cmdPrint, cmdEcho) + cmdEcho.AddCommand(cmdTimes) + rootCmd.Execute() + } - var rootCmd = &cobra.Command{Use: "app"} - rootCmd.AddCommand(cmdPrint, cmdEcho) - cmdEcho.AddCommand(cmdTimes) - rootCmd.Execute() -} -``` +For a more complete example of a larger application, please checkout [Hugo](http://hugo.spf13.com) -For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/). - -## Help Command +## The Help Command Cobra automatically adds a help command to your application when you have subcommands. -This will be called when a user runs 'app help'. Additionally, help will also -support all other commands as input. Say, for instance, you have a command called -'create' without any additional configuration; Cobra will work when 'app help +This will be called when a user runs 'app help'. Additionally help will also +support all other commands as input. Say for instance you have a command called +'create' without any additional configuration cobra will work when 'app help create' is called. Every command will automatically have the '--help' flag added. ### Example -The following output is automatically generated by Cobra. Nothing beyond the +The following output is automatically generated by cobra. Nothing beyond the command and flag definitions are needed. - $ cobra help + > hugo help - 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. + A Fast and Flexible Static Site Generator built with + love by spf13 and friends in Go. + + Complete documentation is available at http://hugo.spf13.com Usage: - cobra [command] + hugo [flags] + hugo [command] Available Commands: - add Add a command to a Cobra Application - help Help about any command - init Initialize a Cobra Application + server :: Hugo runs it's own a webserver to render the files + version :: Print the version number of Hugo + check :: Check content in the source directory + benchmark :: Benchmark hugo by building a site a number of times + help [command] :: Help about any command - Flags: - -a, --author string author name for copyright attribution (default "YOUR NAME") - --config string config file (default is $HOME/.cobra.yaml) - -h, --help help for cobra - -l, --license string name of license for the project - --viper use Viper for configuration (default true) + Available Flags: + -b, --base-url="": hostname (and path) to the root eg. http://spf13.com/ + -D, --build-drafts=false: include content marked as draft + --config="": config file (default is path/config.yaml|json|toml) + -d, --destination="": filesystem path to write files to + -s, --source="": filesystem path to read files relative from + --stepAnalysis=false: display memory and timing of different steps of the program + --uglyurls=false: if true, use /filename.html instead of /filename/ + -v, --verbose=false: verbose output + -w, --watch=false: watch filesystem for changes and recreate as needed + + Use "hugo help [command]" for more information about that command. - Use "cobra [command] --help" for more information about a command. Help is just a command like any other. There is no special logic or behavior -around it. In fact, you can provide your own if you want. +around it. In fact you can provide your own if you want. ### Defining your own help -You can provide your own Help command or your own template for the default command to use -with following functions: +You can provide your own Help command or you own template for the default command to use. -```go -cmd.SetHelpCommand(cmd *Command) -cmd.SetHelpFunc(f func(*Command, []string)) -cmd.SetHelpTemplate(s string) -``` +The default help command is + + func (c *Command) initHelp() { + if c.helpCommand == nil { + 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.`, + Run: c.HelpFunc(), + } + } + c.AddCommand(c.helpCommand) + } + +You can provide your own command, function or template through the following methods. + + command.SetHelpCommand(cmd *Command) + + command.SetHelpFunc(f func(*Command, []string)) + + command.SetHelpTemplate(s string) The latter two will also apply to any children commands. -## Usage Message +## Usage -When the user provides an invalid flag or invalid command, Cobra responds by -showing the user the 'usage'. +When the user provides an invalid flag or invalid command Cobra responds by +showing the user the 'usage' ### Example You may recognize this from the help above. That's because the default help -embeds the usage as part of its output. +embeds the usage as part of it's output. - $ cobra --invalid - Error: unknown flag: --invalid Usage: - cobra [command] + hugo [flags] + hugo [command] Available Commands: - add Add a command to a Cobra Application - help Help about any command - init Initialize a Cobra Application + server Hugo runs it's own a webserver to render the files + version Print the version number of Hugo + check Check content in the source directory + benchmark Benchmark hugo by building a site a number of times + help [command] Help about any command - Flags: - -a, --author string author name for copyright attribution (default "YOUR NAME") - --config string config file (default is $HOME/.cobra.yaml) - -h, --help help for cobra - -l, --license string name of license for the project - --viper use Viper for configuration (default true) - - Use "cobra [command] --help" for more information about a command. + Available Flags: + -b, --base-url="": hostname (and path) to the root eg. http://spf13.com/ + -D, --build-drafts=false: include content marked as draft + --config="": config file (default is path/config.yaml|json|toml) + -d, --destination="": filesystem path to write files to + -s, --source="": filesystem path to read files relative from + --stepAnalysis=false: display memory and timing of different steps of the program + --uglyurls=false: if true, use /filename.html instead of /filename/ + -v, --verbose=false: verbose output + -w, --watch=false: watch filesystem for changes and recreate as needed ### Defining your own usage -You can provide your own usage function or template for Cobra to use. -Like help, the function and template are overridable through public methods: +You can provide your own usage function or template for cobra to use. -```go -cmd.SetUsageFunc(f func(*Command) error) -cmd.SetUsageTemplate(s string) -``` +The default usage function is -## Version Flag + return func(c *Command) error { + err := tmpl(c.Out(), c.UsageTemplate(), c) + return err + } -Cobra adds a top-level '--version' flag if the Version field is set on the root command. -Running an application with the '--version' flag will print the version to stdout using -the version template. The template can be customized using the -`cmd.SetVersionTemplate(s string)` function. +Like help the function and template are over ridable through public methods. -## PreRun and PostRun Hooks + command.SetUsageFunc(f func(*Command) error) -It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order: + command.SetUsageTemplate(s string) + +## PreRun or PostRun Hooks + +It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistendPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherrited by children if they do not declare their own. These function are run in the following order: - `PersistentPreRun` - `PreRun` - `Run` - `PostRun` -- `PersistentPostRun` +- `PersistenPostRun` -An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`: +And example of two commands which use all of these features is below. When the subcommand in executed it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun` ```go package main import ( - "fmt" + "fmt" - "github.com/spf13/cobra" + "github.com/spf13/cobra" ) func main() { - var rootCmd = &cobra.Command{ - Use: "root [sub]", - Short: "My root command", - PersistentPreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args) - }, - PreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PreRun with args: %v\n", args) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd Run with args: %v\n", args) - }, - PostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PostRun with args: %v\n", args) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args) - }, - } + var rootCmd = &cobra.Command{ + Use: "root [sub]", + Short: "My root command", + PersistentPreRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args) + }, + PreRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside rootCmd PreRun with args: %v\n", args) + }, + Run: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside rootCmd Run with args: %v\n", args) + }, + PostRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside rootCmd PostRun with args: %v\n", args) + }, + PersistentPostRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args) + }, + } - var subCmd = &cobra.Command{ - Use: "sub [no options!]", - Short: "My subcommand", - PreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PreRun with args: %v\n", args) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd Run with args: %v\n", args) - }, - PostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PostRun with args: %v\n", args) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args) - }, - } + var subCmd = &cobra.Command{ + Use: "sub [no options!]", + Short: "My sub command", + PreRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside subCmd PreRun with args: %v\n", args) + }, + Run: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside subCmd Run with args: %v\n", args) + }, + PostRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside subCmd PostRun with args: %v\n", args) + }, + PersistentPostRun: func(cmd *cobra.Command, args []string) { + fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args) + }, + } - rootCmd.AddCommand(subCmd) + rootCmd.AddCommand(subCmd) - rootCmd.SetArgs([]string{""}) - rootCmd.Execute() - fmt.Println() - rootCmd.SetArgs([]string{"sub", "arg1", "arg2"}) - rootCmd.Execute() + rootCmd.SetArgs([]string{""}) + _ = rootCmd.Execute() + fmt.Print("\n") + rootCmd.SetArgs([]string{"sub", "arg1", "arg2"}) + _ = rootCmd.Execute() } ``` -Output: -``` -Inside rootCmd PersistentPreRun with args: [] -Inside rootCmd PreRun with args: [] -Inside rootCmd Run with args: [] -Inside rootCmd PostRun with args: [] -Inside rootCmd PersistentPostRun with args: [] +## Generating markdown formatted documentation for your command -Inside rootCmd PersistentPreRun with args: [arg1 arg2] -Inside subCmd PreRun with args: [arg1 arg2] -Inside subCmd Run with args: [arg1 arg2] -Inside subCmd PostRun with args: [arg1 arg2] -Inside subCmd PersistentPostRun with args: [arg1 arg2] -``` +Cobra can generate a markdown formatted document based on the subcommands, flags, etc. A simple example of how to do this for your command can be found in [Markdown Docs](md_docs.md) -## Suggestions when "unknown command" happens +## Generating bash completions for your command -Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example: +Cobra can generate a bash completions file. If you add more information to your command these completions can be amazingly powerful and flexible. Read more about [Bash Completions](bash_completions.md) -``` -$ hugo srever -Error: unknown command "srever" for "hugo" +## Debugging -Did you mean this? - server +Cobra provides a ‘DebugFlags’ method on a command which when called will print +out everything Cobra knows about the flags for each command -Run 'hugo --help' for usage. -``` +### Example -Suggestions are automatic based on every subcommand registered and use an implementation of [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion. + command.DebugFlags() -If you need to disable suggestions or tweak the string distance in your command, use: +## 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 -```go -command.DisableSuggestions = true -``` +## ToDo +* Launch proper documentation site -or - -```go -command.SuggestionsMinimumDistance = 1 -``` - -You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but makes sense in your set of commands and for some which you don't want aliases. Example: - -``` -$ kubectl remove -Error: unknown command "remove" for "kubectl" - -Did you mean this? - delete - -Run 'kubectl help' for usage. -``` - -## Generating documentation for your command - -Cobra can generate documentation based on subcommands, flags, etc. in the following formats: - -- [Markdown](doc/md_docs.md) -- [ReStructured Text](doc/rest_docs.md) -- [Man Page](doc/man_docs.md) - -## Generating bash completions - -Cobra can generate a bash-completion file. If you add more information to your command, these completions can be amazingly powerful and flexible. Read more about it in [Bash Completions](bash_completions.md). - -# Contributing +## Contributing 1. Fork it -2. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`) -3. Create your feature branch (`git checkout -b my-new-feature`) -4. Make changes and add them (`git add .`) -5. Commit your changes (`git commit -m 'Add some feature'`) -6. Push to the branch (`git push origin my-new-feature`) -7. Create new pull request +2. Create your feature branch (`git checkout -b my-new-feature`) +3. Commit your changes (`git commit -am 'Add some feature'`) +4. Push to the branch (`git push origin my-new-feature`) +5. Create new Pull Request -# License +## Contributors + +Names in no particular order: + +* [spf13](https://github.com/spf13) + +## 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/vendor/github.com/spf13/cobra/args.go b/vendor/github.com/spf13/cobra/args.go deleted file mode 100644 index a5d8a927..00000000 --- a/vendor/github.com/spf13/cobra/args.go +++ /dev/null @@ -1,89 +0,0 @@ -package cobra - -import ( - "fmt" -) - -type PositionalArgs func(cmd *Command, args []string) error - -// Legacy arg validation has the following behaviour: -// - root commands with no subcommands can take arbitrary arguments -// - root commands with subcommands will do subcommand validity checking -// - subcommands will always accept arbitrary arguments -func legacyArgs(cmd *Command, args []string) error { - // no subcommand, always take args - if !cmd.HasSubCommands() { - return nil - } - - // root command with subcommands, do subcommand checking. - if !cmd.HasParent() && len(args) > 0 { - return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0])) - } - return nil -} - -// NoArgs returns an error if any args are included. -func NoArgs(cmd *Command, args []string) error { - if len(args) > 0 { - return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath()) - } - return nil -} - -// OnlyValidArgs returns an error if any args are not in the list of ValidArgs. -func OnlyValidArgs(cmd *Command, args []string) error { - if len(cmd.ValidArgs) > 0 { - for _, v := range args { - if !stringInSlice(v, cmd.ValidArgs) { - return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0])) - } - } - } - return nil -} - -// ArbitraryArgs never returns an error. -func ArbitraryArgs(cmd *Command, args []string) error { - return nil -} - -// MinimumNArgs returns an error if there is not at least N args. -func MinimumNArgs(n int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) < n { - return fmt.Errorf("requires at least %d arg(s), only received %d", n, len(args)) - } - return nil - } -} - -// MaximumNArgs returns an error if there are more than N args. -func MaximumNArgs(n int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) > n { - return fmt.Errorf("accepts at most %d arg(s), received %d", n, len(args)) - } - return nil - } -} - -// ExactArgs returns an error if there are not exactly n args. -func ExactArgs(n int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) != n { - return fmt.Errorf("accepts %d arg(s), received %d", n, len(args)) - } - return nil - } -} - -// RangeArgs returns an error if the number of args is not within the expected range. -func RangeArgs(min int, max int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) < min || len(args) > max { - return fmt.Errorf("accepts between %d and %d arg(s), received %d", min, max, len(args)) - } - return nil - } -} diff --git a/vendor/github.com/spf13/cobra/args_test.go b/vendor/github.com/spf13/cobra/args_test.go deleted file mode 100644 index d797b6f5..00000000 --- a/vendor/github.com/spf13/cobra/args_test.go +++ /dev/null @@ -1,241 +0,0 @@ -package cobra - -import ( - "strings" - "testing" -) - -func TestNoArgs(t *testing.T) { - c := &Command{Use: "c", Args: NoArgs, Run: emptyRun} - - output, err := executeCommand(c) - if output != "" { - t.Errorf("Unexpected string: %v", output) - } - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } -} - -func TestNoArgsWithArgs(t *testing.T) { - c := &Command{Use: "c", Args: NoArgs, Run: emptyRun} - - _, err := executeCommand(c, "illegal") - if err == nil { - t.Fatal("Expected an error") - } - - got := err.Error() - expected := `unknown command "illegal" for "c"` - if got != expected { - t.Errorf("Expected: %q, got: %q", expected, got) - } -} - -func TestOnlyValidArgs(t *testing.T) { - c := &Command{ - Use: "c", - Args: OnlyValidArgs, - ValidArgs: []string{"one", "two"}, - Run: emptyRun, - } - - output, err := executeCommand(c, "one", "two") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } -} - -func TestOnlyValidArgsWithInvalidArgs(t *testing.T) { - c := &Command{ - Use: "c", - Args: OnlyValidArgs, - ValidArgs: []string{"one", "two"}, - Run: emptyRun, - } - - _, err := executeCommand(c, "three") - if err == nil { - t.Fatal("Expected an error") - } - - got := err.Error() - expected := `invalid argument "three" for "c"` - if got != expected { - t.Errorf("Expected: %q, got: %q", expected, got) - } -} - -func TestArbitraryArgs(t *testing.T) { - c := &Command{Use: "c", Args: ArbitraryArgs, Run: emptyRun} - output, err := executeCommand(c, "a", "b") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } -} - -func TestMinimumNArgs(t *testing.T) { - c := &Command{Use: "c", Args: MinimumNArgs(2), Run: emptyRun} - output, err := executeCommand(c, "a", "b", "c") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } -} - -func TestMinimumNArgsWithLessArgs(t *testing.T) { - c := &Command{Use: "c", Args: MinimumNArgs(2), Run: emptyRun} - _, err := executeCommand(c, "a") - - if err == nil { - t.Fatal("Expected an error") - } - - got := err.Error() - expected := "requires at least 2 arg(s), only received 1" - if got != expected { - t.Fatalf("Expected %q, got %q", expected, got) - } -} - -func TestMaximumNArgs(t *testing.T) { - c := &Command{Use: "c", Args: MaximumNArgs(3), Run: emptyRun} - output, err := executeCommand(c, "a", "b") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } -} - -func TestMaximumNArgsWithMoreArgs(t *testing.T) { - c := &Command{Use: "c", Args: MaximumNArgs(2), Run: emptyRun} - _, err := executeCommand(c, "a", "b", "c") - - if err == nil { - t.Fatal("Expected an error") - } - - got := err.Error() - expected := "accepts at most 2 arg(s), received 3" - if got != expected { - t.Fatalf("Expected %q, got %q", expected, got) - } -} - -func TestExactArgs(t *testing.T) { - c := &Command{Use: "c", Args: ExactArgs(3), Run: emptyRun} - output, err := executeCommand(c, "a", "b", "c") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } -} - -func TestExactArgsWithInvalidCount(t *testing.T) { - c := &Command{Use: "c", Args: ExactArgs(2), Run: emptyRun} - _, err := executeCommand(c, "a", "b", "c") - - if err == nil { - t.Fatal("Expected an error") - } - - got := err.Error() - expected := "accepts 2 arg(s), received 3" - if got != expected { - t.Fatalf("Expected %q, got %q", expected, got) - } -} - -func TestRangeArgs(t *testing.T) { - c := &Command{Use: "c", Args: RangeArgs(2, 4), Run: emptyRun} - output, err := executeCommand(c, "a", "b", "c") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } -} - -func TestRangeArgsWithInvalidCount(t *testing.T) { - c := &Command{Use: "c", Args: RangeArgs(2, 4), Run: emptyRun} - _, err := executeCommand(c, "a") - - if err == nil { - t.Fatal("Expected an error") - } - - got := err.Error() - expected := "accepts between 2 and 4 arg(s), received 1" - if got != expected { - t.Fatalf("Expected %q, got %q", expected, got) - } -} - -func TestRootTakesNoArgs(t *testing.T) { - rootCmd := &Command{Use: "root", Run: emptyRun} - childCmd := &Command{Use: "child", Run: emptyRun} - rootCmd.AddCommand(childCmd) - - _, err := executeCommand(rootCmd, "illegal", "args") - if err == nil { - t.Fatal("Expected an error") - } - - got := err.Error() - expected := `unknown command "illegal" for "root"` - if !strings.Contains(got, expected) { - t.Errorf("expected %q, got %q", expected, got) - } -} - -func TestRootTakesArgs(t *testing.T) { - rootCmd := &Command{Use: "root", Args: ArbitraryArgs, Run: emptyRun} - childCmd := &Command{Use: "child", Run: emptyRun} - rootCmd.AddCommand(childCmd) - - _, err := executeCommand(rootCmd, "legal", "args") - if err != nil { - t.Errorf("Unexpected error: %v", err) - } -} - -func TestChildTakesNoArgs(t *testing.T) { - rootCmd := &Command{Use: "root", Run: emptyRun} - childCmd := &Command{Use: "child", Args: NoArgs, Run: emptyRun} - rootCmd.AddCommand(childCmd) - - _, err := executeCommand(rootCmd, "child", "illegal", "args") - if err == nil { - t.Fatal("Expected an error") - } - - got := err.Error() - expected := `unknown command "illegal" for "root child"` - if !strings.Contains(got, expected) { - t.Errorf("expected %q, got %q", expected, got) - } -} - -func TestChildTakesArgs(t *testing.T) { - rootCmd := &Command{Use: "root", Run: emptyRun} - childCmd := &Command{Use: "child", Args: ArbitraryArgs, Run: emptyRun} - rootCmd.AddCommand(childCmd) - - _, err := executeCommand(rootCmd, "child", "legal", "args") - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } -} diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go index 291eae7d..82c4274a 100644 --- a/vendor/github.com/spf13/cobra/bash_completions.go +++ b/vendor/github.com/spf13/cobra/bash_completions.go @@ -3,7 +3,6 @@ package cobra import ( "bytes" "fmt" - "io" "os" "sort" "strings" @@ -11,33 +10,24 @@ import ( "github.com/spf13/pflag" ) -// Annotations for Bash completion. const ( - BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extensions" - BashCompCustom = "cobra_annotation_bash_completion_custom" + BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extentions" BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag" BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir" ) -func writePreamble(buf *bytes.Buffer, name string) { - buf.WriteString(fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name)) - buf.WriteString(fmt.Sprintf(` -__%[1]s_debug() +func preamble(out *bytes.Buffer) { + fmt.Fprintf(out, `#!/bin/bash + + +__debug() { if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then echo "$*" >> "${BASH_COMP_DEBUG_FILE}" fi } -# Homebrew on Macs have version 1.3 of bash-completion which doesn't include -# _init_completion. This is a very minimal version of that function. -__%[1]s_init_completion() -{ - COMPREPLY=() - _get_comp_words_by_ref "$@" cur prev words cword -} - -__%[1]s_index_of_word() +__index_of_word() { local w word=$1 shift @@ -49,7 +39,7 @@ __%[1]s_index_of_word() index=-1 } -__%[1]s_contains_word() +__contains_word() { local w word=$1; shift for w in "$@"; do @@ -58,14 +48,12 @@ __%[1]s_contains_word() return 1 } -__%[1]s_handle_reply() +__handle_reply() { - __%[1]s_debug "${FUNCNAME[0]}" + __debug "${FUNCNAME}" case $cur in -*) - if [[ $(type -t compopt) = "builtin" ]]; then - compopt -o nospace - fi + compopt -o nospace local allflags if [ ${#must_have_one_flag[@]} -ne 0 ]; then allflags=("${must_have_one_flag[@]}") @@ -73,37 +61,14 @@ __%[1]s_handle_reply() allflags=("${flags[*]} ${two_word_flags[*]}") fi COMPREPLY=( $(compgen -W "${allflags[*]}" -- "$cur") ) - if [[ $(type -t compopt) = "builtin" ]]; then - [[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace - fi - - # complete after --flag=abc - if [[ $cur == *=* ]]; then - if [[ $(type -t compopt) = "builtin" ]]; then - compopt +o nospace - fi - - local index flag - flag="${cur%%=*}" - __%[1]s_index_of_word "${flag}" "${flags_with_completion[@]}" - COMPREPLY=() - if [[ ${index} -ge 0 ]]; then - PREFIX="" - cur="${cur#*=}" - ${flags_completion[${index}]} - if [ -n "${ZSH_VERSION}" ]; then - # zsh completion needs --flag= prefix - eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )" - fi - fi - fi + [[ $COMPREPLY == *= ]] || compopt +o nospace return 0; ;; esac # check if we are handling a flag with special work handling local index - __%[1]s_index_of_word "${prev}" "${flags_with_completion[@]}" + __index_of_word "${prev}" "${flags_with_completion[@]}" if [[ ${index} -ge 0 ]]; then ${flags_completion[${index}]} return @@ -115,85 +80,51 @@ __%[1]s_handle_reply() fi local completions - completions=("${commands[@]}") - if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then - completions=("${must_have_one_noun[@]}") - fi if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then - completions+=("${must_have_one_flag[@]}") + completions=("${must_have_one_flag[@]}") + elif [[ ${#must_have_one_noun[@]} -ne 0 ]]; then + completions=("${must_have_one_noun[@]}") + else + completions=("${commands[@]}") fi COMPREPLY=( $(compgen -W "${completions[*]}" -- "$cur") ) - if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then - COMPREPLY=( $(compgen -W "${noun_aliases[*]}" -- "$cur") ) - fi - if [[ ${#COMPREPLY[@]} -eq 0 ]]; then declare -F __custom_func >/dev/null && __custom_func fi - - # available in bash-completion >= 2, not always present on macOS - if declare -F __ltrim_colon_completions >/dev/null; then - __ltrim_colon_completions "$cur" - fi - - # If there is only 1 completion and it is a flag with an = it will be completed - # but we don't want a space after the = - if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then - compopt -o nospace - fi } # The arguments should be in the form "ext1|ext2|extn" -__%[1]s_handle_filename_extension_flag() +__handle_filename_extension_flag() { local ext="$1" _filedir "@(${ext})" } -__%[1]s_handle_subdirs_in_dir_flag() +__handle_subdirs_in_dir_flag() { local dir="$1" pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 } -__%[1]s_handle_flag() +__handle_flag() { - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" + __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}" # if a command required a flag, and we found it, unset must_have_one_flag() local flagname=${words[c]} - local flagvalue # if the word contained an = if [[ ${words[c]} == *"="* ]]; then - flagvalue=${flagname#*=} # take in as flagvalue after the = flagname=${flagname%%=*} # strip everything after the = flagname="${flagname}=" # but put the = back fi - __%[1]s_debug "${FUNCNAME[0]}: looking for ${flagname}" - if __%[1]s_contains_word "${flagname}" "${must_have_one_flag[@]}"; then + __debug "${FUNCNAME}: looking for ${flagname}" + if __contains_word "${flagname}" "${must_have_one_flag[@]}"; then must_have_one_flag=() fi - # if you set a flag which only applies to this command, don't show subcommands - if __%[1]s_contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then - commands=() - fi - - # keep flag value with flagname as flaghash - # flaghash variable is an associative array which is only supported in bash > 3. - if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then - if [ -n "${flagvalue}" ] ; then - flaghash[${flagname}]=${flagvalue} - elif [ -n "${words[ $((c+1)) ]}" ] ; then - flaghash[${flagname}]=${words[ $((c+1)) ]} - else - flaghash[${flagname}]="true" # pad "true" for bool flag - fi - fi - # skip the argument to a two word flag - if __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then + if __contains_word "${words[c]}" "${two_word_flags[@]}"; then c=$((c+1)) # if we are looking for a flags value, don't show commands if [[ $c -eq $cword ]]; then @@ -201,17 +132,16 @@ __%[1]s_handle_flag() fi fi + # skip the flag itself c=$((c+1)) } -__%[1]s_handle_noun() +__handle_noun() { - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" + __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}" - if __%[1]s_contains_word "${words[c]}" "${must_have_one_noun[@]}"; then - must_have_one_noun=() - elif __%[1]s_contains_word "${words[c]}" "${noun_aliases[@]}"; then + if __contains_word "${words[c]}" "${must_have_one_noun[@]}"; then must_have_one_noun=() fi @@ -219,327 +149,235 @@ __%[1]s_handle_noun() c=$((c+1)) } -__%[1]s_handle_command() +__handle_command() { - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" + __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}" local next_command if [[ -n ${last_command} ]]; then - next_command="_${last_command}_${words[c]//:/__}" + next_command="_${last_command}_${words[c]}" else - if [[ $c -eq 0 ]]; then - next_command="_%[1]s_root_command" - else - next_command="_${words[c]//:/__}" - fi + next_command="_${words[c]}" fi c=$((c+1)) - __%[1]s_debug "${FUNCNAME[0]}: looking for ${next_command}" - declare -F "$next_command" >/dev/null && $next_command + __debug "${FUNCNAME}: looking for ${next_command}" + declare -F $next_command >/dev/null && $next_command } -__%[1]s_handle_word() +__handle_word() { if [[ $c -ge $cword ]]; then - __%[1]s_handle_reply - return + __handle_reply + return fi - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" + __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}" if [[ "${words[c]}" == -* ]]; then - __%[1]s_handle_flag - elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then - __%[1]s_handle_command - elif [[ $c -eq 0 ]]; then - __%[1]s_handle_command + __handle_flag + elif __contains_word "${words[c]}" "${commands[@]}"; then + __handle_command else - __%[1]s_handle_noun + __handle_noun fi - __%[1]s_handle_word + __handle_word } -`, name)) +`) } -func writePostscript(buf *bytes.Buffer, name string) { - name = strings.Replace(name, ":", "__", -1) - buf.WriteString(fmt.Sprintf("__start_%s()\n", name)) - buf.WriteString(fmt.Sprintf(`{ +func postscript(out *bytes.Buffer, name string) { + fmt.Fprintf(out, "__start_%s()\n", name) + fmt.Fprintf(out, `{ local cur prev words cword - declare -A flaghash 2>/dev/null || : - if declare -F _init_completion >/dev/null 2>&1; then - _init_completion -s || return - else - __%[1]s_init_completion -n "=" || return - fi + _init_completion -s || return local c=0 local flags=() local two_word_flags=() - local local_nonpersistent_flags=() local flags_with_completion=() local flags_completion=() - local commands=("%[1]s") + local commands=("%s") local must_have_one_flag=() local must_have_one_noun=() local last_command local nouns=() - __%[1]s_handle_word + __handle_word } -`, 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)) - buf.WriteString("# ex: ts=4 sw=4 et filetype=sh\n") +`, name) + fmt.Fprintf(out, "complete -F __start_%s %s\n", name, name) + fmt.Fprintf(out, "# ex: ts=4 sw=4 et filetype=sh\n") } -func writeCommands(buf *bytes.Buffer, cmd *Command) { - buf.WriteString(" commands=()\n") +func writeCommands(cmd *Command, out *bytes.Buffer) { + fmt.Fprintf(out, " commands=()\n") for _, c := range cmd.Commands() { - if !c.IsAvailableCommand() || c == cmd.helpCommand { + if len(c.Deprecated) > 0 { continue } - buf.WriteString(fmt.Sprintf(" commands+=(%q)\n", c.Name())) + fmt.Fprintf(out, " commands+=(%q)\n", c.Name()) } - buf.WriteString("\n") + fmt.Fprintf(out, "\n") } -func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]string, cmd *Command) { +func writeFlagHandler(name string, annotations map[string][]string, out *bytes.Buffer) { for key, value := range annotations { switch key { case BashCompFilenameExt: - buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) + fmt.Fprintf(out, " flags_with_completion+=(%q)\n", name) - var ext string if len(value) > 0 { - ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Root().Name()) + strings.Join(value, "|") + ext := "__handle_filename_extension_flag " + strings.Join(value, "|") + fmt.Fprintf(out, " flags_completion+=(%q)\n", ext) } else { - ext = "_filedir" - } - buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext)) - case BashCompCustom: - buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) - if len(value) > 0 { - handlers := strings.Join(value, "; ") - buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", handlers)) - } else { - buf.WriteString(" flags_completion+=(:)\n") + ext := "_filedir" + fmt.Fprintf(out, " flags_completion+=(%q)\n", ext) } case BashCompSubdirsInDir: - buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) + fmt.Fprintf(out, " flags_with_completion+=(%q)\n", name) - var ext string if len(value) == 1 { - ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Root().Name()) + value[0] + ext := "__handle_subdirs_in_dir_flag " + value[0] + fmt.Fprintf(out, " flags_completion+=(%q)\n", ext) } else { - ext = "_filedir -d" + ext := "_filedir -d" + fmt.Fprintf(out, " flags_completion+=(%q)\n", ext) } - buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext)) } } } -func writeShortFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) { +func writeShortFlag(flag *pflag.Flag, out *bytes.Buffer) { + b := (flag.Value.Type() == "bool") name := flag.Shorthand format := " " - if len(flag.NoOptDefVal) == 0 { + if !b { format += "two_word_" } format += "flags+=(\"-%s\")\n" - buf.WriteString(fmt.Sprintf(format, name)) - writeFlagHandler(buf, "-"+name, flag.Annotations, cmd) + fmt.Fprintf(out, format, name) + writeFlagHandler("-"+name, flag.Annotations, out) } -func writeFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) { +func writeFlag(flag *pflag.Flag, out *bytes.Buffer) { + b := (flag.Value.Type() == "bool") name := flag.Name format := " flags+=(\"--%s" - if len(flag.NoOptDefVal) == 0 { + if !b { format += "=" } format += "\")\n" - buf.WriteString(fmt.Sprintf(format, name)) - writeFlagHandler(buf, "--"+name, flag.Annotations, cmd) + fmt.Fprintf(out, format, name) + writeFlagHandler("--"+name, flag.Annotations, out) } -func writeLocalNonPersistentFlag(buf *bytes.Buffer, flag *pflag.Flag) { - name := flag.Name - format := " local_nonpersistent_flags+=(\"--%s" - if len(flag.NoOptDefVal) == 0 { - format += "=" - } - format += "\")\n" - buf.WriteString(fmt.Sprintf(format, name)) -} - -func writeFlags(buf *bytes.Buffer, cmd *Command) { - buf.WriteString(` flags=() +func writeFlags(cmd *Command, out *bytes.Buffer) { + fmt.Fprintf(out, ` flags=() two_word_flags=() - local_nonpersistent_flags=() flags_with_completion=() flags_completion=() `) - localNonPersistentFlags := cmd.LocalNonPersistentFlags() cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { - if nonCompletableFlag(flag) { - return - } - writeFlag(buf, flag, cmd) + writeFlag(flag, out) if len(flag.Shorthand) > 0 { - writeShortFlag(buf, flag, cmd) - } - if localNonPersistentFlags.Lookup(flag.Name) != nil { - writeLocalNonPersistentFlag(buf, flag) - } - }) - cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { - if nonCompletableFlag(flag) { - return - } - writeFlag(buf, flag, cmd) - if len(flag.Shorthand) > 0 { - writeShortFlag(buf, flag, cmd) + writeShortFlag(flag, out) } }) - buf.WriteString("\n") + fmt.Fprintf(out, "\n") } -func writeRequiredFlag(buf *bytes.Buffer, cmd *Command) { - buf.WriteString(" must_have_one_flag=()\n") +func writeRequiredFlag(cmd *Command, out *bytes.Buffer) { + fmt.Fprintf(out, " must_have_one_flag=()\n") flags := cmd.NonInheritedFlags() flags.VisitAll(func(flag *pflag.Flag) { - if nonCompletableFlag(flag) { - return - } - for key := range flag.Annotations { + for key, _ := range flag.Annotations { switch key { case BashCompOneRequiredFlag: format := " must_have_one_flag+=(\"--%s" - if flag.Value.Type() != "bool" { + b := (flag.Value.Type() == "bool") + if !b { format += "=" } format += "\")\n" - buf.WriteString(fmt.Sprintf(format, flag.Name)) + fmt.Fprintf(out, format, flag.Name) if len(flag.Shorthand) > 0 { - buf.WriteString(fmt.Sprintf(" must_have_one_flag+=(\"-%s\")\n", flag.Shorthand)) + fmt.Fprintf(out, " must_have_one_flag+=(\"-%s\")\n", flag.Shorthand) } } } }) } -func writeRequiredNouns(buf *bytes.Buffer, cmd *Command) { - buf.WriteString(" must_have_one_noun=()\n") +func writeRequiredNoun(cmd *Command, out *bytes.Buffer) { + fmt.Fprintf(out, " must_have_one_noun=()\n") sort.Sort(sort.StringSlice(cmd.ValidArgs)) for _, value := range cmd.ValidArgs { - buf.WriteString(fmt.Sprintf(" must_have_one_noun+=(%q)\n", value)) + fmt.Fprintf(out, " must_have_one_noun+=(%q)\n", value) } } -func writeArgAliases(buf *bytes.Buffer, cmd *Command) { - buf.WriteString(" noun_aliases=()\n") - sort.Sort(sort.StringSlice(cmd.ArgAliases)) - for _, value := range cmd.ArgAliases { - buf.WriteString(fmt.Sprintf(" noun_aliases+=(%q)\n", value)) - } -} - -func gen(buf *bytes.Buffer, cmd *Command) { +func gen(cmd *Command, out *bytes.Buffer) { for _, c := range cmd.Commands() { - if !c.IsAvailableCommand() || c == cmd.helpCommand { + if len(c.Deprecated) > 0 { continue } - gen(buf, c) + gen(c, out) } commandName := cmd.CommandPath() commandName = strings.Replace(commandName, " ", "_", -1) - commandName = strings.Replace(commandName, ":", "__", -1) + fmt.Fprintf(out, "_%s()\n{\n", commandName) + fmt.Fprintf(out, " last_command=%q\n", commandName) + writeCommands(cmd, out) + writeFlags(cmd, out) + writeRequiredFlag(cmd, out) + writeRequiredNoun(cmd, out) + fmt.Fprintf(out, "}\n\n") +} - if cmd.Root() == cmd { - buf.WriteString(fmt.Sprintf("_%s_root_command()\n{\n", commandName)) - } else { - buf.WriteString(fmt.Sprintf("_%s()\n{\n", commandName)) +func (cmd *Command) GenBashCompletion(out *bytes.Buffer) { + preamble(out) + if len(cmd.BashCompletionFunction) > 0 { + fmt.Fprintf(out, "%s\n", cmd.BashCompletionFunction) } - - 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") + gen(cmd, out) + postscript(out, cmd.Name()) } -// GenBashCompletion generates bash completion file and writes to the passed writer. -func (c *Command) GenBashCompletion(w io.Writer) error { - buf := new(bytes.Buffer) - writePreamble(buf, c.Name()) - if len(c.BashCompletionFunction) > 0 { - buf.WriteString(c.BashCompletionFunction + "\n") - } - gen(buf, c) - writePostscript(buf, c.Name()) +func (cmd *Command) GenBashCompletionFile(filename string) error { + out := new(bytes.Buffer) - _, err := buf.WriteTo(w) - return err -} + cmd.GenBashCompletion(out) -func nonCompletableFlag(flag *pflag.Flag) bool { - return flag.Hidden || len(flag.Deprecated) > 0 -} - -// GenBashCompletionFile generates bash completion file. -func (c *Command) GenBashCompletionFile(filename string) error { outFile, err := os.Create(filename) if err != nil { return err } defer outFile.Close() - return c.GenBashCompletion(outFile) + _, err = outFile.Write(out.Bytes()) + if err != nil { + return err + } + return nil } -// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag if it exists, -// and causes your command to report an error if invoked without the flag. -func (c *Command) MarkFlagRequired(name string) error { - return MarkFlagRequired(c.Flags(), name) +// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag, if it exists. +func (cmd *Command) MarkFlagRequired(name string) error { + return MarkFlagRequired(cmd.Flags(), name) } -// MarkPersistentFlagRequired adds the BashCompOneRequiredFlag annotation to the named persistent flag if it exists, -// and causes your command to report an error if invoked without the flag. -func (c *Command) MarkPersistentFlagRequired(name string) error { - return MarkFlagRequired(c.PersistentFlags(), name) -} - -// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag if it exists, -// and causes your command to report an error if invoked without the flag. +// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag in the flag set, if it exists. func MarkFlagRequired(flags *pflag.FlagSet, name string) error { return flags.SetAnnotation(name, BashCompOneRequiredFlag, []string{"true"}) } // MarkFlagFilename adds the BashCompFilenameExt annotation to the named flag, if it exists. // Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided. -func (c *Command) MarkFlagFilename(name string, extensions ...string) error { - return MarkFlagFilename(c.Flags(), name, extensions...) -} - -// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. -// Generated bash autocompletion will call the bash function f for the flag. -func (c *Command) MarkFlagCustom(name string, f string) error { - return MarkFlagCustom(c.Flags(), name, f) -} - -// MarkPersistentFlagFilename adds the BashCompFilenameExt annotation to the named persistent flag, if it exists. -// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided. -func (c *Command) MarkPersistentFlagFilename(name string, extensions ...string) error { - return MarkFlagFilename(c.PersistentFlags(), name, extensions...) +func (cmd *Command) MarkFlagFilename(name string, extensions ...string) error { + return MarkFlagFilename(cmd.Flags(), name, extensions...) } // MarkFlagFilename adds the BashCompFilenameExt annotation to the named flag in the flag set, if it exists. @@ -547,9 +385,3 @@ func (c *Command) MarkPersistentFlagFilename(name string, extensions ...string) func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error { return flags.SetAnnotation(name, BashCompFilenameExt, extensions) } - -// MarkFlagCustom adds the BashCompCustom annotation to the named flag in the flag set, if it exists. -// Generated bash autocompletion will call the bash function f for the flag. -func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error { - return flags.SetAnnotation(name, BashCompCustom, []string{f}) -} diff --git a/vendor/github.com/spf13/cobra/bash_completions.md b/vendor/github.com/spf13/cobra/bash_completions.md index 8d01f456..204704ef 100644 --- a/vendor/github.com/spf13/cobra/bash_completions.md +++ b/vendor/github.com/spf13/cobra/bash_completions.md @@ -6,20 +6,19 @@ Generating bash completions from a cobra command is incredibly easy. An actual p package main import ( - "io/ioutil" - "os" + "io/ioutil" + "os" - "k8s.io/kubernetes/pkg/kubectl/cmd" - "k8s.io/kubernetes/pkg/kubectl/cmd/util" + "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd" ) func main() { - kubectl := cmd.NewKubectlCommand(util.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard) - kubectl.GenBashCompletionFile("out.sh") + kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard) + kubectl.GenBashCompletionFile("out.sh") } ``` -`out.sh` will get you completions of subcommands and flags. Copy it to `/etc/bash_completion.d/` as described [here](https://debian-administration.org/article/316/An_introduction_to_bash_completion_part_1) and reset your terminal to use autocompletion. If you make additional annotations to your code, you can get even more intelligent and flexible behavior. +That will get you completions of subcommands and flags. If you make additional annotations to your code, you can get even more intelligent and flexible behavior. ## Creating your own custom functions @@ -81,7 +80,7 @@ The `BashCompletionFunction` option is really only valid/useful on the root comm In the above example "pod" was assumed to already be typed. But if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. Simplified code from `kubectl get` looks like: ```go -validArgs []string = { "pod", "node", "service", "replicationcontroller" } +validArgs []string = { "pods", "nodes", "services", "replicationControllers" } cmd := &cobra.Command{ Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)", @@ -100,34 +99,9 @@ Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give result ```bash # kubectl get [tab][tab] -node pod replicationcontroller service +nodes pods replicationControllers services ``` -## Plural form and shortcuts for nouns - -If your nouns have a number of aliases, you can define them alongside `ValidArgs` using `ArgAliases`: - -```go -argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" } - -cmd := &cobra.Command{ - ... - ValidArgs: validArgs, - ArgAliases: argAliases -} -``` - -The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by -the completion algorithm if entered manually, e.g. in: - -```bash -# kubectl get rc [tab][tab] -backend frontend database -``` - -Note that without declaring `rc` as an alias, the completion algorithm would show the list of nouns -in this example again instead of the replication controllers. - ## Mark flags as required Most of the time completions will only show subcommands. But if a flag is required to make a subcommand work, you probably want it to show up when the user types [tab][tab]. Marking a flag as 'Required' is incredibly easy. @@ -173,49 +147,3 @@ hello.yml test.json ``` So while there are many other files in the CWD it only shows me subdirs and those with valid extensions. - -# Specify custom flag completion - -Similar to the filename completion and filtering using cobra.BashCompFilenameExt, you can specify -a custom flag completion function with cobra.BashCompCustom: - -```go - annotation := make(map[string][]string) - annotation[cobra.BashCompFilenameExt] = []string{"__kubectl_get_namespaces"} - - flag := &pflag.Flag{ - Name: "namespace", - Usage: usage, - Annotations: annotation, - } - cmd.Flags().AddFlag(flag) -``` - -In addition add the `__handle_namespace_flag` implementation in the `BashCompletionFunction` -value, e.g.: - -```bash -__kubectl_get_namespaces() -{ - local template - template="{{ range .items }}{{ .metadata.name }} {{ end }}" - local kubectl_out - if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then - COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) ) - fi -} -``` -# Using bash aliases for commands - -You can also configure the `bash aliases` for the commands and they will also support completions. - -```bash -alias aliasname=origcommand -complete -o default -F __start_origcommand aliasname - -# and now when you run `aliasname` completion will make -# suggestions as it did for `origcommand`. - -$) aliasname -completion firstcommand secondcommand -``` diff --git a/vendor/github.com/spf13/cobra/bash_completions_test.go b/vendor/github.com/spf13/cobra/bash_completions_test.go index 02a4f15b..a1f2b13c 100644 --- a/vendor/github.com/spf13/cobra/bash_completions_test.go +++ b/vendor/github.com/spf13/cobra/bash_completions_test.go @@ -4,214 +4,84 @@ import ( "bytes" "fmt" "os" - "os/exec" - "regexp" "strings" "testing" ) +var _ = fmt.Println +var _ = os.Stderr + func checkOmit(t *testing.T, found, unexpected string) { if strings.Contains(found, unexpected) { - t.Errorf("Got: %q\nBut should not have!\n", unexpected) + t.Errorf("Unexpected response.\nGot: %q\nBut should not have!\n", unexpected) } } func check(t *testing.T, found, expected string) { if !strings.Contains(found, expected) { - t.Errorf("Expecting to contain: \n %q\nGot:\n %q\n", expected, found) + t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) } } -func checkRegex(t *testing.T, found, pattern string) { - matched, err := regexp.MatchString(pattern, found) - if err != nil { - t.Errorf("Error thrown performing MatchString: \n %s\n", err) - } - if !matched { - t.Errorf("Expecting to match: \n %q\nGot:\n %q\n", pattern, found) - } -} - -func runShellCheck(s string) error { - excluded := []string{ - "SC2034", // PREFIX appears unused. Verify it or export it. - } - cmd := exec.Command("shellcheck", "-s", "bash", "-", "-e", strings.Join(excluded, ",")) - cmd.Stderr = os.Stderr - cmd.Stdout = os.Stdout - - stdin, err := cmd.StdinPipe() - if err != nil { - return err - } - go func() { - stdin.Write([]byte(s)) - stdin.Close() - }() - - return cmd.Run() -} - // World worst custom function, just keep telling you to enter hello! -const bashCompletionFunc = `__custom_func() { - COMPREPLY=( "hello" ) +const ( + bash_completion_func = `__custom_func() { +COMPREPLY=( "hello" ) } ` +) func TestBashCompletions(t *testing.T) { - rootCmd := &Command{ - Use: "root", - ArgAliases: []string{"pods", "nodes", "services", "replicationcontrollers", "po", "no", "svc", "rc"}, - ValidArgs: []string{"pod", "node", "service", "replicationcontroller"}, - BashCompletionFunction: bashCompletionFunc, - Run: emptyRun, - } - rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot") - rootCmd.MarkFlagRequired("introot") + c := initializeWithRootCmd() + cmdEcho.AddCommand(cmdTimes) + c.AddCommand(cmdEcho, cmdPrint, cmdDeprecated) - // Filename. - rootCmd.Flags().String("filename", "", "Enter a filename") - rootCmd.MarkFlagFilename("filename", "json", "yaml", "yml") + // custom completion function + c.BashCompletionFunction = bash_completion_func - // Persistent filename. - rootCmd.PersistentFlags().String("persistent-filename", "", "Enter a filename") - rootCmd.MarkPersistentFlagFilename("persistent-filename") - rootCmd.MarkPersistentFlagRequired("persistent-filename") + // required flag + c.MarkFlagRequired("introot") - // Filename extensions. - rootCmd.Flags().String("filename-ext", "", "Enter a filename (extension limited)") - rootCmd.MarkFlagFilename("filename-ext") - rootCmd.Flags().String("custom", "", "Enter a filename (extension limited)") - rootCmd.MarkFlagCustom("custom", "__complete_custom") + // valid nouns + validArgs := []string{"pods", "nodes", "services", "replicationControllers"} + c.ValidArgs = validArgs - // Subdirectories in a given directory. - rootCmd.Flags().String("theme", "", "theme to use (located in /themes/THEMENAME/)") - rootCmd.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"}) + // filename + var flagval string + c.Flags().StringVar(&flagval, "filename", "", "Enter a filename") + c.MarkFlagFilename("filename", "json", "yaml", "yml") - echoCmd := &Command{ - Use: "echo [string to echo]", - Aliases: []string{"say"}, - Short: "Echo anything to the screen", - Long: "an utterly useless command for testing.", - Example: "Just run cobra-test echo", - Run: emptyRun, - } + // filename extensions + var flagvalExt string + c.Flags().StringVar(&flagvalExt, "filename-ext", "", "Enter a filename (extension limited)") + c.MarkFlagFilename("filename-ext") - echoCmd.Flags().String("filename", "", "Enter a filename") - echoCmd.MarkFlagFilename("filename", "json", "yaml", "yml") - echoCmd.Flags().String("config", "", "config to use (located in /config/PROFILE/)") - echoCmd.Flags().SetAnnotation("config", BashCompSubdirsInDir, []string{"config"}) + // subdirectories in a given directory + var flagvalTheme string + c.Flags().StringVar(&flagvalTheme, "theme", "", "theme to use (located in /themes/THEMENAME/)") + c.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"}) - printCmd := &Command{ - Use: "print [string to print]", - Args: MinimumNArgs(1), - Short: "Print anything to the screen", - Long: "an absolutely utterly useless command for testing.", - Run: emptyRun, - } + out := new(bytes.Buffer) + c.GenBashCompletion(out) + str := out.String() - deprecatedCmd := &Command{ - Use: "deprecated [can't do anything here]", - Args: NoArgs, - Short: "A command which is deprecated", - Long: "an absolutely utterly useless command for testing deprecation!.", - Deprecated: "Please use echo instead", - Run: emptyRun, - } - - colonCmd := &Command{ - Use: "cmd:colon", - Run: emptyRun, - } - - timesCmd := &Command{ - Use: "times [# times] [string to echo]", - SuggestFor: []string{"counts"}, - Args: OnlyValidArgs, - ValidArgs: []string{"one", "two", "three", "four"}, - Short: "Echo anything to the screen more times", - Long: "a slightly useless command for testing.", - Run: emptyRun, - } - - echoCmd.AddCommand(timesCmd) - rootCmd.AddCommand(echoCmd, printCmd, deprecatedCmd, colonCmd) - - buf := new(bytes.Buffer) - rootCmd.GenBashCompletion(buf) - output := buf.String() - - check(t, output, "_root") - check(t, output, "_root_echo") - check(t, output, "_root_echo_times") - check(t, output, "_root_print") - check(t, output, "_root_cmd__colon") + check(t, str, "_cobra-test") + check(t, str, "_cobra-test_echo") + check(t, str, "_cobra-test_echo_times") + check(t, str, "_cobra-test_print") // check for required flags - check(t, output, `must_have_one_flag+=("--introot=")`) - check(t, output, `must_have_one_flag+=("--persistent-filename=")`) + check(t, str, `must_have_one_flag+=("--introot=")`) // check for custom completion function - check(t, output, `COMPREPLY=( "hello" )`) + check(t, str, `COMPREPLY=( "hello" )`) // check for required nouns - check(t, output, `must_have_one_noun+=("pod")`) - // check for noun aliases - check(t, output, `noun_aliases+=("pods")`) - check(t, output, `noun_aliases+=("rc")`) - checkOmit(t, output, `must_have_one_noun+=("pods")`) + check(t, str, `must_have_one_noun+=("pods")`) // check for filename extension flags - check(t, output, `flags_completion+=("_filedir")`) + check(t, str, `flags_completion+=("_filedir")`) // check for filename extension flags - check(t, output, `must_have_one_noun+=("three")`) - // check for filename extension flags - check(t, output, fmt.Sprintf(`flags_completion+=("__%s_handle_filename_extension_flag json|yaml|yml")`, rootCmd.Name())) - // check for filename extension flags in a subcommand - checkRegex(t, output, fmt.Sprintf(`_root_echo\(\)\n{[^}]*flags_completion\+=\("__%s_handle_filename_extension_flag json\|yaml\|yml"\)`, rootCmd.Name())) - // check for custom flags - check(t, output, `flags_completion+=("__complete_custom")`) + check(t, str, `flags_completion+=("__handle_filename_extension_flag json|yaml|yml")`) // check for subdirs_in_dir flags - check(t, output, fmt.Sprintf(`flags_completion+=("__%s_handle_subdirs_in_dir_flag themes")`, rootCmd.Name())) - // check for subdirs_in_dir flags in a subcommand - checkRegex(t, output, fmt.Sprintf(`_root_echo\(\)\n{[^}]*flags_completion\+=\("__%s_handle_subdirs_in_dir_flag config"\)`, rootCmd.Name())) + check(t, str, `flags_completion+=("__handle_subdirs_in_dir_flag themes")`) - checkOmit(t, output, deprecatedCmd.Name()) - - // If available, run shellcheck against the script. - if err := exec.Command("which", "shellcheck").Run(); err != nil { - return - } - if err := runShellCheck(output); err != nil { - t.Fatalf("shellcheck failed: %v", err) - } -} - -func TestBashCompletionHiddenFlag(t *testing.T) { - c := &Command{Use: "c", Run: emptyRun} - - const flagName = "hiddenFlag" - c.Flags().Bool(flagName, false, "") - c.Flags().MarkHidden(flagName) - - buf := new(bytes.Buffer) - c.GenBashCompletion(buf) - output := buf.String() - - if strings.Contains(output, flagName) { - t.Errorf("Expected completion to not include %q flag: Got %v", flagName, output) - } -} - -func TestBashCompletionDeprecatedFlag(t *testing.T) { - c := &Command{Use: "c", Run: emptyRun} - - const flagName = "deprecated-flag" - c.Flags().Bool(flagName, false, "") - c.Flags().MarkDeprecated(flagName, "use --not-deprecated instead") - - buf := new(bytes.Buffer) - c.GenBashCompletion(buf) - output := buf.String() - - if strings.Contains(output, flagName) { - t.Errorf("expected completion to not include %q flag: Got %v", flagName, output) - } + checkOmit(t, str, cmdDeprecated.Name()) } diff --git a/vendor/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go index 7010fd15..78b92b0a 100644 --- a/vendor/github.com/spf13/cobra/cobra.go +++ b/vendor/github.com/spf13/cobra/cobra.go @@ -23,64 +23,32 @@ import ( "strconv" "strings" "text/template" - "unicode" ) -var templateFuncs = template.FuncMap{ - "trim": strings.TrimSpace, - "trimRightSpace": trimRightSpace, - "trimTrailingWhitespaces": trimRightSpace, - "appendIfNotPresent": appendIfNotPresent, - "rpad": rpad, - "gt": Gt, - "eq": Eq, -} - var initializers []func() -// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing -// to automatically enable in CLI tools. -// Set this to true to enable it. -var EnablePrefixMatching = false +// automatic prefix matching can be a dangerous thing to automatically enable in CLI tools. +// Set this to true to enable it +var EnablePrefixMatching bool = false -// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default. -// To disable sorting, set it to false. -var EnableCommandSorting = true +// enables an information splash screen on Windows if the CLI is started from explorer.exe. +var EnableWindowsMouseTrap bool = true -// MousetrapHelpText enables an information splash screen on Windows -// if the CLI is started from explorer.exe. -// To disable the mousetrap, just set this variable to blank string (""). -// Works only on Microsoft Windows. -var MousetrapHelpText string = `This is a command line tool. +var MousetrapHelpText string = `This is a command line tool You need to open cmd.exe and run it from there. ` -// AddTemplateFunc adds a template function that's available to Usage and Help -// template generation. -func AddTemplateFunc(name string, tmplFunc interface{}) { - templateFuncs[name] = tmplFunc -} - -// AddTemplateFuncs adds multiple template functions that are available to Usage and -// Help template generation. -func AddTemplateFuncs(tmplFuncs template.FuncMap) { - for k, v := range tmplFuncs { - templateFuncs[k] = v +//OnInitialize takes a series of func() arguments and appends them to a slice of func(). +func OnInitialize(y ...func()) { + for _, x := range y { + initializers = append(initializers, x) } } -// OnInitialize sets the passed functions to be run when each command's -// Execute method is called. -func OnInitialize(y ...func()) { - initializers = append(initializers, y...) -} - -// 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. +//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) @@ -108,9 +76,7 @@ func Gt(a interface{}, b interface{}) bool { 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. +//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) @@ -126,21 +92,7 @@ func Eq(a interface{}, b interface{}) bool { 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. +//rpad adds padding to the right of a string func rpad(s string, padding int) string { template := fmt.Sprintf("%%-%ds", padding) return fmt.Sprintf(template, s) @@ -149,52 +101,12 @@ 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") - t.Funcs(templateFuncs) + t.Funcs(template.FuncMap{ + "trim": strings.TrimSpace, + "rpad": rpad, + "gt": Gt, + "eq": Eq, + }) template.Must(t.Parse(text)) return t.Execute(w, data) } - -// ld compares two strings and returns the levenshtein distance between them. -func ld(s, t string, ignoreCase bool) int { - if ignoreCase { - s = strings.ToLower(s) - t = strings.ToLower(t) - } - d := make([][]int, len(s)+1) - for i := range d { - d[i] = make([]int, len(t)+1) - } - for i := range d { - d[i][0] = i - } - for j := range d[0] { - d[0][j] = j - } - for j := 1; j <= len(t); j++ { - for i := 1; i <= len(s); i++ { - if s[i-1] == t[j-1] { - d[i][j] = d[i-1][j-1] - } else { - min := d[i-1][j] - if d[i][j-1] < min { - min = d[i][j-1] - } - if d[i-1][j-1] < min { - min = d[i-1][j-1] - } - d[i][j] = min + 1 - } - } - - } - return d[len(s)][len(t)] -} - -func stringInSlice(a string, list []string) bool { - for _, b := range list { - if b == a { - return true - } - } - return false -} diff --git a/vendor/github.com/spf13/cobra/cobra/README.md b/vendor/github.com/spf13/cobra/cobra/README.md deleted file mode 100644 index 6054f95c..00000000 --- a/vendor/github.com/spf13/cobra/cobra/README.md +++ /dev/null @@ -1,94 +0,0 @@ -# Cobra Generator - -Cobra provides its own program that will create your application and add any -commands you want. It's the easiest way to incorporate Cobra into your application. - -In order to use the cobra command, compile it using the following command: - - go get github.com/spf13/cobra/cobra - -This will create the cobra executable under your `$GOPATH/bin` directory. - -### cobra init - -The `cobra init [app]` command will create your initial application code -for you. It is a very powerful application that will populate your program with -the right structure so you can immediately enjoy all the benefits of Cobra. It -will also automatically apply the license you specify to your application. - -Cobra init is pretty smart. You can provide it a full path, or simply a path -similar to what is expected in the import. - -``` -cobra init github.com/spf13/newApp -``` - -### cobra add - -Once an application is initialized, Cobra can create additional commands for you. -Let's say you created an app and you wanted the following commands for it: - -* app serve -* app config -* app config create - -In your project directory (where your main.go file is) you would run the following: - -``` -cobra add serve -cobra add config -cobra add create -p 'configCmd' -``` - -*Note: Use camelCase (not snake_case/snake-case) for command names. -Otherwise, you will encounter 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 similar to -the following: - -``` - ▾ app/ - ▾ cmd/ - serve.go - config.go - create.go - main.go -``` - -At this point you can run `go run main.go` and it would run your app. `go run -main.go serve`, `go run main.go config`, `go run main.go config create` along -with `go run main.go help serve`, etc. would all work. - -Obviously you haven't added your own code to these yet. The commands are ready -for you to give them their tasks. Have fun! - -### Configuring the cobra generator - -The Cobra generator will be easier to use if you provide a simple configuration -file which will help you eliminate providing a bunch of repeated information in -flags over and over. - -An example ~/.cobra.yaml file: - -```yaml -author: Steve Francia -license: MIT -``` - -You can specify no license by setting `license` to `none` or you can specify -a custom license: - -```yaml -license: - header: This file is part of {{ .appName }}. - text: | - {{ .copyright }} - - This is my license. There are many like it, but this one is mine. - My license is my best friend. It is my life. I must master it as I must - master my life. -``` - -You can also use built-in licenses. For example, **GPLv2**, **GPLv3**, **LGPL**, -**AGPL**, **MIT**, **2-Clause BSD** or **3-Clause BSD**. diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/add.go b/vendor/github.com/spf13/cobra/cobra/cmd/add.go deleted file mode 100644 index fb22096a..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/add.go +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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" - "path/filepath" - "unicode" - - "github.com/spf13/cobra" -) - -func init() { - addCmd.Flags().StringVarP(&packageName, "package", "t", "", "target package name (e.g. github.com/spf13/hugo)") - addCmd.Flags().StringVarP(&parentName, "parent", "p", "rootCmd", "variable name of parent command for this command") -} - -var packageName, parentName string - -var addCmd = &cobra.Command{ - Use: "add [command name]", - Aliases: []string{"command"}, - Short: "Add a command to a Cobra Application", - Long: `Add (cobra add) will create a new command, with a license and -the appropriate structure for a Cobra-based CLI application, -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`, - - Run: func(cmd *cobra.Command, args []string) { - if len(args) < 1 { - er("add needs a name for the command") - } - - var project *Project - if packageName != "" { - project = NewProject(packageName) - } else { - 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) - }, -} - -// 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 - } - - // If the current character isn't dash or underscore, - // just add it. - if output != "" { - output += string(source[i]) - } - i++ - } - - if output == "" { - return source // source is initially valid name. - } - return output -} - -func createCmdFile(license License, path, cmdName string) { - template := `{{comment .copyright}} -{{if .license}}{{comment .license}}{{end}} - -package {{.cmdPackage}} - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -// {{.cmdName}}Cmd represents the {{.cmdName}} command -var {{.cmdName}}Cmd = &cobra.Command{ - Use: "{{.cmdName}}", - Short: "A brief description of your command", - Long: ` + "`" + `A longer description that spans multiple lines and likely contains examples -and usage of using your command. For example: - -Cobra is a CLI library for Go that empowers applications. -This application is a tool to generate the needed files -to quickly create a Cobra application.` + "`" + `, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("{{.cmdName}} called") - }, -} - -func init() { - {{.parentName}}.AddCommand({{.cmdName}}Cmd) - - // Here you will define your flags and configuration settings. - - // Cobra supports Persistent Flags which will work for this command - // and all subcommands, e.g.: - // {{.cmdName}}Cmd.PersistentFlags().String("foo", "", "A help for foo") - - // Cobra supports local flags which will only run when this command - // is called directly, e.g.: - // {{.cmdName}}Cmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") -} -` - - data := make(map[string]interface{}) - data["copyright"] = copyrightLine() - data["license"] = license.Header - data["cmdPackage"] = filepath.Base(filepath.Dir(path)) // last dir of path - data["parentName"] = parentName - data["cmdName"] = cmdName - - cmdScript, err := executeTemplate(template, data) - if err != nil { - er(err) - } - err = writeStringToFile(path, cmdScript) - if err != nil { - er(err) - } -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/add_test.go b/vendor/github.com/spf13/cobra/cobra/cmd/add_test.go deleted file mode 100644 index b920e2b9..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/add_test.go +++ /dev/null @@ -1,109 +0,0 @@ -package cmd - -import ( - "errors" - "io/ioutil" - "os" - "path/filepath" - "testing" - - "github.com/spf13/viper" -) - -// 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) - defer os.RemoveAll(project.AbsPath()) - - viper.Set("author", "NAME HERE ") - viper.Set("license", "apache") - viper.Set("year", 2017) - defer viper.Set("author", nil) - defer viper.Set("license", nil) - defer viper.Set("year", nil) - - // Initialize the project first. - initializeProject(project) - - // 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 { - // Known 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/vendor/github.com/spf13/cobra/cobra/cmd/golden_test.go b/vendor/github.com/spf13/cobra/cobra/cmd/golden_test.go deleted file mode 100644 index 59a5a1c9..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/golden_test.go +++ /dev/null @@ -1,77 +0,0 @@ -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, "-u", pathA, pathB) - diffCmd.Stdout = output - diffCmd.Stderr = output - - output.WriteString("$ diff -u " + 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/vendor/github.com/spf13/cobra/cobra/cmd/helpers.go b/vendor/github.com/spf13/cobra/cobra/cmd/helpers.go deleted file mode 100644 index cd94b3e3..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/helpers.go +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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 ( - "bytes" - "fmt" - "io" - "os" - "os/exec" - "path/filepath" - "strings" - "text/template" -) - -var srcPaths []string - -func init() { - // Initialize srcPaths. - envGoPath := os.Getenv("GOPATH") - goPaths := filepath.SplitList(envGoPath) - if len(goPaths) == 0 { - // Adapted from https://github.com/Masterminds/glide/pull/798/files. - // As of Go 1.8 the GOPATH is no longer required to be set. Instead there - // is a default value. If there is no GOPATH check for the default value. - // Note, checking the GOPATH first to avoid invoking the go toolchain if - // possible. - - goExecutable := os.Getenv("COBRA_GO_EXECUTABLE") - if len(goExecutable) <= 0 { - goExecutable = "go" - } - - out, err := exec.Command(goExecutable, "env", "GOPATH").Output() - if err != nil { - er(err) - } - - toolchainGoPath := strings.TrimSpace(string(out)) - goPaths = filepath.SplitList(toolchainGoPath) - if len(goPaths) == 0 { - er("$GOPATH is not set") - } - } - srcPaths = make([]string, 0, len(goPaths)) - for _, goPath := range goPaths { - srcPaths = append(srcPaths, filepath.Join(goPath, "src")) - } -} - -func er(msg interface{}) { - fmt.Println("Error:", msg) - os.Exit(1) -} - -// isEmpty checks if a given path is empty. -// Hidden files in path are ignored. -func isEmpty(path string) bool { - fi, err := os.Stat(path) - if err != nil { - er(err) - } - - if !fi.IsDir() { - return fi.Size() == 0 - } - - f, err := os.Open(path) - if err != nil { - er(err) - } - defer f.Close() - - names, err := f.Readdirnames(-1) - if err != nil && err != io.EOF { - er(err) - } - - for _, name := range names { - if len(name) > 0 && name[0] != '.' { - return false - } - } - return true -} - -// exists checks if a file or directory exists. -func exists(path string) bool { - if path == "" { - return false - } - _, err := os.Stat(path) - if err == nil { - return true - } - if !os.IsNotExist(err) { - er(err) - } - return false -} - -func executeTemplate(tmplStr string, data interface{}) (string, error) { - tmpl, err := template.New("").Funcs(template.FuncMap{"comment": commentifyString}).Parse(tmplStr) - if err != nil { - return "", err - } - - buf := new(bytes.Buffer) - err = tmpl.Execute(buf, data) - return buf.String(), err -} - -func writeStringToFile(path string, s string) error { - return writeToFile(path, strings.NewReader(s)) -} - -// writeToFile writes r to file with path only -// if file/directory on given path doesn't exist. -func writeToFile(path string, r io.Reader) error { - if exists(path) { - return fmt.Errorf("%v already exists", path) - } - - dir := filepath.Dir(path) - if dir != "" { - if err := os.MkdirAll(dir, 0777); err != nil { - return err - } - } - - file, err := os.Create(path) - if err != nil { - return err - } - defer file.Close() - - _, err = io.Copy(file, r) - return err -} - -// commentfyString comments every line of in. -func commentifyString(in string) string { - var newlines []string - lines := strings.Split(in, "\n") - for _, line := range lines { - if strings.HasPrefix(line, "//") { - newlines = append(newlines, line) - } else { - if line == "" { - newlines = append(newlines, "//") - } else { - newlines = append(newlines, "// "+line) - } - } - } - return strings.Join(newlines, "\n") -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/init.go b/vendor/github.com/spf13/cobra/cobra/cmd/init.go deleted file mode 100644 index 24413701..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/init.go +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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" - "path" - "path/filepath" - - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -var initCmd = &cobra.Command{ - Use: "init [name]", - Aliases: []string{"initialize", "initialise", "create"}, - Short: "Initialize a Cobra Application", - Long: `Initialize (cobra init) will create a new application, with a license -and the appropriate structure for a Cobra-based CLI application. - - * If a name is provided, it will be created in the current directory; - * If no name is provided, the current directory will be assumed; - * If a relative path is provided, it will be created inside $GOPATH - (e.g. github.com/spf13/hugo); - * If an absolute path is provided, it will be created; - * If the directory already exists but is empty, it will be used. - -Init will not use an existing directory with contents.`, - - Run: func(cmd *cobra.Command, args []string) { - wd, err := os.Getwd() - if err != nil { - er(err) - } - - 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 provide only one argument") - } - - 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 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 !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(project.License(), project.AbsPath()) - createMainFile(project) - createRootCmdFile(project) -} - -func createLicenseFile(license License, path string) { - data := make(map[string]interface{}) - data["copyright"] = copyrightLine() - - // Generate license template from text and data. - text, err := executeTemplate(license.Text, data) - 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(project *Project) { - mainTemplate := `{{ comment .copyright }} -{{if .license}}{{ comment .license }}{{end}} - -package main - -import "{{ .importpath }}" - -func main() { - cmd.Execute() -} -` - data := make(map[string]interface{}) - data["copyright"] = copyrightLine() - data["license"] = project.License().Header - data["importpath"] = path.Join(project.Name(), filepath.Base(project.CmdPath())) - - mainScript, err := executeTemplate(mainTemplate, data) - if err != nil { - er(err) - } - - err = writeStringToFile(filepath.Join(project.AbsPath(), "main.go"), mainScript) - if err != nil { - er(err) - } -} - -func createRootCmdFile(project *Project) { - template := `{{comment .copyright}} -{{if .license}}{{comment .license}}{{end}} - -package cmd - -import ( - "fmt" - "os" -{{if .viper}} - homedir "github.com/mitchellh/go-homedir"{{end}} - "github.com/spf13/cobra"{{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}}", - 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 and 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() { {{- 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 }} - -// 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(err) - os.Exit(1) - } - - // Search config in home directory with name ".{{ .appName }}" (without extension). - viper.AddConfigPath(home) - viper.SetConfigName(".{{ .appName }}") - } - - 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 }} -` - - data := make(map[string]interface{}) - data["copyright"] = copyrightLine() - 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 = writeStringToFile(filepath.Join(project.CmdPath(), "root.go"), rootCmdScript) - if err != nil { - er(err) - } - -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/init_test.go b/vendor/github.com/spf13/cobra/cobra/cmd/init_test.go deleted file mode 100644 index 40eb4038..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/init_test.go +++ /dev/null @@ -1,83 +0,0 @@ -package cmd - -import ( - "errors" - "io/ioutil" - "os" - "path/filepath" - "testing" - - "github.com/spf13/viper" -) - -// 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()) - - viper.Set("author", "NAME HERE ") - viper.Set("license", "apache") - viper.Set("year", 2017) - defer viper.Set("author", nil) - defer viper.Set("license", nil) - defer viper.Set("year", nil) - - 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 { - // Known 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 - } - if err := ioutil.WriteFile(goldenPath, got, 0644); err != nil { - t.Fatal("Error while updating file:", err) - } - } - 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/vendor/github.com/spf13/cobra/cobra/cmd/license_agpl.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_agpl.go deleted file mode 100644 index bc22e973..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/license_agpl.go +++ /dev/null @@ -1,683 +0,0 @@ -package cmd - -func initAgpl() { - Licenses["agpl"] = License{ - Name: "GNU Affero General Public License", - PossibleMatches: []string{"agpl", "affero gpl", "gnu agpl"}, - Header: ` -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. - -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 this program. If not, see .`, - Text: ` GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -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. - - - Copyright (C) - - 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. - - 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 this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -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 -. -`, - } -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/license_apache_2.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_apache_2.go deleted file mode 100644 index 38393d54..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/license_apache_2.go +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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. - -// Parts inspired by https://github.com/ryanuber/go-license - -package cmd - -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.`, - Text: ` - 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/vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_2.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_2.go deleted file mode 100644 index 4a847e04..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_2.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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. - -// Parts inspired by https://github.com/ryanuber/go-license - -package cmd - -func initBsdClause2() { - Licenses["freebsd"] = License{ - Name: "Simplified BSD License", - PossibleMatches: []string{"freebsd", "simpbsd", "simple bsd", "2-clause bsd", - "2 clause bsd", "simplified bsd license"}, - Header: `All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE.`, - Text: `{{ .copyright }} -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -`, - } -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_3.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_3.go deleted file mode 100644 index c7476b31..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/license_bsd_clause_3.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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. - -// Parts inspired by https://github.com/ryanuber/go-license - -package cmd - -func initBsdClause3() { - Licenses["bsd"] = License{ - Name: "NewBSD", - PossibleMatches: []string{"bsd", "newbsd", "3 clause bsd", "3-clause bsd"}, - Header: `All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE.`, - Text: `{{ .copyright }} -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -`, - } -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_2.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_2.go deleted file mode 100644 index 03e05b3a..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_2.go +++ /dev/null @@ -1,376 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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. - -// Parts inspired by https://github.com/ryanuber/go-license - -package cmd - -func initGpl2() { - Licenses["gpl2"] = License{ - Name: "GNU General Public License 2.0", - PossibleMatches: []string{"gpl2", "gnu gpl2", "gplv2"}, - Header: ` -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 Lesser General Public License -along with this program. If not, see .`, - Text: ` GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -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. - - - Copyright (C) - - 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. - - , 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/vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_3.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_3.go deleted file mode 100644 index ce07679c..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/license_gpl_3.go +++ /dev/null @@ -1,711 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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. - -// Parts inspired by https://github.com/ryanuber/go-license - -package cmd - -func initGpl3() { - Licenses["gpl3"] = License{ - Name: "GNU General Public License 3.0", - PossibleMatches: []string{"gpl3", "gplv3", "gpl", "gnu gpl3", "gnu gpl"}, - Header: ` -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 .`, - Text: ` GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -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. - - - Copyright (C) - - 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 . - -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: - - Copyright (C) - 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 -. - - 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 -. -`, - } -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/license_lgpl.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_lgpl.go deleted file mode 100644 index 0f8b96ca..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/license_lgpl.go +++ /dev/null @@ -1,186 +0,0 @@ -package cmd - -func initLgpl() { - Licenses["lgpl"] = License{ - Name: "GNU Lesser General Public License", - PossibleMatches: []string{"lgpl", "lesser gpl", "gnu lgpl"}, - Header: ` -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. - -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 this program. If not, see .`, - Text: ` GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library.`, - } -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/license_mit.go b/vendor/github.com/spf13/cobra/cobra/cmd/license_mit.go deleted file mode 100644 index bd2d0c4f..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/license_mit.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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. - -// Parts inspired by https://github.com/ryanuber/go-license - -package cmd - -func initMit() { - Licenses["mit"] = License{ - Name: "MIT License", - PossibleMatches: []string{"mit"}, - Header: ` -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE.`, - Text: `The MIT License (MIT) - -{{ .copyright }} - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -`, - } -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/licenses.go b/vendor/github.com/spf13/cobra/cobra/cmd/licenses.go deleted file mode 100644 index a070134d..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/licenses.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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. - -// Parts inspired by https://github.com/ryanuber/go-license - -package cmd - -import ( - "strings" - "time" - - "github.com/spf13/viper" -) - -// 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), -// the header to be used with each file on the file's creating, and the text -// of the license -type License struct { - Name string // The type of license in use - PossibleMatches []string // Similar names to guess - Text string // License text data - Header string // License header for source files -} - -func init() { - // Allows a user to not use a license. - Licenses["none"] = License{"None", []string{"none", "false"}, "", ""} - - initApache2() - initMit() - initBsdClause3() - initBsdClause2() - initGpl2() - initGpl3() - initLgpl() - initAgpl() -} - -// 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 { - // If explicitly flagged, use that. - if userLicense != "" { - return findLicense(userLicense) - } - - // If user wants to have custom license, use that. - if viper.IsSet("license.header") || viper.IsSet("license.text") { - return License{Header: viper.GetString("license.header"), - Text: viper.GetString("license.text")} - } - - // If user wants to have built-in license, use that. - if viper.IsSet("license") { - return findLicense(viper.GetString("license")) - } - - // If user didn't set any license, use Apache 2.0 by default. - return Licenses["apache"] -} - -func copyrightLine() string { - author := viper.GetString("author") - - year := viper.GetString("year") // For tests. - if year == "" { - year = time.Now().Format("2006") - } - - return "Copyright © " + year + " " + author -} - -// 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(name, match) { - return key - } - } - } - - return "" -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/project.go b/vendor/github.com/spf13/cobra/cobra/cmd/project.go deleted file mode 100644 index 7ddb8258..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/project.go +++ /dev/null @@ -1,200 +0,0 @@ -package cmd - -import ( - "os" - "path/filepath" - "runtime" - "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. -func NewProject(projectName string) *Project { - if projectName == "" { - er("can't create project with blank name") - } - - 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 filepathHasPrefix(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. -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. -func NewProjectFromPath(absPath string) *Project { - if absPath == "" { - er("can't create project: absPath can't be blank") - } - if !filepath.IsAbs(absPath) { - er("can't create project: absPath is not absolute") - } - - // If absPath is symlink, use its destination. - fi, err := os.Lstat(absPath) - if err != nil { - er("can't read path info: " + err.Error()) - } - if fi.Mode()&os.ModeSymlink != 0 { - path, err := os.Readlink(absPath) - if err != nil { - er("can't read the destination of symlink: " + err.Error()) - } - absPath = path - } - - p := new(Project) - p.absPath = strings.TrimSuffix(absPath, findCmdDir(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(err) - } - 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. -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. -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 []string{"cmd", "cmds", "command", "commands"} { - 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 filepathHasPrefix(p.absPath, srcPath) { - p.srcPath = srcPath - break - } - } - - 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/vendor/github.com/spf13/cobra/cobra/cmd/project_test.go b/vendor/github.com/spf13/cobra/cobra/cmd/project_test.go deleted file mode 100644 index 037f7c55..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/project_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package cmd - -import ( - "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 filepathHasPrefix(path, srcPath) { - return true - } - } - return false -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/root.go b/vendor/github.com/spf13/cobra/cobra/cmd/root.go deleted file mode 100644 index 19568f98..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/root.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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" - - homedir "github.com/mitchellh/go-homedir" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -var ( - // Used for flags. - cfgFile, userLicense string - - 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() { - rootCmd.Execute() -} - -func init() { - cobra.OnInitialize(initConfig) - - rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") - rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution") - rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project") - rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration") - viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) - viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) - viper.SetDefault("author", "NAME HERE ") - viper.SetDefault("license", "apache") - - rootCmd.AddCommand(addCmd) - rootCmd.AddCommand(initCmd) -} - -func initConfig() { - if cfgFile != "" { - // Use config file from the flag. - viper.SetConfigFile(cfgFile) - } else { - // Find home directory. - home, err := homedir.Dir() - if err != nil { - er(err) - } - - // Search config in home directory with name ".cobra" (without extension). - viper.AddConfigPath(home) - viper.SetConfigName(".cobra") - } - - viper.AutomaticEnv() - - if err := viper.ReadInConfig(); err == nil { - fmt.Println("Using config file:", viper.ConfigFileUsed()) - } -} diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/testdata/LICENSE.golden b/vendor/github.com/spf13/cobra/cobra/cmd/testdata/LICENSE.golden deleted file mode 100644 index d6456956..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/testdata/LICENSE.golden +++ /dev/null @@ -1,202 +0,0 @@ - - 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/vendor/github.com/spf13/cobra/cobra/cmd/testdata/main.go.golden b/vendor/github.com/spf13/cobra/cobra/cmd/testdata/main.go.golden deleted file mode 100644 index cdbe38d7..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/testdata/main.go.golden +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright © 2017 NAME HERE -// -// 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/vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden b/vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden deleted file mode 100644 index d74f4cd4..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright © 2017 NAME HERE -// -// 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 and 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(err) - os.Exit(1) - } - - // Search config in home directory with name ".testproject" (without extension). - viper.AddConfigPath(home) - viper.SetConfigName(".testproject") - } - - 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/vendor/github.com/spf13/cobra/cobra/cmd/testdata/test.go.golden b/vendor/github.com/spf13/cobra/cobra/cmd/testdata/test.go.golden deleted file mode 100644 index ed644275..00000000 --- a/vendor/github.com/spf13/cobra/cobra/cmd/testdata/test.go.golden +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright © 2017 NAME HERE -// -// 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/vendor/github.com/spf13/cobra/cobra/main.go b/vendor/github.com/spf13/cobra/cobra/main.go deleted file mode 100644 index c3a9d9cb..00000000 --- a/vendor/github.com/spf13/cobra/cobra/main.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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/cobra/cobra/cmd" - -func main() { - cmd.Execute() -} diff --git a/vendor/github.com/spf13/cobra/cobra_test.go b/vendor/github.com/spf13/cobra/cobra_test.go index 0d1755bd..7cb4917d 100644 --- a/vendor/github.com/spf13/cobra/cobra_test.go +++ b/vendor/github.com/spf13/cobra/cobra_test.go @@ -1,22 +1,965 @@ package cobra import ( + "bytes" + "fmt" + "os" + "reflect" + "runtime" + "strings" "testing" - "text/template" + + "github.com/spf13/pflag" ) -func TestAddTemplateFunctions(t *testing.T) { - AddTemplateFunc("t", func() bool { return true }) - AddTemplateFuncs(template.FuncMap{ - "f": func() bool { return false }, - "h": func() string { return "Hello," }, - "w": func() string { return "world." }}) +var _ = fmt.Println +var _ = os.Stderr - c := &Command{} - c.SetUsageTemplate(`{{if t}}{{h}}{{end}}{{if f}}{{h}}{{end}} {{w}}`) +var tp, te, tt, t1, tr []string +var rootPersPre, echoPre, echoPersPre, timesPersPre []string +var flagb1, flagb2, flagb3, flagbr, flagbp bool +var flags1, flags2a, flags2b, flags3 string +var flagi1, flagi2, flagi3, flagir int +var globalFlag1 bool +var flagEcho, rootcalled bool +var versionUsed int - const expected = "Hello, world." - if got := c.UsageString(); got != expected { - t.Errorf("Expected UsageString: %v\nGot: %v", expected, got) +const strtwoParentHelp = "help message for parent flag strtwo" +const strtwoChildHelp = "help message for child flag strtwo" + +var cmdPrint = &Command{ + Use: "print [string to print]", + Short: "Print anything to the screen", + Long: `an absolutely utterly useless command for testing.`, + Run: func(cmd *Command, args []string) { + tp = args + }, +} + +var cmdEcho = &Command{ + Use: "echo [string to echo]", + Aliases: []string{"say"}, + Short: "Echo anything to the screen", + Long: `an utterly useless command for testing.`, + Example: "Just run cobra-test echo", + PersistentPreRun: func(cmd *Command, args []string) { + echoPersPre = args + }, + PreRun: func(cmd *Command, args []string) { + echoPre = args + }, + Run: func(cmd *Command, args []string) { + te = args + }, +} + +var cmdEchoSub = &Command{ + Use: "echosub [string to print]", + Short: "second sub command for echo", + Long: `an absolutely utterly useless command for testing gendocs!.`, + Run: func(cmd *Command, args []string) { + }, +} + +var cmdDeprecated = &Command{ + Use: "deprecated [can't do anything here]", + Short: "A command which is deprecated", + Long: `an absolutely utterly useless command for testing deprecation!.`, + Deprecated: "Please use echo instead", + Run: func(cmd *Command, args []string) { + }, +} + +var cmdTimes = &Command{ + Use: "times [# times] [string to echo]", + Short: "Echo anything to the screen more times", + Long: `a slightly useless command for testing.`, + PersistentPreRun: func(cmd *Command, args []string) { + timesPersPre = args + }, + Run: func(cmd *Command, args []string) { + tt = args + }, +} + +var cmdRootNoRun = &Command{ + Use: "cobra-test", + Short: "The root can run it's own function", + Long: "The root description for help", + PersistentPreRun: func(cmd *Command, args []string) { + rootPersPre = args + }, +} + +var cmdRootSameName = &Command{ + Use: "print", + Short: "Root with the same name as a subcommand", + Long: "The root description for help", +} + +var cmdRootWithRun = &Command{ + Use: "cobra-test", + Short: "The root can run it's own function", + Long: "The root description for help", + Run: func(cmd *Command, args []string) { + tr = args + rootcalled = true + }, +} + +var cmdSubNoRun = &Command{ + Use: "subnorun", + Short: "A subcommand without a Run function", + Long: "A long output about a subcommand without a Run function", +} + +var cmdVersion1 = &Command{ + Use: "version", + Short: "Print the version number", + Long: `First version of the version command`, + Run: func(cmd *Command, args []string) { + versionUsed = 1 + }, +} + +var cmdVersion2 = &Command{ + Use: "version", + Short: "Print the version number", + Long: `Second version of the version command`, + Run: func(cmd *Command, args []string) { + versionUsed = 2 + }, +} + +func flagInit() { + cmdEcho.ResetFlags() + cmdPrint.ResetFlags() + cmdTimes.ResetFlags() + cmdRootNoRun.ResetFlags() + cmdRootSameName.ResetFlags() + cmdRootWithRun.ResetFlags() + cmdSubNoRun.ResetFlags() + cmdRootNoRun.PersistentFlags().StringVarP(&flags2a, "strtwo", "t", "two", strtwoParentHelp) + cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone") + cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo") + cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree") + cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone") + cmdEcho.PersistentFlags().BoolVarP(&flagbp, "persistentbool", "p", false, "help message for flag persistentbool") + cmdTimes.PersistentFlags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp) + cmdPrint.PersistentFlags().StringVarP(&flags3, "strthree", "s", "three", "help message for flag strthree") + cmdEcho.Flags().BoolVarP(&flagb1, "boolone", "b", true, "help message for flag boolone") + cmdTimes.Flags().BoolVarP(&flagb2, "booltwo", "c", false, "help message for flag booltwo") + cmdPrint.Flags().BoolVarP(&flagb3, "boolthree", "b", true, "help message for flag boolthree") + cmdVersion1.ResetFlags() + cmdVersion2.ResetFlags() +} + +func commandInit() { + cmdEcho.ResetCommands() + cmdPrint.ResetCommands() + cmdTimes.ResetCommands() + cmdRootNoRun.ResetCommands() + cmdRootSameName.ResetCommands() + cmdRootWithRun.ResetCommands() + cmdSubNoRun.ResetCommands() +} + +func initialize() *Command { + tt, tp, te = nil, nil, nil + rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil + + var c = cmdRootNoRun + flagInit() + commandInit() + return c +} + +func initializeWithSameName() *Command { + tt, tp, te = nil, nil, nil + rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil + var c = cmdRootSameName + flagInit() + commandInit() + return c +} + +func initializeWithRootCmd() *Command { + cmdRootWithRun.ResetCommands() + tt, tp, te, tr, rootcalled = nil, nil, nil, nil, false + flagInit() + cmdRootWithRun.Flags().BoolVarP(&flagbr, "boolroot", "b", false, "help message for flag boolroot") + cmdRootWithRun.Flags().IntVarP(&flagir, "introot", "i", 321, "help message for flag introot") + commandInit() + return cmdRootWithRun +} + +type resulter struct { + Error error + Output string + Command *Command +} + +func fullSetupTest(input string) resulter { + c := initializeWithRootCmd() + + return fullTester(c, input) +} + +func noRRSetupTest(input string) resulter { + c := initialize() + + return fullTester(c, input) +} + +func rootOnlySetupTest(input string) resulter { + c := initializeWithRootCmd() + + return simpleTester(c, input) +} + +func simpleTester(c *Command, input string) resulter { + buf := new(bytes.Buffer) + // Testing flag with invalid input + c.SetOutput(buf) + c.SetArgs(strings.Split(input, " ")) + + err := c.Execute() + output := buf.String() + + return resulter{err, output, c} +} + +func fullTester(c *Command, input string) resulter { + buf := new(bytes.Buffer) + // Testing flag with invalid input + c.SetOutput(buf) + cmdEcho.AddCommand(cmdTimes) + c.AddCommand(cmdPrint, cmdEcho, cmdSubNoRun, cmdDeprecated) + c.SetArgs(strings.Split(input, " ")) + + err := c.Execute() + output := buf.String() + + return resulter{err, output, c} +} + +func logErr(t *testing.T, found, expected string) { + out := new(bytes.Buffer) + + _, _, line, ok := runtime.Caller(2) + if ok { + fmt.Fprintf(out, "Line: %d ", line) + } + fmt.Fprintf(out, "Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) + t.Errorf(out.String()) +} + +func checkResultContains(t *testing.T, x resulter, check string) { + if !strings.Contains(x.Output, check) { + logErr(t, x.Output, check) + } +} + +func checkResultOmits(t *testing.T, x resulter, check string) { + if strings.Contains(x.Output, check) { + logErr(t, x.Output, check) + } +} + +func checkOutputContains(t *testing.T, c *Command, check string) { + buf := new(bytes.Buffer) + c.SetOutput(buf) + c.Execute() + + if !strings.Contains(buf.String(), check) { + logErr(t, buf.String(), check) + } +} + +func TestSingleCommand(t *testing.T) { + noRRSetupTest("print one two") + + if te != nil || tt != nil { + t.Error("Wrong command called") + } + if tp == nil { + t.Error("Wrong command called") + } + if strings.Join(tp, " ") != "one two" { + t.Error("Command didn't parse correctly") + } +} + +func TestChildCommand(t *testing.T) { + noRRSetupTest("echo times one two") + + if te != nil || tp != nil { + t.Error("Wrong command called") + } + if tt == nil { + t.Error("Wrong command called") + } + if strings.Join(tt, " ") != "one two" { + t.Error("Command didn't parse correctly") + } +} + +func TestCommandAlias(t *testing.T) { + noRRSetupTest("say times one two") + + if te != nil || tp != nil { + t.Error("Wrong command called") + } + if tt == nil { + t.Error("Wrong command called") + } + if strings.Join(tt, " ") != "one two" { + t.Error("Command didn't parse correctly") + } +} + +func TestPrefixMatching(t *testing.T) { + EnablePrefixMatching = true + noRRSetupTest("ech times one two") + + if te != nil || tp != nil { + t.Error("Wrong command called") + } + if tt == nil { + t.Error("Wrong command called") + } + if strings.Join(tt, " ") != "one two" { + t.Error("Command didn't parse correctly") + } + + EnablePrefixMatching = false +} + +func TestNoPrefixMatching(t *testing.T) { + EnablePrefixMatching = false + + noRRSetupTest("ech times one two") + + if !(tt == nil && te == nil && tp == nil) { + t.Error("Wrong command called") + } +} + +func TestAliasPrefixMatching(t *testing.T) { + EnablePrefixMatching = true + noRRSetupTest("sa times one two") + + if te != nil || tp != nil { + t.Error("Wrong command called") + } + if tt == nil { + t.Error("Wrong command called") + } + if strings.Join(tt, " ") != "one two" { + t.Error("Command didn't parse correctly") + } + EnablePrefixMatching = false +} + +func TestChildSameName(t *testing.T) { + c := initializeWithSameName() + c.AddCommand(cmdPrint, cmdEcho) + c.SetArgs(strings.Split("print one two", " ")) + c.Execute() + + if te != nil || tt != nil { + t.Error("Wrong command called") + } + if tp == nil { + t.Error("Wrong command called") + } + if strings.Join(tp, " ") != "one two" { + t.Error("Command didn't parse correctly") + } +} + +func TestGrandChildSameName(t *testing.T) { + c := initializeWithSameName() + cmdTimes.AddCommand(cmdPrint) + c.AddCommand(cmdTimes) + c.SetArgs(strings.Split("times print one two", " ")) + c.Execute() + + if te != nil || tt != nil { + t.Error("Wrong command called") + } + if tp == nil { + t.Error("Wrong command called") + } + if strings.Join(tp, " ") != "one two" { + t.Error("Command didn't parse correctly") + } +} + +func TestFlagLong(t *testing.T) { + noRRSetupTest("echo --intone=13 something here") + + if strings.Join(te, " ") != "something here" { + t.Errorf("flags didn't leave proper args remaining..%s given", te) + } + if flagi1 != 13 { + t.Errorf("int flag didn't get correct value, had %d", flagi1) + } + if flagi2 != 234 { + t.Errorf("default flag value changed, 234 expected, %d given", flagi2) + } +} + +func TestFlagShort(t *testing.T) { + noRRSetupTest("echo -i13 something here") + + if strings.Join(te, " ") != "something here" { + t.Errorf("flags didn't leave proper args remaining..%s given", te) + } + if flagi1 != 13 { + t.Errorf("int flag didn't get correct value, had %d", flagi1) + } + if flagi2 != 234 { + t.Errorf("default flag value changed, 234 expected, %d given", flagi2) + } + + noRRSetupTest("echo -i 13 something here") + + if strings.Join(te, " ") != "something here" { + t.Errorf("flags didn't leave proper args remaining..%s given", te) + } + if flagi1 != 13 { + t.Errorf("int flag didn't get correct value, had %d", flagi1) + } + if flagi2 != 234 { + t.Errorf("default flag value changed, 234 expected, %d given", flagi2) + } + + noRRSetupTest("print -i99 one two") + + if strings.Join(tp, " ") != "one two" { + t.Errorf("flags didn't leave proper args remaining..%s given", tp) + } + if flagi3 != 99 { + t.Errorf("int flag didn't get correct value, had %d", flagi3) + } + if flagi1 != 123 { + t.Errorf("default flag value changed on different command with same shortname, 234 expected, %d given", flagi2) + } +} + +func TestChildCommandFlags(t *testing.T) { + 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") + + if r.Error == nil { + t.Errorf("invalid flag should generate error") + } + + if !strings.Contains(r.Output, "unknown shorthand") { + t.Errorf("Wrong error message displayed, \n %s", r.Output) + } + + if flagi2 != 99 { + t.Errorf("flag value should be 99, %d given", flagi2) + } + + if flagi1 != 123 { + t.Errorf("unset flag should have default value, expecting 123, given %d", flagi1) + } + + // Testing with flag only existing on child + r = noRRSetupTest("echo -j 99 -i77 one two") + + if r.Error == nil { + t.Errorf("invalid flag should generate error") + } + + if !strings.Contains(r.Output, "unknown shorthand flag") { + t.Errorf("Wrong error message displayed, \n %s", r.Output) + } + + // Testing with persistent flag overwritten by child + noRRSetupTest("echo times --strtwo=child one two") + + if flags2b != "child" { + t.Errorf("flag value should be child, %s given", flags2b) + } + + if flags2a != "two" { + t.Errorf("unset flag should have default value, expecting two, given %s", flags2a) + } + + // Testing flag with invalid input + r = noRRSetupTest("echo -i10E") + + if r.Error == nil { + t.Errorf("invalid input should generate error") + } + + if !strings.Contains(r.Output, "invalid argument \"10E\" for i10E") { + t.Errorf("Wrong error message displayed, \n %s", r.Output) + } +} + +func TestTrailingCommandFlags(t *testing.T) { + x := fullSetupTest("echo two -x") + + if x.Error == nil { + t.Errorf("invalid flag should generate error") + } +} + +func TestInvalidSubcommandFlags(t *testing.T) { + cmd := initializeWithRootCmd() + cmd.AddCommand(cmdTimes) + + result := simpleTester(cmd, "times --inttwo=2 --badflag=bar") + + checkResultContains(t, result, "unknown flag: --badflag") + + if strings.Contains(result.Output, "unknown flag: --inttwo") { + t.Errorf("invalid --badflag flag shouldn't fail on 'unknown' --inttwo flag") + } + +} + +func TestSubcommandArgEvaluation(t *testing.T) { + cmd := initializeWithRootCmd() + + first := &Command{ + Use: "first", + Run: func(cmd *Command, args []string) { + }, + } + cmd.AddCommand(first) + + second := &Command{ + Use: "second", + Run: func(cmd *Command, args []string) { + fmt.Fprintf(cmd.Out(), "%v", args) + }, + } + first.AddCommand(second) + + result := simpleTester(cmd, "first second first third") + + expectedOutput := fmt.Sprintf("%v", []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") + + // persistentFlag should act like normal flag on it's own command + if strings.Join(te, " ") != "more here" { + t.Errorf("flags didn't leave proper args remaining..%s given", te) + } + if flags1 != "something" { + t.Errorf("string flag didn't get correct value, had %v", flags1) + } + if !flagbp { + t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp) + } + + // persistentFlag should act like normal flag on it's own command + 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) + } + + if flags1 != "again" { + t.Errorf("string flag didn't get correct value, had %v", flags1) + } + + if !flagb2 { + t.Errorf("local flag not parsed correctly. Expected true, had %v", flagb2) + } + if !flagbp { + t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp) + } +} + +func TestHelpCommand(t *testing.T) { + x := fullSetupTest("help") + checkResultContains(t, x, cmdRootWithRun.Long) + + x = fullSetupTest("help echo") + checkResultContains(t, x, cmdEcho.Long) + + x = fullSetupTest("help echo times") + checkResultContains(t, x, cmdTimes.Long) +} + +func TestChildCommandHelp(t *testing.T) { + c := noRRSetupTest("print --help") + checkResultContains(t, c, strtwoParentHelp) + r := noRRSetupTest("echo times --help") + checkResultContains(t, r, strtwoChildHelp) +} + +func TestNonRunChildHelp(t *testing.T) { + x := noRRSetupTest("subnorun") + checkResultContains(t, x, cmdSubNoRun.Long) +} + +func TestRunnableRootCommand(t *testing.T) { + fullSetupTest("") + + if rootcalled != true { + t.Errorf("Root Function was not called") + } +} + +func TestRunnableRootCommandNilInput(t *testing.T) { + empty_arg := make([]string, 0) + c := initializeWithRootCmd() + + buf := new(bytes.Buffer) + // Testing flag with invalid input + c.SetOutput(buf) + cmdEcho.AddCommand(cmdTimes) + c.AddCommand(cmdPrint, cmdEcho) + c.SetArgs(empty_arg) + + c.Execute() + + if rootcalled != true { + t.Errorf("Root Function was not called") + } +} + +func TestRunnableRootCommandEmptyInput(t *testing.T) { + args := make([]string, 3) + args[0] = "" + args[1] = "--introot=12" + args[2] = "" + c := initializeWithRootCmd() + + buf := new(bytes.Buffer) + // Testing flag with invalid input + c.SetOutput(buf) + cmdEcho.AddCommand(cmdTimes) + c.AddCommand(cmdPrint, cmdEcho) + c.SetArgs(args) + + c.Execute() + + if rootcalled != true { + t.Errorf("Root Function was not called.\n\nOutput was:\n\n%s\n", buf) + } +} + +func TestInvalidSubcommandWhenArgsAllowed(t *testing.T) { + fullSetupTest("echo invalid-sub") + + if te[0] != "invalid-sub" { + t.Errorf("Subcommand didn't work...") + } +} + +func TestRootFlags(t *testing.T) { + fullSetupTest("-i 17 -b") + + if flagbr != true { + t.Errorf("flag value should be true, %v given", flagbr) + } + + if flagir != 17 { + t.Errorf("flag value should be 17, %d given", flagir) + } +} + +func TestRootHelp(t *testing.T) { + x := fullSetupTest("--help") + + checkResultContains(t, x, "Available Commands:") + checkResultContains(t, x, "for more information about a command") + + if strings.Contains(x.Output, "unknown flag: --help") { + t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) + } + + if strings.Contains(x.Output, cmdEcho.Use) { + t.Errorf("--help shouldn't display subcommand's usage, Got: \n %s", x.Output) + } + + 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) + } + + checkResultContains(t, x, "Available Commands:") + checkResultContains(t, x, "for more information about a command") + + if strings.Contains(x.Output, "unknown flag: --help") { + t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) + } + +} + +func TestFlagAccess(t *testing.T) { + initialize() + + local := cmdTimes.LocalFlags() + inherited := cmdTimes.InheritedFlags() + + for _, f := range []string{"inttwo", "strtwo", "booltwo"} { + if local.Lookup(f) == nil { + t.Errorf("LocalFlags expected to contain %s, Got: nil", f) + } + } + if inherited.Lookup("strone") == nil { + t.Errorf("InheritedFlags expected to contain strone, Got: nil") + } + if inherited.Lookup("strtwo") != nil { + t.Errorf("InheritedFlags shouldn not contain overwritten flag strtwo") + + } +} + +func TestNoNRunnableRootCommandNilInput(t *testing.T) { + args := make([]string, 0) + c := initialize() + + buf := new(bytes.Buffer) + // Testing flag with invalid input + c.SetOutput(buf) + cmdEcho.AddCommand(cmdTimes) + c.AddCommand(cmdPrint, cmdEcho) + c.SetArgs(args) + + c.Execute() + + if !strings.Contains(buf.String(), cmdRootNoRun.Long) { + t.Errorf("Expected to get help output, Got: \n %s", buf) + } +} + +func TestRootNoCommandHelp(t *testing.T) { + x := rootOnlySetupTest("--help") + + checkResultOmits(t, x, "Available Commands:") + checkResultOmits(t, x, "for more information about a command") + + if strings.Contains(x.Output, "unknown flag: --help") { + t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) + } + + x = rootOnlySetupTest("echo --help") + + checkResultOmits(t, x, "Available Commands:") + checkResultOmits(t, x, "for more information about a command") + + if strings.Contains(x.Output, "unknown flag: --help") { + t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) + } +} + +func TestRootUnknownCommand(t *testing.T) { + r := noRRSetupTest("bogus") + s := "Error: unknown command \"bogus\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n" + + if r.Output != s { + t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output) + } + + 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) + } +} + +func TestFlagsBeforeCommand(t *testing.T) { + // short without space + 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) + //} + + // long with equals + 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") + if !strings.Contains(x.Output, "invalid argument \"10E\" for i10E") { + t.Errorf("Wrong error message displayed, \n %s", x.Output) + } + + //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) { + versionUsed = 0 + c := initializeWithRootCmd() + c.AddCommand(cmdVersion1) + c.RemoveCommand(cmdVersion1) + x := fullTester(c, "version") + if x.Error == nil { + t.Errorf("Removed command should not have been called\n") + return + } +} + +func TestCommandWithoutSubcommands(t *testing.T) { + c := initializeWithRootCmd() + + x := simpleTester(c, "") + if x.Error != nil { + t.Errorf("Calling command without subcommands should not have error: %v", x.Error) + return + } +} + +func TestCommandWithoutSubcommandsWithArg(t *testing.T) { + c := initializeWithRootCmd() + expectedArgs := []string{"arg"} + + x := simpleTester(c, "arg") + if x.Error != nil { + t.Errorf("Calling command without subcommands but with arg should not have error: %v", x.Error) + return + } + if !reflect.DeepEqual(expectedArgs, tr) { + t.Errorf("Calling command without subcommands but with arg has wrong args: expected: %v, actual: %v", expectedArgs, tr) + return + } +} + +func TestReplaceCommandWithRemove(t *testing.T) { + versionUsed = 0 + c := initializeWithRootCmd() + c.AddCommand(cmdVersion1) + c.RemoveCommand(cmdVersion1) + c.AddCommand(cmdVersion2) + x := fullTester(c, "version") + if x.Error != nil { + t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) + return + } + if versionUsed == 1 { + t.Errorf("Removed command shouldn't be called\n") + } + if versionUsed != 2 { + t.Errorf("Replacing command should have been called but didn't\n") + } +} + +func TestDeprecatedSub(t *testing.T) { + c := fullSetupTest("deprecated") + + checkResultContains(t, c, cmdDeprecated.Deprecated) +} + +func TestPreRun(t *testing.T) { + noRRSetupTest("echo one two") + if echoPre == nil || echoPersPre == nil { + t.Error("PreRun or PersistentPreRun not called") + } + if rootPersPre != nil || timesPersPre != nil { + t.Error("Wrong *Pre functions called!") + } + + noRRSetupTest("echo times one two") + if timesPersPre == nil { + t.Error("PreRun or PersistentPreRun not called") + } + if echoPre != nil || echoPersPre != nil || rootPersPre != nil { + t.Error("Wrong *Pre functions called!") + } + + noRRSetupTest("print one two") + if rootPersPre == nil { + t.Error("Parent PersistentPreRun not called but should not have been") + } + if echoPre != nil || echoPersPre != nil || timesPersPre != nil { + t.Error("Wrong *Pre functions called!") + } +} + +// Check if cmdEchoSub gets PersistentPreRun from rootCmd even if is added last +func TestPeristentPreRunPropagation(t *testing.T) { + rootCmd := initialize() + + // First add the cmdEchoSub to cmdPrint + cmdPrint.AddCommand(cmdEchoSub) + // Now add cmdPrint to rootCmd + rootCmd.AddCommand(cmdPrint) + + rootCmd.SetArgs(strings.Split("print echosub lala", " ")) + rootCmd.Execute() + + if rootPersPre == nil || len(rootPersPre) == 0 || rootPersPre[0] != "lala" { + t.Error("RootCmd PersistentPreRun not called but should have been") + } +} + +func TestGlobalNormFuncPropagation(t *testing.T) { + normFunc := func(f *pflag.FlagSet, name string) pflag.NormalizedName { + return pflag.NormalizedName(name) + } + + rootCmd := initialize() + rootCmd.SetGlobalNormalizationFunc(normFunc) + if reflect.ValueOf(normFunc) != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()) { + t.Error("rootCmd seems to have a wrong normalization function") + } + + // First add the cmdEchoSub to cmdPrint + cmdPrint.AddCommand(cmdEchoSub) + if cmdPrint.GlobalNormalizationFunc() != nil && cmdEchoSub.GlobalNormalizationFunc() != nil { + t.Error("cmdPrint and cmdEchoSub should had no normalization functions") + } + + // Now add cmdPrint to rootCmd + rootCmd.AddCommand(cmdPrint) + if reflect.ValueOf(cmdPrint.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() || + reflect.ValueOf(cmdEchoSub.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() { + t.Error("cmdPrint and cmdEchoSub should had the normalization function of rootCmd") } } diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go index 15b81127..74565c2b 100644 --- a/vendor/github.com/spf13/cobra/command.go +++ b/vendor/github.com/spf13/cobra/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 ( @@ -20,230 +20,145 @@ import ( "fmt" "io" "os" - "path/filepath" - "sort" + "runtime" "strings" + "time" + "github.com/inconshreveable/mousetrap" flag "github.com/spf13/pflag" ) // Command is just that, a command for your application. -// E.g. 'go run ...' - 'run' is the command. Cobra requires +// eg. '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 { - // Use is the one-line usage message. + // Name is the command name, usually the executable's name. + name string + // The one-line usage message. Use string - - // Aliases is an array of aliases that can be used instead of the first word in Use. + // An array of aliases that can be used instead of the first word in Use. Aliases []string - - // SuggestFor is an array of command names for which this command will be suggested - - // similar to aliases but only suggests. - SuggestFor []string - - // Short is the short description shown in the 'help' output. + // The short description shown in the 'help' output. Short string - - // Long is the long message shown in the 'help ' output. + // The long message shown in the 'help ' output. Long string - - // Example is examples of how to use the command. + // Examples of how to use the command Example string - - // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions + // List of all valid non-flag arguments, used for bash completions *TODO* actually validate these ValidArgs []string - - // Expected arguments - Args PositionalArgs - - // 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 - - // BashCompletionFunction is custom functions used by the bash autocompletion generator. + // Custom functions used by the bash autocompletion generator BashCompletionFunction string - - // Deprecated defines, if this command is deprecated and should print this string when used. + // Is this command deprecated and should print this string when used? Deprecated string - - // 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. - Annotations map[string]string - - // Version defines the version for this command. If this value is non-empty and the command does not - // define a "version" flag, a "version" boolean flag will be added to the command and, if specified, - // will print content of the "Version" variable. - Version 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 // 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 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 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 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 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 func(cmd *Command, args []string) error - - // 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 - - // DisableFlagsInUseLine will disable the addition of [flags] to the usage - // line of a command when printing help or generating docs - DisableFlagsInUseLine bool - - // 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 - - // TraverseChildren parses flags on all parents before executing child command. - TraverseChildren bool - - // commands is the list of commands supported by this program. + // Commands is the list of commands supported by this program. commands []*Command - // parent is a parent command for this command. + // 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 - // commandsAreSorted defines, if command slice are sorted or not. - commandsAreSorted bool - // commandCalledAs is the name or alias value used to call this command. - commandCalledAs struct { - name string - called bool - } - // args is actual args parsed from flags. - args []string - // flagErrorBuf contains all error messages from pflag. flagErrorBuf *bytes.Buffer - // 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 - // 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 - // versionTemplate is the version template defined by user. - versionTemplate string + args []string // actual args parsed from flags + output *io.Writer // nil means stderr; use Out() method instead + usageFunc func(*Command) error // Usage can be defined by application + usageTemplate string // Can be defined by Application + helpTemplate string // Can be defined by Application + helpFunc func(*Command, []string) // Help can be defined by application + helpCommand *Command // The help command + helpFlagVal bool + // The global normalization function that we can use on every pFlag set and children commands + globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName } -// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden +// os.Args[1:] by default, if desired, can be overridden // particularly useful when testing. func (c *Command) SetArgs(a []string) { c.args = a } +func (c *Command) getOut(def io.Writer) io.Writer { + if c.output != nil { + return *c.output + } + + if c.HasParent() { + return c.parent.Out() + } else { + return def + } +} + +func (c *Command) Out() io.Writer { + return c.getOut(os.Stderr) +} + +func (c *Command) getOutOrStdout() io.Writer { + return c.getOut(os.Stdout) +} + // SetOutput sets the destination for usage and error messages. // If output is nil, os.Stderr is used. func (c *Command) SetOutput(output io.Writer) { - c.output = output + c.output = &output } -// SetUsageFunc sets usage function. Usage can be defined by application. +// Usage can be defined by application func (c *Command) SetUsageFunc(f func(*Command) error) { c.usageFunc = f } -// SetUsageTemplate sets usage template. Can be defined by Application. +// Can be defined by Application func (c *Command) SetUsageTemplate(s string) { c.usageTemplate = s } -// SetFlagErrorFunc sets a function to generate an error when flag parsing -// fails. -func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) { - c.flagErrorFunc = f -} - -// SetHelpFunc sets help function. Can be defined by Application. +// Can be defined by Application func (c *Command) SetHelpFunc(f func(*Command, []string)) { c.helpFunc = f } -// SetHelpCommand sets help command. func (c *Command) SetHelpCommand(cmd *Command) { c.helpCommand = cmd } -// SetHelpTemplate sets help template to be used. Application can use it to set custom template. +// Can be defined by Application func (c *Command) SetHelpTemplate(s string) { c.helpTemplate = s } -// SetVersionTemplate sets version template to be used. Application can use it to set custom template. -func (c *Command) SetVersionTemplate(s string) { - c.versionTemplate = s -} - // SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. // The user should not have a cyclic dependency on commands. func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) { c.Flags().SetNormalizeFunc(n) c.PersistentFlags().SetNormalizeFunc(n) + c.LocalFlags().SetNormalizeFunc(n) c.globNormFunc = n for _, command := range c.commands { @@ -251,135 +166,81 @@ func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string } } -// OutOrStdout returns output to stdout. -func (c *Command) OutOrStdout() io.Writer { - return c.getOut(os.Stdout) -} - -// OutOrStderr returns output to stderr -func (c *Command) OutOrStderr() io.Writer { - return c.getOut(os.Stderr) -} - -func (c *Command) getOut(def io.Writer) io.Writer { - if c.output != nil { - return c.output - } - if c.HasParent() { - return c.parent.getOut(def) - } - return def -} - -// UsageFunc returns either the function set by SetUsageFunc for this command -// or a parent, or it returns a default usage function. func (c *Command) UsageFunc() (f func(*Command) error) { if c.usageFunc != nil { return c.usageFunc } + if c.HasParent() { - return c.Parent().UsageFunc() - } - return func(c *Command) error { - c.mergePersistentFlags() - err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c) - if err != nil { - c.Println(err) + return c.parent.UsageFunc() + } else { + return func(c *Command) error { + err := tmpl(c.Out(), c.UsageTemplate(), c) + return err } - return err } } - -// Usage puts out the usage for the command. -// Used when a user provides invalid input. -// Can be defined by user by overriding UsageFunc. -func (c *Command) Usage() error { - return c.UsageFunc()(c) -} - -// HelpFunc returns either the function set by SetHelpFunc for this command -// or a parent, or it returns a function with default help behavior. func (c *Command) HelpFunc() func(*Command, []string) { if c.helpFunc != nil { return c.helpFunc } + if c.HasParent() { - return c.Parent().HelpFunc() - } - return func(c *Command, a []string) { - c.mergePersistentFlags() - err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c) - if err != nil { - c.Println(err) + return c.parent.HelpFunc() + } else { + return func(c *Command, args []string) { + if len(args) == 0 { + // Help called without any topic, calling on root + c.Root().Help() + return + } + + cmd, _, e := c.Root().Find(args) + if cmd == nil || e != nil { + c.Printf("Unknown help topic %#q.", args) + + c.Root().Usage() + } else { + err := cmd.Help() + if err != nil { + c.Println(err) + } + } } } } -// Help puts out the help for the command. -// Used when a user calls help [command]. -// Can be defined by user by overriding HelpFunc. -func (c *Command) Help() error { - c.HelpFunc()(c, []string{}) - return nil -} +var minUsagePadding int = 25 -// UsageString return usage string. -func (c *Command) UsageString() string { - tmpOutput := c.output - bb := new(bytes.Buffer) - c.SetOutput(bb) - c.Usage() - c.output = tmpOutput - return bb.String() -} - -// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this -// command or a parent, or it returns a function which returns the original -// error. -func (c *Command) FlagErrorFunc() (f func(*Command, error) error) { - if c.flagErrorFunc != nil { - return c.flagErrorFunc - } - - if c.HasParent() { - return c.parent.FlagErrorFunc() - } - return func(c *Command, err error) error { - return err - } -} - -var minUsagePadding = 25 - -// UsagePadding return padding for the usage. func (c *Command) UsagePadding() int { if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen { return minUsagePadding + } else { + return c.parent.commandsMaxUseLen } - return c.parent.commandsMaxUseLen } -var minCommandPathPadding = 11 +var minCommandPathPadding int = 11 -// CommandPathPadding return padding for the command path. +// func (c *Command) CommandPathPadding() int { if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen { return minCommandPathPadding + } else { + return c.parent.commandsMaxCommandPathLen } - return c.parent.commandsMaxCommandPathLen } -var minNamePadding = 11 +var minNamePadding int = 11 -// NamePadding returns padding for the name. func (c *Command) NamePadding() int { if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen { return minNamePadding + } else { + return c.parent.commandsMaxNameLen } - return c.parent.commandsMaxNameLen } -// UsageTemplate returns usage template for the command. func (c *Command) UsageTemplate() string { if c.usageTemplate != "" { return c.usageTemplate @@ -387,34 +248,36 @@ func (c *Command) UsageTemplate() string { if c.HasParent() { return c.parent.UsageTemplate() - } - return `Usage:{{if .Runnable}} - {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}} - {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}} + } else { + return `{{ $cmd := . }} +Usage: {{if .Runnable}} + {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}} + {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}} Aliases: - {{.NameAndAliases}}{{end}}{{if .HasExample}} + {{.NameAndAliases}} +{{end}}{{if .HasExample}} Examples: -{{.Example}}{{end}}{{if .HasAvailableSubCommands}} +{{ .Example }}{{end}}{{ if .HasNonHelpSubCommands}} -Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}} - {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}} +Available Commands: {{range .Commands}}{{if (not .IsHelpCommand)}} + {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasLocalFlags}} Flags: -{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}} +{{.LocalFlags.FlagUsages}}{{end}}{{ if .HasInheritedFlags}} Global Flags: -{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}} +{{.InheritedFlags.FlagUsages}}{{end}}{{if .HasHelpSubCommands}} -Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}} - {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}} +Additional help topics: {{range .Commands}}{{if .IsHelpCommand}} + {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}}{{end}}{{end}}{{ if .HasSubCommands }} -Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}} -` +Use "{{.CommandPath}} [command] --help" for more information about a command. +{{end}}` + } } -// HelpTemplate return help template for the command. func (c *Command) HelpTemplate() string { if c.helpTemplate != "" { return c.helpTemplate @@ -422,77 +285,74 @@ func (c *Command) HelpTemplate() string { if c.HasParent() { return c.parent.HelpTemplate() - } - return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}} - -{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` -} - -// VersionTemplate return version template for the command. -func (c *Command) VersionTemplate() string { - if c.versionTemplate != "" { - return c.versionTemplate - } - - if c.HasParent() { - return c.parent.VersionTemplate() - } - return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}} + } else { + return `{{with or .Long .Short }}{{. | trim}}{{end}} +{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}} ` + } } -func hasNoOptDefVal(name string, fs *flag.FlagSet) bool { - flag := fs.Lookup(name) +// Really only used when casting a command to a commander +func (c *Command) resetChildrensParents() { + for _, x := range c.commands { + x.parent = c + } +} + +// Test if the named flag is a boolean flag. +func isBooleanFlag(name string, f *flag.FlagSet) bool { + flag := f.Lookup(name) if flag == nil { return false } - return flag.NoOptDefVal != "" + return flag.Value.Type() == "bool" } -func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool { - if len(name) == 0 { - return false - } - - flag := fs.ShorthandLookup(name[:1]) - if flag == nil { - return false - } - return flag.NoOptDefVal != "" +// Test if the named flag is a boolean flag. +func isBooleanShortFlag(name string, f *flag.FlagSet) bool { + result := false + f.VisitAll(func(f *flag.Flag) { + if f.Shorthand == name && f.Value.Type() == "bool" { + result = true + } + }) + return result } func stripFlags(args []string, c *Command) []string { - if len(args) == 0 { + if len(args) < 1 { return args } c.mergePersistentFlags() commands := []string{} - flags := c.Flags() -Loop: - for len(args) > 0 { - s := args[0] - args = args[1:] - switch { - case s == "--": - // "--" terminates the flags - break Loop - 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 + inQuote := false + inFlag := false + for _, y := range args { + if !inQuote { + switch { + case strings.HasPrefix(y, "\""): + inQuote = true + case strings.Contains(y, "=\""): + inQuote = true + case strings.HasPrefix(y, "--") && !strings.Contains(y, "="): + // TODO: this isn't quite right, we should really check ahead for 'true' or 'false' + inFlag = !isBooleanFlag(y[2:], c.Flags()) + case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()): + inFlag = true + case inFlag: + inFlag = false + case y == "": + // strip empty commands, as the go tests expect this to be ok.... + case !strings.HasPrefix(y, "-"): + commands = append(commands, y) + inFlag = false } - case s != "" && !strings.HasPrefix(s, "-"): - commands = append(commands, s) + } + + if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") { + inQuote = false } } @@ -513,14 +373,13 @@ func argsMinusFirstX(args []string, x string) []string { return args } -func isFlagArg(arg string) bool { - return ((len(arg) >= 3 && arg[1] == '-') || - (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-')) -} - -// Find the target command given the args and command tree +// find the target command given the args and command tree // Meant to be run on the highest node. Only searches down. func (c *Command) Find(args []string) (*Command, []string, error) { + if c == nil { + return nil, nil, fmt.Errorf("Called find() on a nil Command") + } + var innerfind func(*Command, []string) (*Command, []string) innerfind = func(c *Command, innerArgs []string) (*Command, []string) { @@ -529,141 +388,58 @@ func (c *Command) Find(args []string) (*Command, []string, error) { return c, innerArgs } nextSubCmd := argsWOflags[0] - - cmd := c.findNext(nextSubCmd) - if cmd != nil { - return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd)) + matches := make([]*Command, 0) + for _, cmd := range c.commands { + if cmd.Name() == nextSubCmd || cmd.HasAlias(nextSubCmd) { // exact name or alias match + return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd)) + } + if EnablePrefixMatching { + if strings.HasPrefix(cmd.Name(), nextSubCmd) { // prefix match + matches = append(matches, cmd) + } + for _, x := range cmd.Aliases { + if strings.HasPrefix(x, nextSubCmd) { + matches = append(matches, cmd) + } + } + } } + + // only accept a single prefix match - multiple matches would be ambiguous + if len(matches) == 1 { + return innerfind(matches[0], argsMinusFirstX(innerArgs, argsWOflags[0])) + } + return c, innerArgs } commandFound, a := innerfind(c, args) - if commandFound.Args == nil { - return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound)) + argsWOflags := stripFlags(a, commandFound) + + // no subcommand, always take args + if !commandFound.HasSubCommands() { + return commandFound, a, nil } + // root command with subcommands, do subcommand checking + if commandFound == c && len(argsWOflags) > 0 { + return commandFound, a, fmt.Errorf("unknown command %q for %q", argsWOflags[0], commandFound.CommandPath()) + } + return commandFound, a, nil } -func (c *Command) findSuggestions(arg string) string { - if c.DisableSuggestions { - return "" - } - if c.SuggestionsMinimumDistance <= 0 { - c.SuggestionsMinimumDistance = 2 - } - suggestionsString := "" - if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 { - suggestionsString += "\n\nDid you mean this?\n" - for _, s := range suggestions { - suggestionsString += fmt.Sprintf("\t%v\n", s) - } - } - return suggestionsString -} - -func (c *Command) findNext(next string) *Command { - matches := make([]*Command, 0) - for _, cmd := range c.commands { - if cmd.Name() == next || cmd.HasAlias(next) { - cmd.commandCalledAs.name = next - return cmd - } - if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) { - matches = append(matches, cmd) - } - } - - if len(matches) == 1 { - return matches[0] - } - - return nil -} - -// Traverse the command tree to find the command, and parse args for -// each parent. -func (c *Command) Traverse(args []string) (*Command, []string, error) { - flags := []string{} - inFlag := false - - for i, arg := range args { - switch { - // A long flag with a space separated value - case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="): - // TODO: this isn't quite right, we should really check ahead for 'true' or 'false' - inFlag = !hasNoOptDefVal(arg[2:], c.Flags()) - flags = append(flags, arg) - continue - // A short flag with a space separated value - case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()): - inFlag = true - flags = append(flags, arg) - continue - // The value for a flag - case inFlag: - inFlag = false - flags = append(flags, arg) - continue - // A flag without a value, or with an `=` separated value - case isFlagArg(arg): - flags = append(flags, arg) - continue - } - - cmd := c.findNext(arg) - if cmd == nil { - return c, args, nil - } - - if err := c.ParseFlags(flags); err != nil { - return nil, args, err - } - return cmd.Traverse(args[i+1:]) - } - return c, args, nil -} - -// SuggestionsFor provides suggestions for the typedName. -func (c *Command) SuggestionsFor(typedName string) []string { - suggestions := []string{} - for _, cmd := range c.commands { - if cmd.IsAvailableCommand() { - levenshteinDistance := ld(typedName, cmd.Name(), true) - suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance - suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName)) - if suggestByLevenshtein || suggestByPrefix { - suggestions = append(suggestions, cmd.Name()) - } - for _, explicitSuggestion := range cmd.SuggestFor { - if strings.EqualFold(typedName, explicitSuggestion) { - suggestions = append(suggestions, cmd.Name()) - } - } - } - } - return suggestions -} - -// VisitParents visits all parents of the command and invokes fn on each parent. -func (c *Command) VisitParents(fn func(*Command)) { - if c.HasParent() { - fn(c.Parent()) - c.Parent().VisitParents(fn) - } -} - -// Root finds root command. func (c *Command) Root() *Command { - if c.HasParent() { - return c.Parent().Root() - } - return c -} + var findRoot func(*Command) *Command -// ArgsLenAtDash will return the length of c.Flags().Args at the moment -// when a -- was found during args parsing. -func (c *Command) ArgsLenAtDash() int { - return c.Flags().ArgsLenAtDash() + findRoot = func(x *Command) *Command { + if x.HasParent() { + return findRoot(x.parent) + } else { + return x + } + } + + return findRoot(c) } func (c *Command) execute(a []string) (err error) { @@ -675,104 +451,36 @@ func (c *Command) execute(a []string) (err error) { c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated) } - // initialize help and version flag at the last point possible to allow for user - // overriding - c.InitDefaultHelpFlag() - c.InitDefaultVersionFlag() - err = c.ParseFlags(a) if err != nil { - return c.FlagErrorFunc()(c, err) - } - - // 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 InitDefaultHelpFlag() - c.Println("\"help\" flag declared as non-bool. Please correct your code") return err } - - if helpVal { - return flag.ErrHelp - } - - // for back-compat, only add version flag behavior if version is defined - if c.Version != "" { - versionVal, err := c.Flags().GetBool("version") - if err != nil { - c.Println("\"version\" flag declared as non-bool. Please correct your code") - return err - } - if versionVal { - err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c) - if err != nil { - c.Println(err) - } - return err - } - } - - if !c.Runnable() { + // If help is called, regardless of other flags, return we want help + // Also say we need help if c.Run is nil. + if c.helpFlagVal || !c.Runnable() { return flag.ErrHelp } c.preRun() - argWoFlags := c.Flags().Args() - if c.DisableFlagParsing { - argWoFlags = a - } - - if err := c.ValidateArgs(argWoFlags); err != nil { - return err - } for p := c; p != nil; p = p.Parent() { - if p.PersistentPreRunE != nil { - if err := p.PersistentPreRunE(c, argWoFlags); err != nil { - return err - } - break - } else if p.PersistentPreRun != nil { + if p.PersistentPreRun != nil { p.PersistentPreRun(c, argWoFlags) break } } - if c.PreRunE != nil { - if err := c.PreRunE(c, argWoFlags); err != nil { - return err - } - } else if c.PreRun != nil { + if c.PreRun != nil { c.PreRun(c, argWoFlags) } - if err := c.validateRequiredFlags(); err != nil { - return err - } - if c.RunE != nil { - if err := c.RunE(c, argWoFlags); err != nil { - return err - } - } else { - c.Run(c, argWoFlags) - } - if c.PostRunE != nil { - if err := c.PostRunE(c, argWoFlags); err != nil { - return err - } - } else if c.PostRun != nil { + c.Run(c, argWoFlags) + + if c.PostRun != nil { c.PostRun(c, argWoFlags) } for p := c; p != nil; p = p.Parent() { - if p.PersistentPostRunE != nil { - if err := p.PersistentPostRunE(c, argWoFlags); err != nil { - return err - } - break - } else if p.PersistentPostRun != nil { + if p.PersistentPostRun != nil { p.PersistentPostRun(c, argWoFlags) break } @@ -787,202 +495,99 @@ func (c *Command) preRun() { } } -// Execute uses the args (os.Args[1:] by default) -// and run through the command tree finding appropriate matches -// for commands and then corresponding flags. -func (c *Command) Execute() error { - _, err := c.ExecuteC() - return err +func (c *Command) errorMsgFromParse() string { + s := c.flagErrorBuf.String() + + x := strings.Split(s, "\n") + + if len(x) > 0 { + return x[0] + } else { + return "" + } } -// ExecuteC executes the command. -func (c *Command) ExecuteC() (cmd *Command, err error) { +// Call execute to use the args (os.Args[1:] by default) +// and run through the command tree finding appropriate matches +// for commands and then corresponding flags. +func (c *Command) Execute() (err error) { + // Regardless of what command execute is called on, run on Root only if c.HasParent() { - return c.Root().ExecuteC() + return c.Root().Execute() } - // windows hook - if preExecHookFn != nil { - preExecHookFn(c) + if EnableWindowsMouseTrap && runtime.GOOS == "windows" { + if mousetrap.StartedByExplorer() { + c.Print(MousetrapHelpText) + time.Sleep(5 * time.Second) + os.Exit(1) + } } // initialize help as the last point possible to allow for user // overriding - c.InitDefaultHelpCmd() + c.initHelp() var args []string - // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155 - if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" { + if len(c.args) == 0 { args = os.Args[1:] } else { args = c.args } - var flags []string - if c.TraverseChildren { - cmd, flags, err = c.Traverse(args) - } else { - cmd, flags, err = c.Find(args) - } + cmd, flags, err := c.Find(args) if err != nil { // If found parse to a subcommand and then failed, talk about the subcommand if cmd != nil { c = cmd } - if !c.SilenceErrors { - c.Println("Error:", err.Error()) - c.Printf("Run '%v --help' for usage.\n", c.CommandPath()) - } - return c, err - } - - cmd.commandCalledAs.called = true - if cmd.commandCalledAs.name == "" { - cmd.commandCalledAs.name = cmd.Name() + c.Println("Error:", err.Error()) + c.Printf("Run '%v --help' for usage.\n", c.CommandPath()) + return err } err = cmd.execute(flags) if err != nil { - // Always show help if requested, even if SilenceErrors is in - // effect if err == flag.ErrHelp { - cmd.HelpFunc()(cmd, args) - return cmd, nil - } - - // If root command has SilentErrors flagged, - // all subcommands should respect it - if !cmd.SilenceErrors && !c.SilenceErrors { - c.Println("Error:", err.Error()) - } - - // If root command has SilentUsage flagged, - // all subcommands should respect it - if !cmd.SilenceUsage && !c.SilenceUsage { - c.Println(cmd.UsageString()) + cmd.Help() + return nil } + c.Println(cmd.UsageString()) + c.Println("Error:", err.Error()) } - return cmd, err + + return } -func (c *Command) ValidateArgs(args []string) error { - if c.Args == nil { - return nil - } - return c.Args(c, args) -} - -func (c *Command) validateRequiredFlags() error { - flags := c.Flags() - missingFlagNames := []string{} - flags.VisitAll(func(pflag *flag.Flag) { - requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag] - if !found { +func (c *Command) initHelp() { + if c.helpCommand == nil { + if !c.HasSubCommands() { return } - if (requiredAnnotation[0] == "true") && !pflag.Changed { - missingFlagNames = append(missingFlagNames, pflag.Name) - } - }) - if len(missingFlagNames) > 0 { - return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`)) - } - return nil -} - -// InitDefaultHelpFlag adds default help flag to c. -// It is called automatically by executing the c or by calling help and usage. -// If c already has help flag, it will do nothing. -func (c *Command) InitDefaultHelpFlag() { - c.mergePersistentFlags() - if c.Flags().Lookup("help") == nil { - usage := "help for " - if c.Name() == "" { - usage += "this command" - } else { - usage += c.Name() - } - c.Flags().BoolP("help", "h", false, usage) - } -} - -// InitDefaultVersionFlag adds default version flag to c. -// It is called automatically by executing the c. -// If c already has a version flag, it will do nothing. -// If c.Version is empty, it will do nothing. -func (c *Command) InitDefaultVersionFlag() { - if c.Version == "" { - return - } - - c.mergePersistentFlags() - if c.Flags().Lookup("version") == nil { - usage := "version for " - if c.Name() == "" { - usage += "this command" - } else { - usage += c.Name() - } - c.Flags().Bool("version", false, usage) - } -} - -// 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.HasSubCommands() { - return - } - - if c.helpCommand == nil { 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.`, - - 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() - } - }, + Simply type ` + c.Name() + ` help [path to command] for full details.`, + Run: c.HelpFunc(), + PersistentPreRun: func(cmd *Command, args []string) {}, + PersistentPostRun: func(cmd *Command, args []string) {}, } } - c.RemoveCommand(c.helpCommand) c.AddCommand(c.helpCommand) } -// ResetCommands delete parent, subcommand and help command from c. +// Used for testing func (c *Command) ResetCommands() { - c.parent = nil c.commands = nil c.helpCommand = nil - c.parentsPflags = nil } -// Sorts commands by their names. -type commandSorterByName []*Command - -func (c commandSorterByName) Len() int { return len(c) } -func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] } -func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() } - -// Commands returns a sorted slice of child commands. +//Commands returns a slice of child commands. func (c *Command) Commands() []*Command { - // do not sort commands if it already sorted or sorting was disabled - if EnableCommandSorting && !c.commandsAreSorted { - sort.Sort(commandSorterByName(c.commands)) - c.commandsAreSorted = true - } return c.commands } @@ -1006,16 +611,15 @@ func (c *Command) AddCommand(cmds ...*Command) { if nameLen > c.commandsMaxNameLen { c.commandsMaxNameLen = nameLen } - // If global normalization function exists, update all children + // If glabal normalization function exists, update all children if c.globNormFunc != nil { x.SetGlobalNormalizationFunc(c.globNormFunc) } c.commands = append(c.commands, x) - c.commandsAreSorted = false } } -// RemoveCommand removes one or more commands from a parent command. +// AddCommand removes one or more commands from a parent command. func (c *Command) RemoveCommand(cmds ...*Command) { commands := []*Command{} main: @@ -1049,48 +653,72 @@ main: } } -// Print is a convenience method to Print to the defined output, fallback to Stderr if not set. +// Convenience method to Print to the defined output func (c *Command) Print(i ...interface{}) { - fmt.Fprint(c.OutOrStderr(), i...) + fmt.Fprint(c.Out(), i...) } -// Println is a convenience method to Println to the defined output, fallback to Stderr if not set. +// Convenience method to Println to the defined output func (c *Command) Println(i ...interface{}) { - c.Print(fmt.Sprintln(i...)) + str := fmt.Sprintln(i...) + c.Print(str) } -// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set. +// Convenience method to Printf to the defined output func (c *Command) Printf(format string, i ...interface{}) { - c.Print(fmt.Sprintf(format, i...)) + str := fmt.Sprintf(format, i...) + c.Print(str) +} + +// Output the usage for the command +// Used when a user provides invalid input +// Can be defined by user by overriding UsageFunc +func (c *Command) Usage() error { + c.mergePersistentFlags() + err := c.UsageFunc()(c) + return err +} + +// Output the help for the command +// Used when a user calls help [command] +// by the default HelpFunc in the commander +func (c *Command) Help() error { + c.mergePersistentFlags() + err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c) + return err +} + +func (c *Command) UsageString() string { + tmpOutput := c.output + bb := new(bytes.Buffer) + c.SetOutput(bb) + c.Usage() + c.output = tmpOutput + return bb.String() } // CommandPath returns the full path to this command. func (c *Command) CommandPath() string { - if c.HasParent() { - return c.Parent().CommandPath() + " " + c.Name() + str := c.Name() + x := c + for x.HasParent() { + str = x.parent.Name() + " " + str + x = x.parent } - return c.Name() + return str } -// UseLine puts out the full usage for a given command (including parents). +//The full usage for a given command (including parents) func (c *Command) UseLine() string { - var useline string + str := "" if c.HasParent() { - useline = c.parent.CommandPath() + " " + c.Use - } else { - useline = c.Use + str = c.parent.CommandPath() + " " } - if c.DisableFlagsInUseLine { - return useline - } - if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") { - useline += " [flags]" - } - return useline + return str + c.Use } -// DebugFlags used to determine which flags have been assigned to which commands -// and which persist. +// For use in determining which flags have been assigned to which commands +// and which persist func (c *Command) DebugFlags() { c.Println("DebugFlags called on", c.Name()) var debugflags func(*Command) @@ -1101,8 +729,12 @@ func (c *Command) DebugFlags() { } if x.HasFlags() { x.flags.VisitAll(func(f *flag.Flag) { - if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]") + if x.HasPersistentFlags() { + if x.persistentFlag(f.Name) == nil { + c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]") + } else { + c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]") + } } else { c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]") } @@ -1132,6 +764,9 @@ func (c *Command) DebugFlags() { // Name returns the command's name: the first word in the use line. func (c *Command) Name() string { + if c.name != "" { + return c.name + } name := c.Use i := strings.Index(name, " ") if i >= 0 { @@ -1140,7 +775,7 @@ func (c *Command) Name() string { return name } -// HasAlias determines if a given string is an alias of the command. +// Determine if a given string is an alias of the command. func (c *Command) HasAlias(s string) bool { for _, a := range c.Aliases { if a == s { @@ -1150,134 +785,74 @@ func (c *Command) HasAlias(s string) bool { return false } -// CalledAs returns the command name or alias that was used to invoke -// this command or an empty string if the command has not been called. -func (c *Command) CalledAs() string { - if c.commandCalledAs.called { - return c.commandCalledAs.name - } - return "" -} - -// hasNameOrAliasPrefix returns true if the Name or any of aliases start -// with prefix -func (c *Command) hasNameOrAliasPrefix(prefix string) bool { - if strings.HasPrefix(c.Name(), prefix) { - c.commandCalledAs.name = c.Name() - return true - } - for _, alias := range c.Aliases { - if strings.HasPrefix(alias, prefix) { - c.commandCalledAs.name = alias - return true - } - } - return false -} - -// NameAndAliases returns a list of the command name and all aliases func (c *Command) NameAndAliases() string { return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ") } -// HasExample determines if the command has example. func (c *Command) HasExample() bool { return len(c.Example) > 0 } -// Runnable determines if the command is itself runnable. +// Determine if the command is itself runnable func (c *Command) Runnable() bool { - return c.Run != nil || c.RunE != nil + return c.Run != nil } -// HasSubCommands determines if the command has children commands. +// Determine if the command has children commands func (c *Command) HasSubCommands() bool { return len(c.commands) > 0 } -// IsAvailableCommand determines if a command is available as a non-help command -// (this includes all non deprecated/hidden commands). -func (c *Command) IsAvailableCommand() bool { - if len(c.Deprecated) != 0 || c.Hidden { +func (c *Command) IsHelpCommand() bool { + if c.Runnable() { return false } - - if c.HasParent() && c.Parent().helpCommand == c { - return false - } - - if c.Runnable() || c.HasAvailableSubCommands() { - return true - } - - return false -} - -// IsAdditionalHelpTopicCommand determines if a command is an additional -// help topic command; additional help topic command is determined by the -// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that -// are runnable/hidden/deprecated. -// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924. -func (c *Command) IsAdditionalHelpTopicCommand() bool { - // if a command is runnable, deprecated, or hidden it is not a 'help' command - if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden { - return false - } - - // if any non-help sub commands are found, the command is not a 'help' command for _, sub := range c.commands { - if !sub.IsAdditionalHelpTopicCommand() { + if len(sub.Deprecated) != 0 { + continue + } + if !sub.IsHelpCommand() { return false } } - - // the command either has no sub commands, or no non-help sub commands return true } -// HasHelpSubCommands determines if a command has any available 'help' sub commands -// that need to be shown in the usage/help default template under 'additional help -// topics'. func (c *Command) HasHelpSubCommands() bool { - // return true on the first found available 'help' sub command for _, sub := range c.commands { - if sub.IsAdditionalHelpTopicCommand() { + if len(sub.Deprecated) != 0 { + continue + } + if sub.IsHelpCommand() { return true } } - - // the command either has no sub commands, or no available 'help' sub commands return false } -// HasAvailableSubCommands determines if a command has available sub commands that -// need to be shown in the usage/help default template under 'available commands'. -func (c *Command) HasAvailableSubCommands() bool { - // return true on the first found available (non deprecated/help/hidden) - // sub command +func (c *Command) HasNonHelpSubCommands() bool { for _, sub := range c.commands { - if sub.IsAvailableCommand() { + if len(sub.Deprecated) != 0 { + continue + } + if !sub.IsHelpCommand() { return true } } - - // the command either has no sub commands, or no available (non deprecated/help/hidden) - // sub commands return false } -// HasParent determines if the command is a child command. +// Determine if the command is a child command func (c *Command) HasParent() bool { return c.parent != nil } -// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist. +// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName { return c.globNormFunc } -// Flags returns the complete FlagSet that applies -// to this command (local and persistent declared here and by all parents). +// Get the complete FlagSet that applies to this command (local and persistent declared here and by all parents) func (c *Command) Flags() *flag.FlagSet { if c.flags == nil { c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) @@ -1285,81 +860,57 @@ func (c *Command) Flags() *flag.FlagSet { c.flagErrorBuf = new(bytes.Buffer) } c.flags.SetOutput(c.flagErrorBuf) + c.PersistentFlags().BoolVarP(&c.helpFlagVal, "help", "h", false, "help for "+c.Name()) } - return c.flags } -// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands. -func (c *Command) LocalNonPersistentFlags() *flag.FlagSet { - persistentFlags := c.PersistentFlags() - - out := flag.NewFlagSet(c.Name(), flag.ContinueOnError) - c.LocalFlags().VisitAll(func(f *flag.Flag) { - if persistentFlags.Lookup(f.Name) == nil { - out.AddFlag(f) - } - }) - return out -} - -// LocalFlags returns the local FlagSet specifically set in the current command. +// Get the local FlagSet specifically set in the current command func (c *Command) LocalFlags() *flag.FlagSet { c.mergePersistentFlags() - if c.lflags == nil { - c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - c.lflags.SetOutput(c.flagErrorBuf) - } - c.lflags.SortFlags = c.Flags().SortFlags - if c.globNormFunc != nil { - c.lflags.SetNormalizeFunc(c.globNormFunc) - } - - addToLocal := func(f *flag.Flag) { - if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil { - c.lflags.AddFlag(f) - } - } - c.Flags().VisitAll(addToLocal) - c.PersistentFlags().VisitAll(addToLocal) - return c.lflags + local := flag.NewFlagSet(c.Name(), flag.ContinueOnError) + c.lflags.VisitAll(func(f *flag.Flag) { + local.AddFlag(f) + }) + return local } -// InheritedFlags returns all flags which were inherited from parents commands. +// All Flags which were inherited from parents commands func (c *Command) InheritedFlags() *flag.FlagSet { c.mergePersistentFlags() - 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) - } - + inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError) local := c.LocalFlags() - if c.globNormFunc != nil { - c.iflags.SetNormalizeFunc(c.globNormFunc) + + var rmerge func(x *Command) + + rmerge = func(x *Command) { + if x.HasPersistentFlags() { + x.PersistentFlags().VisitAll(func(f *flag.Flag) { + if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil { + inherited.AddFlag(f) + } + }) + } + if x.HasParent() { + rmerge(x.parent) + } } - c.parentsPflags.VisitAll(func(f *flag.Flag) { - if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil { - c.iflags.AddFlag(f) - } - }) - return c.iflags + if c.HasParent() { + rmerge(c.parent) + } + + return inherited } -// NonInheritedFlags returns all flags which were not inherited from parent commands. +// All Flags which were not inherited from parent commands func (c *Command) NonInheritedFlags() *flag.FlagSet { return c.LocalFlags() } -// PersistentFlags returns the persistent FlagSet specifically set in the current command. +// Get the Persistent FlagSet specifically set in the current command func (c *Command) PersistentFlags() *flag.FlagSet { if c.pflags == nil { c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) @@ -1371,7 +922,7 @@ func (c *Command) PersistentFlags() *flag.FlagSet { return c.pflags } -// ResetFlags deletes all flags from command. +// For use in testing func (c *Command) ResetFlags() { c.flagErrorBuf = new(bytes.Buffer) c.flagErrorBuf.Reset() @@ -1379,56 +930,28 @@ func (c *Command) ResetFlags() { c.flags.SetOutput(c.flagErrorBuf) c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) c.pflags.SetOutput(c.flagErrorBuf) - - c.lflags = nil - c.iflags = nil - c.parentsPflags = nil } -// HasFlags checks if the command contains any flags (local plus persistent from the entire structure). +// Does the command contain any flags (local plus persistent from the entire structure) func (c *Command) HasFlags() bool { return c.Flags().HasFlags() } -// HasPersistentFlags checks if the command contains persistent flags. +// Does the command contain persistent flags func (c *Command) HasPersistentFlags() bool { return c.PersistentFlags().HasFlags() } -// HasLocalFlags checks if the command has flags specifically declared locally. +// Does the command has flags specifically declared locally func (c *Command) HasLocalFlags() bool { return c.LocalFlags().HasFlags() } -// HasInheritedFlags checks if the command has flags inherited from its parent command. func (c *Command) HasInheritedFlags() bool { return c.InheritedFlags().HasFlags() } -// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire -// structure) which are not hidden or deprecated. -func (c *Command) HasAvailableFlags() bool { - return c.Flags().HasAvailableFlags() -} - -// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated. -func (c *Command) HasAvailablePersistentFlags() bool { - return c.PersistentFlags().HasAvailableFlags() -} - -// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden -// or deprecated. -func (c *Command) HasAvailableLocalFlags() bool { - return c.LocalFlags().HasAvailableFlags() -} - -// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are -// not hidden or deprecated. -func (c *Command) HasAvailableInheritedFlags() bool { - return c.InheritedFlags().HasAvailableFlags() -} - -// Flag climbs up the command tree looking for matching flag. +// Climbs up the command tree looking for matching flag func (c *Command) Flag(name string) (flag *flag.Flag) { flag = c.Flags().Lookup(name) @@ -1439,69 +962,64 @@ func (c *Command) Flag(name string) (flag *flag.Flag) { return } -// Recursively find matching persistent flag. +// recursively find matching persistent flag func (c *Command) persistentFlag(name string) (flag *flag.Flag) { if c.HasPersistentFlags() { flag = c.PersistentFlags().Lookup(name) } - if flag == nil { - c.updateParentsPflags() - flag = c.parentsPflags.Lookup(name) + if flag == nil && c.HasParent() { + flag = c.parent.persistentFlag(name) } return } -// ParseFlags parses persistent flag tree and local flags. -func (c *Command) ParseFlags(args []string) error { - if c.DisableFlagParsing { - return nil - } - - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - beforeErrorBufLen := c.flagErrorBuf.Len() +// Parses persistent flag tree & local flags +func (c *Command) ParseFlags(args []string) (err error) { c.mergePersistentFlags() - err := c.Flags().Parse(args) - // Print warnings if they occurred (e.g. deprecated flag messages). - if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil { - c.Print(c.flagErrorBuf.String()) - } - - return err + err = c.Flags().Parse(args) + return } -// Parent returns a commands parent command. func (c *Command) Parent() *Command { return c.parent } -// mergePersistentFlags merges c.PersistentFlags() to c.Flags() -// and adds missing persistent flags of all parents. func (c *Command) mergePersistentFlags() { - c.updateParentsPflags() - c.Flags().AddFlagSet(c.PersistentFlags()) - c.Flags().AddFlagSet(c.parentsPflags) -} + var rmerge func(x *Command) -// updateParentsPflags updates c.parentsPflags by adding -// new persistent flags of all parents. -// If c.parentsPflags == nil, it makes new. -func (c *Command) updateParentsPflags() { - if c.parentsPflags == nil { - c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - c.parentsPflags.SetOutput(c.flagErrorBuf) - c.parentsPflags.SortFlags = false + // Save the set of local flags + if c.lflags == nil { + c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) + if c.flagErrorBuf == nil { + c.flagErrorBuf = new(bytes.Buffer) + } + c.lflags.SetOutput(c.flagErrorBuf) + addtolocal := func(f *flag.Flag) { + c.lflags.AddFlag(f) + } + c.Flags().VisitAll(addtolocal) + c.PersistentFlags().VisitAll(addtolocal) + } + rmerge = func(x *Command) { + if !x.HasParent() { + flag.CommandLine.VisitAll(func(f *flag.Flag) { + if x.PersistentFlags().Lookup(f.Name) == nil { + x.PersistentFlags().AddFlag(f) + } + }) + } + if x.HasPersistentFlags() { + x.PersistentFlags().VisitAll(func(f *flag.Flag) { + if c.Flags().Lookup(f.Name) == nil { + c.Flags().AddFlag(f) + } + }) + } + if x.HasParent() { + rmerge(x.parent) + } } - if c.globNormFunc != nil { - c.parentsPflags.SetNormalizeFunc(c.globNormFunc) - } - - c.Root().PersistentFlags().AddFlagSet(flag.CommandLine) - - c.VisitParents(func(parent *Command) { - c.parentsPflags.AddFlagSet(parent.PersistentFlags()) - }) + rmerge(c) } diff --git a/vendor/github.com/spf13/cobra/command_notwin.go b/vendor/github.com/spf13/cobra/command_notwin.go deleted file mode 100644 index 6159c1cc..00000000 --- a/vendor/github.com/spf13/cobra/command_notwin.go +++ /dev/null @@ -1,5 +0,0 @@ -// +build !windows - -package cobra - -var preExecHookFn func(*Command) diff --git a/vendor/github.com/spf13/cobra/command_test.go b/vendor/github.com/spf13/cobra/command_test.go index d874a9a5..477d84e7 100644 --- a/vendor/github.com/spf13/cobra/command_test.go +++ b/vendor/github.com/spf13/cobra/command_test.go @@ -1,463 +1,10 @@ package cobra import ( - "bytes" - "fmt" - "os" "reflect" - "strings" "testing" - - "github.com/spf13/pflag" ) -func emptyRun(*Command, []string) {} - -func executeCommand(root *Command, args ...string) (output string, err error) { - _, output, err = executeCommandC(root, args...) - return output, err -} - -func executeCommandC(root *Command, args ...string) (c *Command, output string, err error) { - buf := new(bytes.Buffer) - root.SetOutput(buf) - root.SetArgs(args) - - c, err = root.ExecuteC() - - return c, buf.String(), err -} - -func resetCommandLineFlagSet() { - pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError) -} - -func checkStringContains(t *testing.T, got, expected string) { - if !strings.Contains(got, expected) { - t.Errorf("Expected to contain: \n %v\nGot:\n %v\n", expected, got) - } -} - -func checkStringOmits(t *testing.T, got, expected string) { - if strings.Contains(got, expected) { - t.Errorf("Expected to not contain: \n %v\nGot: %v", expected, got) - } -} - -func TestSingleCommand(t *testing.T) { - var rootCmdArgs []string - rootCmd := &Command{ - Use: "root", - Args: ExactArgs(2), - Run: func(_ *Command, args []string) { rootCmdArgs = args }, - } - aCmd := &Command{Use: "a", Args: NoArgs, Run: emptyRun} - bCmd := &Command{Use: "b", Args: NoArgs, Run: emptyRun} - rootCmd.AddCommand(aCmd, bCmd) - - output, err := executeCommand(rootCmd, "one", "two") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - got := strings.Join(rootCmdArgs, " ") - expected := "one two" - if got != expected { - t.Errorf("rootCmdArgs expected: %q, got: %q", expected, got) - } -} - -func TestChildCommand(t *testing.T) { - var child1CmdArgs []string - rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} - child1Cmd := &Command{ - Use: "child1", - Args: ExactArgs(2), - Run: func(_ *Command, args []string) { child1CmdArgs = args }, - } - child2Cmd := &Command{Use: "child2", Args: NoArgs, Run: emptyRun} - rootCmd.AddCommand(child1Cmd, child2Cmd) - - output, err := executeCommand(rootCmd, "child1", "one", "two") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - got := strings.Join(child1CmdArgs, " ") - expected := "one two" - if got != expected { - t.Errorf("child1CmdArgs expected: %q, got: %q", expected, got) - } -} - -func TestCallCommandWithoutSubcommands(t *testing.T) { - rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} - _, err := executeCommand(rootCmd) - if err != nil { - t.Errorf("Calling command without subcommands should not have error: %v", err) - } -} - -func TestRootExecuteUnknownCommand(t *testing.T) { - rootCmd := &Command{Use: "root", Run: emptyRun} - rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun}) - - output, _ := executeCommand(rootCmd, "unknown") - - expected := "Error: unknown command \"unknown\" for \"root\"\nRun 'root --help' for usage.\n" - - if output != expected { - t.Errorf("Expected:\n %q\nGot:\n %q\n", expected, output) - } -} - -func TestSubcommandExecuteC(t *testing.T) { - rootCmd := &Command{Use: "root", Run: emptyRun} - childCmd := &Command{Use: "child", Run: emptyRun} - rootCmd.AddCommand(childCmd) - - c, output, err := executeCommandC(rootCmd, "child") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if c.Name() != "child" { - t.Errorf(`invalid command returned from ExecuteC: expected "child"', got %q`, c.Name()) - } -} - -func TestRootUnknownCommandSilenced(t *testing.T) { - rootCmd := &Command{Use: "root", Run: emptyRun} - rootCmd.SilenceErrors = true - rootCmd.SilenceUsage = true - rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun}) - - output, _ := executeCommand(rootCmd, "unknown") - if output != "" { - t.Errorf("Expected blank output, because of silenced usage.\nGot:\n %q\n", output) - } -} - -func TestCommandAlias(t *testing.T) { - var timesCmdArgs []string - rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} - echoCmd := &Command{ - Use: "echo", - Aliases: []string{"say", "tell"}, - Args: NoArgs, - Run: emptyRun, - } - timesCmd := &Command{ - Use: "times", - Args: ExactArgs(2), - Run: func(_ *Command, args []string) { timesCmdArgs = args }, - } - echoCmd.AddCommand(timesCmd) - rootCmd.AddCommand(echoCmd) - - output, err := executeCommand(rootCmd, "tell", "times", "one", "two") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - got := strings.Join(timesCmdArgs, " ") - expected := "one two" - if got != expected { - t.Errorf("timesCmdArgs expected: %v, got: %v", expected, got) - } -} - -func TestEnablePrefixMatching(t *testing.T) { - EnablePrefixMatching = true - - var aCmdArgs []string - rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} - aCmd := &Command{ - Use: "aCmd", - Args: ExactArgs(2), - Run: func(_ *Command, args []string) { aCmdArgs = args }, - } - bCmd := &Command{Use: "bCmd", Args: NoArgs, Run: emptyRun} - rootCmd.AddCommand(aCmd, bCmd) - - output, err := executeCommand(rootCmd, "a", "one", "two") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - got := strings.Join(aCmdArgs, " ") - expected := "one two" - if got != expected { - t.Errorf("aCmdArgs expected: %q, got: %q", expected, got) - } - - EnablePrefixMatching = false -} - -func TestAliasPrefixMatching(t *testing.T) { - EnablePrefixMatching = true - - var timesCmdArgs []string - rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} - echoCmd := &Command{ - Use: "echo", - Aliases: []string{"say", "tell"}, - Args: NoArgs, - Run: emptyRun, - } - timesCmd := &Command{ - Use: "times", - Args: ExactArgs(2), - Run: func(_ *Command, args []string) { timesCmdArgs = args }, - } - echoCmd.AddCommand(timesCmd) - rootCmd.AddCommand(echoCmd) - - output, err := executeCommand(rootCmd, "sa", "times", "one", "two") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - got := strings.Join(timesCmdArgs, " ") - expected := "one two" - if got != expected { - t.Errorf("timesCmdArgs expected: %v, got: %v", expected, got) - } - - EnablePrefixMatching = false -} - -// TestChildSameName checks the correct behaviour of cobra in cases, -// when an application with name "foo" and with subcommand "foo" -// is executed with args "foo foo". -func TestChildSameName(t *testing.T) { - var fooCmdArgs []string - rootCmd := &Command{Use: "foo", Args: NoArgs, Run: emptyRun} - fooCmd := &Command{ - Use: "foo", - Args: ExactArgs(2), - Run: func(_ *Command, args []string) { fooCmdArgs = args }, - } - barCmd := &Command{Use: "bar", Args: NoArgs, Run: emptyRun} - rootCmd.AddCommand(fooCmd, barCmd) - - output, err := executeCommand(rootCmd, "foo", "one", "two") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - got := strings.Join(fooCmdArgs, " ") - expected := "one two" - if got != expected { - t.Errorf("fooCmdArgs expected: %v, got: %v", expected, got) - } -} - -// TestGrandChildSameName checks the correct behaviour of cobra in cases, -// when user has a root command and a grand child -// with the same name. -func TestGrandChildSameName(t *testing.T) { - var fooCmdArgs []string - rootCmd := &Command{Use: "foo", Args: NoArgs, Run: emptyRun} - barCmd := &Command{Use: "bar", Args: NoArgs, Run: emptyRun} - fooCmd := &Command{ - Use: "foo", - Args: ExactArgs(2), - Run: func(_ *Command, args []string) { fooCmdArgs = args }, - } - barCmd.AddCommand(fooCmd) - rootCmd.AddCommand(barCmd) - - output, err := executeCommand(rootCmd, "bar", "foo", "one", "two") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - got := strings.Join(fooCmdArgs, " ") - expected := "one two" - if got != expected { - t.Errorf("fooCmdArgs expected: %v, got: %v", expected, got) - } -} - -func TestFlagLong(t *testing.T) { - var cArgs []string - c := &Command{ - Use: "c", - Args: ArbitraryArgs, - Run: func(_ *Command, args []string) { cArgs = args }, - } - - var intFlagValue int - var stringFlagValue string - c.Flags().IntVar(&intFlagValue, "intf", -1, "") - c.Flags().StringVar(&stringFlagValue, "sf", "", "") - - output, err := executeCommand(c, "--intf=7", "--sf=abc", "one", "--", "two") - if output != "" { - t.Errorf("Unexpected output: %v", err) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if c.ArgsLenAtDash() != 1 { - t.Errorf("Expected ArgsLenAtDash: %v but got %v", 1, c.ArgsLenAtDash()) - } - if intFlagValue != 7 { - t.Errorf("Expected intFlagValue: %v, got %v", 7, intFlagValue) - } - if stringFlagValue != "abc" { - t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue) - } - - got := strings.Join(cArgs, " ") - expected := "one two" - if got != expected { - t.Errorf("Expected arguments: %q, got %q", expected, got) - } -} - -func TestFlagShort(t *testing.T) { - var cArgs []string - c := &Command{ - Use: "c", - Args: ArbitraryArgs, - Run: func(_ *Command, args []string) { cArgs = args }, - } - - var intFlagValue int - var stringFlagValue string - c.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "") - c.Flags().StringVarP(&stringFlagValue, "sf", "s", "", "") - - output, err := executeCommand(c, "-i", "7", "-sabc", "one", "two") - if output != "" { - t.Errorf("Unexpected output: %v", err) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if intFlagValue != 7 { - t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue) - } - if stringFlagValue != "abc" { - t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue) - } - - got := strings.Join(cArgs, " ") - expected := "one two" - if got != expected { - t.Errorf("Expected arguments: %q, got %q", expected, got) - } -} - -func TestChildFlag(t *testing.T) { - rootCmd := &Command{Use: "root", Run: emptyRun} - childCmd := &Command{Use: "child", Run: emptyRun} - rootCmd.AddCommand(childCmd) - - var intFlagValue int - childCmd.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "") - - output, err := executeCommand(rootCmd, "child", "-i7") - if output != "" { - t.Errorf("Unexpected output: %v", err) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if intFlagValue != 7 { - t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue) - } -} - -func TestChildFlagWithParentLocalFlag(t *testing.T) { - rootCmd := &Command{Use: "root", Run: emptyRun} - childCmd := &Command{Use: "child", Run: emptyRun} - rootCmd.AddCommand(childCmd) - - var intFlagValue int - rootCmd.Flags().StringP("sf", "s", "", "") - childCmd.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "") - - _, err := executeCommand(rootCmd, "child", "-i7", "-sabc") - if err == nil { - t.Errorf("Invalid flag should generate error") - } - - checkStringContains(t, err.Error(), "unknown shorthand") - - if intFlagValue != 7 { - t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue) - } -} - -func TestFlagInvalidInput(t *testing.T) { - rootCmd := &Command{Use: "root", Run: emptyRun} - rootCmd.Flags().IntP("intf", "i", -1, "") - - _, err := executeCommand(rootCmd, "-iabc") - if err == nil { - t.Errorf("Invalid flag value should generate error") - } - - checkStringContains(t, err.Error(), "invalid syntax") -} - -func TestFlagBeforeCommand(t *testing.T) { - rootCmd := &Command{Use: "root", Run: emptyRun} - childCmd := &Command{Use: "child", Run: emptyRun} - rootCmd.AddCommand(childCmd) - - var flagValue int - childCmd.Flags().IntVarP(&flagValue, "intf", "i", -1, "") - - // With short flag. - _, err := executeCommand(rootCmd, "-i7", "child") - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - if flagValue != 7 { - t.Errorf("Expected flag value: %v, got %v", 7, flagValue) - } - - // With long flag. - _, err = executeCommand(rootCmd, "--intf=8", "child") - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - if flagValue != 8 { - t.Errorf("Expected flag value: %v, got %v", 9, flagValue) - } -} - func TestStripFlags(t *testing.T) { tests := []struct { input []string @@ -468,11 +15,11 @@ func TestStripFlags(t *testing.T) { []string{"foo", "bar"}, }, { - []string{"foo", "--str", "-s"}, + []string{"foo", "--bar", "-b"}, []string{"foo"}, }, { - []string{"-s", "foo", "--str", "bar"}, + []string{"-b", "foo", "--bar", "bar"}, []string{}, }, { @@ -488,7 +35,7 @@ func TestStripFlags(t *testing.T) { []string{"echo"}, }, { - []string{"-ib", "echo", "-sfoo", "baz"}, + []string{"-ib", "echo", "-bfoo", "baz"}, []string{"echo", "baz"}, }, { @@ -496,15 +43,15 @@ func TestStripFlags(t *testing.T) { []string{"bar", "blah"}, }, { - []string{"--int=baz", "-sbar", "-i", "foo", "blah"}, + []string{"--int=baz", "-bbar", "-i", "foo", "blah"}, []string{"blah"}, }, { - []string{"--bool", "bar", "-i", "foo", "blah"}, + []string{"--cat", "bar", "-i", "foo", "blah"}, []string{"bar", "blah"}, }, { - []string{"-b", "bar", "-i", "foo", "blah"}, + []string{"-c", "bar", "-i", "foo", "blah"}, []string{"bar", "blah"}, }, { @@ -517,1112 +64,27 @@ func TestStripFlags(t *testing.T) { }, } - c := &Command{Use: "c", Run: emptyRun} - c.PersistentFlags().BoolP("persist", "p", false, "") - c.Flags().IntP("int", "i", -1, "") - c.Flags().StringP("str", "s", "", "") - c.Flags().BoolP("bool", "b", false, "") + cmdPrint := &Command{ + Use: "print [string to print]", + Short: "Print anything to the screen", + Long: `an utterly useless command for testing.`, + Run: func(cmd *Command, args []string) { + tp = args + }, + } - for i, test := range tests { - got := stripFlags(test.input, c) - if !reflect.DeepEqual(test.output, got) { - t.Errorf("(%v) Expected: %v, got: %v", i, test.output, got) + var flagi int + var flagstr string + var flagbool bool + cmdPrint.PersistentFlags().BoolVarP(&flagbool, "persist", "p", false, "help for persistent one") + cmdPrint.Flags().IntVarP(&flagi, "int", "i", 345, "help message for flag int") + cmdPrint.Flags().StringVarP(&flagstr, "bar", "b", "bar", "help message for flag string") + cmdPrint.Flags().BoolVarP(&flagbool, "cat", "c", false, "help message for flag bool") + + for _, test := range tests { + output := stripFlags(test.input, cmdPrint) + if !reflect.DeepEqual(test.output, output) { + t.Errorf("expected: %v, got: %v", test.output, output) } } } - -func TestDisableFlagParsing(t *testing.T) { - var cArgs []string - c := &Command{ - Use: "c", - DisableFlagParsing: true, - Run: func(_ *Command, args []string) { - cArgs = args - }, - } - - args := []string{"cmd", "-v", "-race", "-file", "foo.go"} - output, err := executeCommand(c, args...) - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if !reflect.DeepEqual(args, cArgs) { - t.Errorf("Expected: %v, got: %v", args, cArgs) - } -} - -func TestPersistentFlagsOnSameCommand(t *testing.T) { - var rootCmdArgs []string - rootCmd := &Command{ - Use: "root", - Args: ArbitraryArgs, - Run: func(_ *Command, args []string) { rootCmdArgs = args }, - } - - var flagValue int - rootCmd.PersistentFlags().IntVarP(&flagValue, "intf", "i", -1, "") - - output, err := executeCommand(rootCmd, "-i7", "one", "two") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - got := strings.Join(rootCmdArgs, " ") - expected := "one two" - if got != expected { - t.Errorf("rootCmdArgs expected: %q, got %q", expected, got) - } - if flagValue != 7 { - t.Errorf("flagValue expected: %v, got %v", 7, flagValue) - } -} - -// TestEmptyInputs checks, -// if flags correctly parsed with blank strings in args. -func TestEmptyInputs(t *testing.T) { - c := &Command{Use: "c", Run: emptyRun} - - var flagValue int - c.Flags().IntVarP(&flagValue, "intf", "i", -1, "") - - output, err := executeCommand(c, "", "-i7", "") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if flagValue != 7 { - t.Errorf("flagValue expected: %v, got %v", 7, flagValue) - } -} - -func TestOverwrittenFlag(t *testing.T) { - // TODO: This test fails, but should work. - t.Skip() - - parent := &Command{Use: "parent", Run: emptyRun} - child := &Command{Use: "child", Run: emptyRun} - - parent.PersistentFlags().Bool("boolf", false, "") - parent.PersistentFlags().Int("intf", -1, "") - child.Flags().String("strf", "", "") - child.Flags().Int("intf", -1, "") - - parent.AddCommand(child) - - childInherited := child.InheritedFlags() - childLocal := child.LocalFlags() - - if childLocal.Lookup("strf") == nil { - t.Error(`LocalFlags expected to contain "strf", got "nil"`) - } - if childInherited.Lookup("boolf") == nil { - t.Error(`InheritedFlags expected to contain "boolf", got "nil"`) - } - - if childInherited.Lookup("intf") != nil { - t.Errorf(`InheritedFlags should not contain overwritten flag "intf"`) - } - if childLocal.Lookup("intf") == nil { - t.Error(`LocalFlags expected to contain "intf", got "nil"`) - } -} - -func TestPersistentFlagsOnChild(t *testing.T) { - var childCmdArgs []string - rootCmd := &Command{Use: "root", Run: emptyRun} - childCmd := &Command{ - Use: "child", - Args: ArbitraryArgs, - Run: func(_ *Command, args []string) { childCmdArgs = args }, - } - rootCmd.AddCommand(childCmd) - - var parentFlagValue int - var childFlagValue int - rootCmd.PersistentFlags().IntVarP(&parentFlagValue, "parentf", "p", -1, "") - childCmd.Flags().IntVarP(&childFlagValue, "childf", "c", -1, "") - - output, err := executeCommand(rootCmd, "child", "-c7", "-p8", "one", "two") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - got := strings.Join(childCmdArgs, " ") - expected := "one two" - if got != expected { - t.Errorf("childCmdArgs expected: %q, got %q", expected, got) - } - if parentFlagValue != 8 { - t.Errorf("parentFlagValue expected: %v, got %v", 8, parentFlagValue) - } - if childFlagValue != 7 { - t.Errorf("childFlagValue expected: %v, got %v", 7, childFlagValue) - } -} - -func TestRequiredFlags(t *testing.T) { - c := &Command{Use: "c", Run: emptyRun} - c.Flags().String("foo1", "", "") - c.MarkFlagRequired("foo1") - c.Flags().String("foo2", "", "") - c.MarkFlagRequired("foo2") - c.Flags().String("bar", "", "") - - expected := fmt.Sprintf("required flag(s) %q, %q not set", "foo1", "foo2") - - _, err := executeCommand(c) - got := err.Error() - - if got != expected { - t.Errorf("Expected error: %q, got: %q", expected, got) - } -} - -func TestPersistentRequiredFlags(t *testing.T) { - parent := &Command{Use: "parent", Run: emptyRun} - parent.PersistentFlags().String("foo1", "", "") - parent.MarkPersistentFlagRequired("foo1") - parent.PersistentFlags().String("foo2", "", "") - parent.MarkPersistentFlagRequired("foo2") - parent.Flags().String("foo3", "", "") - - child := &Command{Use: "child", Run: emptyRun} - child.Flags().String("bar1", "", "") - child.MarkFlagRequired("bar1") - child.Flags().String("bar2", "", "") - child.MarkFlagRequired("bar2") - child.Flags().String("bar3", "", "") - - parent.AddCommand(child) - - expected := fmt.Sprintf("required flag(s) %q, %q, %q, %q not set", "bar1", "bar2", "foo1", "foo2") - - _, err := executeCommand(parent, "child") - if err.Error() != expected { - t.Errorf("Expected %q, got %q", expected, err.Error()) - } -} - -func TestInitHelpFlagMergesFlags(t *testing.T) { - usage := "custom flag" - rootCmd := &Command{Use: "root"} - rootCmd.PersistentFlags().Bool("help", false, "custom flag") - childCmd := &Command{Use: "child"} - rootCmd.AddCommand(childCmd) - - childCmd.InitDefaultHelpFlag() - got := childCmd.Flags().Lookup("help").Usage - if got != usage { - t.Errorf("Expected the help flag from the root command with usage: %v\nGot the default with usage: %v", usage, got) - } -} - -func TestHelpCommandExecuted(t *testing.T) { - rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun} - rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun}) - - output, err := executeCommand(rootCmd, "help") - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - checkStringContains(t, output, rootCmd.Long) -} - -func TestHelpCommandExecutedOnChild(t *testing.T) { - rootCmd := &Command{Use: "root", Run: emptyRun} - childCmd := &Command{Use: "child", Long: "Long description", Run: emptyRun} - rootCmd.AddCommand(childCmd) - - output, err := executeCommand(rootCmd, "help", "child") - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - checkStringContains(t, output, childCmd.Long) -} - -func TestSetHelpCommand(t *testing.T) { - c := &Command{Use: "c", Run: emptyRun} - c.AddCommand(&Command{Use: "empty", Run: emptyRun}) - - expected := "WORKS" - c.SetHelpCommand(&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.`, - Run: func(c *Command, _ []string) { c.Print(expected) }, - }) - - got, err := executeCommand(c, "help") - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if got != expected { - t.Errorf("Expected to contain %q, got %q", expected, got) - } -} - -func TestHelpFlagExecuted(t *testing.T) { - rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun} - - output, err := executeCommand(rootCmd, "--help") - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - checkStringContains(t, output, rootCmd.Long) -} - -func TestHelpFlagExecutedOnChild(t *testing.T) { - rootCmd := &Command{Use: "root", Run: emptyRun} - childCmd := &Command{Use: "child", Long: "Long description", Run: emptyRun} - rootCmd.AddCommand(childCmd) - - output, err := executeCommand(rootCmd, "child", "--help") - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - checkStringContains(t, output, childCmd.Long) -} - -// TestHelpFlagInHelp checks, -// if '--help' flag is shown in help for child (executing `parent help child`), -// that has no other flags. -// Related to https://github.com/spf13/cobra/issues/302. -func TestHelpFlagInHelp(t *testing.T) { - parentCmd := &Command{Use: "parent", Run: func(*Command, []string) {}} - - childCmd := &Command{Use: "child", Run: func(*Command, []string) {}} - parentCmd.AddCommand(childCmd) - - output, err := executeCommand(parentCmd, "help", "child") - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - checkStringContains(t, output, "[flags]") -} - -func TestFlagsInUsage(t *testing.T) { - rootCmd := &Command{Use: "root", Args: NoArgs, Run: func(*Command, []string) {}} - output, err := executeCommand(rootCmd, "--help") - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - checkStringContains(t, output, "[flags]") -} - -func TestHelpExecutedOnNonRunnableChild(t *testing.T) { - rootCmd := &Command{Use: "root", Run: emptyRun} - childCmd := &Command{Use: "child", Long: "Long description"} - rootCmd.AddCommand(childCmd) - - output, err := executeCommand(rootCmd, "child") - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - checkStringContains(t, output, childCmd.Long) -} - -func TestVersionFlagExecuted(t *testing.T) { - rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun} - - output, err := executeCommand(rootCmd, "--version", "arg1") - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - checkStringContains(t, output, "root version 1.0.0") -} - -func TestVersionTemplate(t *testing.T) { - rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun} - rootCmd.SetVersionTemplate(`customized version: {{.Version}}`) - - output, err := executeCommand(rootCmd, "--version", "arg1") - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - checkStringContains(t, output, "customized version: 1.0.0") -} - -func TestVersionFlagExecutedOnSubcommand(t *testing.T) { - rootCmd := &Command{Use: "root", Version: "1.0.0"} - rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun}) - - output, err := executeCommand(rootCmd, "--version", "sub") - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - checkStringContains(t, output, "root version 1.0.0") -} - -func TestVersionFlagOnlyAddedToRoot(t *testing.T) { - rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun} - rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun}) - - _, err := executeCommand(rootCmd, "sub", "--version") - if err == nil { - t.Errorf("Expected error") - } - - checkStringContains(t, err.Error(), "unknown flag: --version") -} - -func TestVersionFlagOnlyExistsIfVersionNonEmpty(t *testing.T) { - rootCmd := &Command{Use: "root", Run: emptyRun} - - _, err := executeCommand(rootCmd, "--version") - if err == nil { - t.Errorf("Expected error") - } - checkStringContains(t, err.Error(), "unknown flag: --version") -} - -func TestUsageIsNotPrintedTwice(t *testing.T) { - var cmd = &Command{Use: "root"} - var sub = &Command{Use: "sub"} - cmd.AddCommand(sub) - - output, _ := executeCommand(cmd, "") - if strings.Count(output, "Usage:") != 1 { - t.Error("Usage output is not printed exactly once") - } -} - -func TestVisitParents(t *testing.T) { - c := &Command{Use: "app"} - sub := &Command{Use: "sub"} - dsub := &Command{Use: "dsub"} - sub.AddCommand(dsub) - c.AddCommand(sub) - - total := 0 - add := func(x *Command) { - total++ - } - sub.VisitParents(add) - if total != 1 { - t.Errorf("Should have visited 1 parent but visited %d", total) - } - - total = 0 - dsub.VisitParents(add) - if total != 2 { - t.Errorf("Should have visited 2 parents but visited %d", total) - } - - total = 0 - c.VisitParents(add) - if total != 0 { - t.Errorf("Should have visited no parents but visited %d", total) - } -} - -func TestSuggestions(t *testing.T) { - rootCmd := &Command{Use: "root", Run: emptyRun} - timesCmd := &Command{ - Use: "times", - SuggestFor: []string{"counts"}, - Run: emptyRun, - } - rootCmd.AddCommand(timesCmd) - - templateWithSuggestions := "Error: unknown command \"%s\" for \"root\"\n\nDid you mean this?\n\t%s\n\nRun 'root --help' for usage.\n" - templateWithoutSuggestions := "Error: unknown command \"%s\" for \"root\"\nRun 'root --help' for usage.\n" - - tests := map[string]string{ - "time": "times", - "tiems": "times", - "tims": "times", - "timeS": "times", - "rimes": "times", - "ti": "times", - "t": "times", - "timely": "times", - "ri": "", - "timezone": "", - "foo": "", - "counts": "times", - } - - for typo, suggestion := range tests { - for _, suggestionsDisabled := range []bool{true, false} { - rootCmd.DisableSuggestions = suggestionsDisabled - - var expected string - output, _ := executeCommand(rootCmd, typo) - - if suggestion == "" || suggestionsDisabled { - expected = fmt.Sprintf(templateWithoutSuggestions, typo) - } else { - expected = fmt.Sprintf(templateWithSuggestions, typo, suggestion) - } - - if output != expected { - t.Errorf("Unexpected response.\nExpected:\n %q\nGot:\n %q\n", expected, output) - } - } - } -} - -func TestRemoveCommand(t *testing.T) { - rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} - childCmd := &Command{Use: "child", Run: emptyRun} - rootCmd.AddCommand(childCmd) - rootCmd.RemoveCommand(childCmd) - - _, err := executeCommand(rootCmd, "child") - if err == nil { - t.Error("Expected error on calling removed command. Got nil.") - } -} - -func TestReplaceCommandWithRemove(t *testing.T) { - childUsed := 0 - rootCmd := &Command{Use: "root", Run: emptyRun} - child1Cmd := &Command{ - Use: "child", - Run: func(*Command, []string) { childUsed = 1 }, - } - child2Cmd := &Command{ - Use: "child", - Run: func(*Command, []string) { childUsed = 2 }, - } - rootCmd.AddCommand(child1Cmd) - rootCmd.RemoveCommand(child1Cmd) - rootCmd.AddCommand(child2Cmd) - - output, err := executeCommand(rootCmd, "child") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if childUsed == 1 { - t.Error("Removed command shouldn't be called") - } - if childUsed != 2 { - t.Error("Replacing command should have been called but didn't") - } -} - -func TestDeprecatedCommand(t *testing.T) { - rootCmd := &Command{Use: "root", Run: emptyRun} - deprecatedCmd := &Command{ - Use: "deprecated", - Deprecated: "This command is deprecated", - Run: emptyRun, - } - rootCmd.AddCommand(deprecatedCmd) - - output, err := executeCommand(rootCmd, "deprecated") - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - checkStringContains(t, output, deprecatedCmd.Deprecated) -} - -func TestHooks(t *testing.T) { - var ( - persPreArgs string - preArgs string - runArgs string - postArgs string - persPostArgs string - ) - - c := &Command{ - Use: "c", - PersistentPreRun: func(_ *Command, args []string) { - persPreArgs = strings.Join(args, " ") - }, - PreRun: func(_ *Command, args []string) { - preArgs = strings.Join(args, " ") - }, - Run: func(_ *Command, args []string) { - runArgs = strings.Join(args, " ") - }, - PostRun: func(_ *Command, args []string) { - postArgs = strings.Join(args, " ") - }, - PersistentPostRun: func(_ *Command, args []string) { - persPostArgs = strings.Join(args, " ") - }, - } - - output, err := executeCommand(c, "one", "two") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if persPreArgs != "one two" { - t.Errorf("Expected persPreArgs %q, got %q", "one two", persPreArgs) - } - if preArgs != "one two" { - t.Errorf("Expected preArgs %q, got %q", "one two", preArgs) - } - if runArgs != "one two" { - t.Errorf("Expected runArgs %q, got %q", "one two", runArgs) - } - if postArgs != "one two" { - t.Errorf("Expected postArgs %q, got %q", "one two", postArgs) - } - if persPostArgs != "one two" { - t.Errorf("Expected persPostArgs %q, got %q", "one two", persPostArgs) - } -} - -func TestPersistentHooks(t *testing.T) { - var ( - parentPersPreArgs string - parentPreArgs string - parentRunArgs string - parentPostArgs string - parentPersPostArgs string - ) - - var ( - childPersPreArgs string - childPreArgs string - childRunArgs string - childPostArgs string - childPersPostArgs string - ) - - parentCmd := &Command{ - Use: "parent", - PersistentPreRun: func(_ *Command, args []string) { - parentPersPreArgs = strings.Join(args, " ") - }, - PreRun: func(_ *Command, args []string) { - parentPreArgs = strings.Join(args, " ") - }, - Run: func(_ *Command, args []string) { - parentRunArgs = strings.Join(args, " ") - }, - PostRun: func(_ *Command, args []string) { - parentPostArgs = strings.Join(args, " ") - }, - PersistentPostRun: func(_ *Command, args []string) { - parentPersPostArgs = strings.Join(args, " ") - }, - } - - childCmd := &Command{ - Use: "child", - PersistentPreRun: func(_ *Command, args []string) { - childPersPreArgs = strings.Join(args, " ") - }, - PreRun: func(_ *Command, args []string) { - childPreArgs = strings.Join(args, " ") - }, - Run: func(_ *Command, args []string) { - childRunArgs = strings.Join(args, " ") - }, - PostRun: func(_ *Command, args []string) { - childPostArgs = strings.Join(args, " ") - }, - PersistentPostRun: func(_ *Command, args []string) { - childPersPostArgs = strings.Join(args, " ") - }, - } - parentCmd.AddCommand(childCmd) - - output, err := executeCommand(parentCmd, "child", "one", "two") - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - // TODO: This test fails, but should not. - // Related to https://github.com/spf13/cobra/issues/252. - // - // if parentPersPreArgs != "one two" { - // t.Errorf("Expected parentPersPreArgs %q, got %q", "one two", parentPersPreArgs) - // } - if parentPreArgs != "" { - t.Errorf("Expected blank parentPreArgs, got %q", parentPreArgs) - } - if parentRunArgs != "" { - t.Errorf("Expected blank parentRunArgs, got %q", parentRunArgs) - } - if parentPostArgs != "" { - t.Errorf("Expected blank parentPostArgs, got %q", parentPostArgs) - } - // TODO: This test fails, but should not. - // Related to https://github.com/spf13/cobra/issues/252. - // - // if parentPersPostArgs != "one two" { - // t.Errorf("Expected parentPersPostArgs %q, got %q", "one two", parentPersPostArgs) - // } - - if childPersPreArgs != "one two" { - t.Errorf("Expected childPersPreArgs %q, got %q", "one two", childPersPreArgs) - } - if childPreArgs != "one two" { - t.Errorf("Expected childPreArgs %q, got %q", "one two", childPreArgs) - } - if childRunArgs != "one two" { - t.Errorf("Expected childRunArgs %q, got %q", "one two", childRunArgs) - } - if childPostArgs != "one two" { - t.Errorf("Expected childPostArgs %q, got %q", "one two", childPostArgs) - } - if childPersPostArgs != "one two" { - t.Errorf("Expected childPersPostArgs %q, got %q", "one two", childPersPostArgs) - } -} - -// Related to https://github.com/spf13/cobra/issues/521. -func TestGlobalNormFuncPropagation(t *testing.T) { - normFunc := func(f *pflag.FlagSet, name string) pflag.NormalizedName { - return pflag.NormalizedName(name) - } - - rootCmd := &Command{Use: "root", Run: emptyRun} - childCmd := &Command{Use: "child", Run: emptyRun} - rootCmd.AddCommand(childCmd) - - rootCmd.SetGlobalNormalizationFunc(normFunc) - if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() { - t.Error("rootCmd seems to have a wrong normalization function") - } - - if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(childCmd.GlobalNormalizationFunc()).Pointer() { - t.Error("childCmd should have had the normalization function of rootCmd") - } -} - -// Related to https://github.com/spf13/cobra/issues/521. -func TestNormPassedOnLocal(t *testing.T) { - toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName { - return pflag.NormalizedName(strings.ToUpper(name)) - } - - c := &Command{} - c.Flags().Bool("flagname", true, "this is a dummy flag") - c.SetGlobalNormalizationFunc(toUpper) - if c.LocalFlags().Lookup("flagname") != c.LocalFlags().Lookup("FLAGNAME") { - t.Error("Normalization function should be passed on to Local flag set") - } -} - -// Related to https://github.com/spf13/cobra/issues/521. -func TestNormPassedOnInherited(t *testing.T) { - toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName { - return pflag.NormalizedName(strings.ToUpper(name)) - } - - c := &Command{} - c.SetGlobalNormalizationFunc(toUpper) - - child1 := &Command{} - c.AddCommand(child1) - - c.PersistentFlags().Bool("flagname", true, "") - - child2 := &Command{} - c.AddCommand(child2) - - inherited := child1.InheritedFlags() - if inherited.Lookup("flagname") == nil || inherited.Lookup("flagname") != inherited.Lookup("FLAGNAME") { - t.Error("Normalization function should be passed on to inherited flag set in command added before flag") - } - - inherited = child2.InheritedFlags() - if inherited.Lookup("flagname") == nil || inherited.Lookup("flagname") != inherited.Lookup("FLAGNAME") { - t.Error("Normalization function should be passed on to inherited flag set in command added after flag") - } -} - -// Related to https://github.com/spf13/cobra/issues/521. -func TestConsistentNormalizedName(t *testing.T) { - toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName { - return pflag.NormalizedName(strings.ToUpper(name)) - } - n := func(f *pflag.FlagSet, name string) pflag.NormalizedName { - return pflag.NormalizedName(name) - } - - c := &Command{} - c.Flags().Bool("flagname", true, "") - c.SetGlobalNormalizationFunc(toUpper) - c.SetGlobalNormalizationFunc(n) - - if c.LocalFlags().Lookup("flagname") == c.LocalFlags().Lookup("FLAGNAME") { - t.Error("Normalizing flag names should not result in duplicate flags") - } -} - -func TestFlagOnPflagCommandLine(t *testing.T) { - flagName := "flagOnCommandLine" - pflag.String(flagName, "", "about my flag") - - c := &Command{Use: "c", Run: emptyRun} - c.AddCommand(&Command{Use: "child", Run: emptyRun}) - - output, _ := executeCommand(c, "--help") - checkStringContains(t, output, flagName) - - resetCommandLineFlagSet() -} - -// TestHiddenCommandExecutes checks, -// if hidden commands run as intended. -func TestHiddenCommandExecutes(t *testing.T) { - executed := false - c := &Command{ - Use: "c", - Hidden: true, - Run: func(*Command, []string) { executed = true }, - } - - output, err := executeCommand(c) - if output != "" { - t.Errorf("Unexpected output: %v", output) - } - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if !executed { - t.Error("Hidden command should have been executed") - } -} - -// test to ensure hidden commands do not show up in usage/help text -func TestHiddenCommandIsHidden(t *testing.T) { - c := &Command{Use: "c", Hidden: true, Run: emptyRun} - if c.IsAvailableCommand() { - t.Errorf("Hidden command should be unavailable") - } -} - -func TestCommandsAreSorted(t *testing.T) { - EnableCommandSorting = true - - originalNames := []string{"middle", "zlast", "afirst"} - expectedNames := []string{"afirst", "middle", "zlast"} - - var rootCmd = &Command{Use: "root"} - - for _, name := range originalNames { - rootCmd.AddCommand(&Command{Use: name}) - } - - for i, c := range rootCmd.Commands() { - got := c.Name() - if expectedNames[i] != got { - t.Errorf("Expected: %s, got: %s", expectedNames[i], got) - } - } - - EnableCommandSorting = true -} - -func TestEnableCommandSortingIsDisabled(t *testing.T) { - EnableCommandSorting = false - - originalNames := []string{"middle", "zlast", "afirst"} - - var rootCmd = &Command{Use: "root"} - - for _, name := range originalNames { - rootCmd.AddCommand(&Command{Use: name}) - } - - for i, c := range rootCmd.Commands() { - got := c.Name() - if originalNames[i] != got { - t.Errorf("expected: %s, got: %s", originalNames[i], got) - } - } - - EnableCommandSorting = true -} - -func TestSetOutput(t *testing.T) { - c := &Command{} - c.SetOutput(nil) - if out := c.OutOrStdout(); out != os.Stdout { - t.Errorf("Expected setting output to nil to revert back to stdout") - } -} - -func TestFlagErrorFunc(t *testing.T) { - c := &Command{Use: "c", Run: emptyRun} - - expectedFmt := "This is expected: %v" - c.SetFlagErrorFunc(func(_ *Command, err error) error { - return fmt.Errorf(expectedFmt, err) - }) - - _, err := executeCommand(c, "--unknown-flag") - - got := err.Error() - expected := fmt.Sprintf(expectedFmt, "unknown flag: --unknown-flag") - if got != expected { - t.Errorf("Expected %v, got %v", expected, got) - } -} - -// TestSortedFlags checks, -// if cmd.LocalFlags() is unsorted when cmd.Flags().SortFlags set to false. -// Related to https://github.com/spf13/cobra/issues/404. -func TestSortedFlags(t *testing.T) { - c := &Command{} - c.Flags().SortFlags = false - names := []string{"C", "B", "A", "D"} - for _, name := range names { - c.Flags().Bool(name, false, "") - } - - i := 0 - c.LocalFlags().VisitAll(func(f *pflag.Flag) { - if i == len(names) { - return - } - if stringInSlice(f.Name, names) { - if names[i] != f.Name { - t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name) - } - i++ - } - }) -} - -// 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: emptyRun} - c.mergePersistentFlags() - if c.Flags().Lookup("boolflag") == nil { - t.Fatal("Expecting to have flag from CommandLine in c.Flags()") - } - - resetCommandLineFlagSet() -} - -// TestUseDeprecatedFlags checks, -// if cobra.Execute() prints a message, if a deprecated flag is used. -// Related to https://github.com/spf13/cobra/issues/463. -func TestUseDeprecatedFlags(t *testing.T) { - c := &Command{Use: "c", Run: emptyRun} - c.Flags().BoolP("deprecated", "d", false, "deprecated flag") - c.Flags().MarkDeprecated("deprecated", "This flag is deprecated") - - output, err := executeCommand(c, "c", "-d") - if err != nil { - t.Error("Unexpected error:", err) - } - checkStringContains(t, output, "This flag is deprecated") -} - -func TestTraverseWithParentFlags(t *testing.T) { - rootCmd := &Command{Use: "root", TraverseChildren: true} - rootCmd.Flags().String("str", "", "") - rootCmd.Flags().BoolP("bool", "b", false, "") - - childCmd := &Command{Use: "child"} - childCmd.Flags().Int("int", -1, "") - - rootCmd.AddCommand(childCmd) - - c, args, err := rootCmd.Traverse([]string{"-b", "--str", "ok", "child", "--int"}) - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - if len(args) != 1 && args[0] != "--add" { - t.Errorf("Wrong args: %v", args) - } - if c.Name() != childCmd.Name() { - t.Errorf("Expected command: %q, got: %q", childCmd.Name(), c.Name()) - } -} - -func TestTraverseNoParentFlags(t *testing.T) { - rootCmd := &Command{Use: "root", TraverseChildren: true} - rootCmd.Flags().String("foo", "", "foo things") - - childCmd := &Command{Use: "child"} - childCmd.Flags().String("str", "", "") - rootCmd.AddCommand(childCmd) - - c, args, err := rootCmd.Traverse([]string{"child"}) - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - if len(args) != 0 { - t.Errorf("Wrong args %v", args) - } - if c.Name() != childCmd.Name() { - t.Errorf("Expected command: %q, got: %q", childCmd.Name(), c.Name()) - } -} - -func TestTraverseWithBadParentFlags(t *testing.T) { - rootCmd := &Command{Use: "root", TraverseChildren: true} - - childCmd := &Command{Use: "child"} - childCmd.Flags().String("str", "", "") - rootCmd.AddCommand(childCmd) - - expected := "unknown flag: --str" - - c, _, err := rootCmd.Traverse([]string{"--str", "ok", "child"}) - if err == nil || !strings.Contains(err.Error(), expected) { - t.Errorf("Expected error, %q, got %q", expected, err) - } - if c != nil { - t.Errorf("Expected nil command") - } -} - -func TestTraverseWithBadChildFlag(t *testing.T) { - rootCmd := &Command{Use: "root", TraverseChildren: true} - rootCmd.Flags().String("str", "", "") - - childCmd := &Command{Use: "child"} - rootCmd.AddCommand(childCmd) - - // Expect no error because the last commands args shouldn't be parsed in - // Traverse. - c, args, err := rootCmd.Traverse([]string{"child", "--str"}) - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - if len(args) != 1 && args[0] != "--str" { - t.Errorf("Wrong args: %v", args) - } - if c.Name() != childCmd.Name() { - t.Errorf("Expected command %q, got: %q", childCmd.Name(), c.Name()) - } -} - -func TestTraverseWithTwoSubcommands(t *testing.T) { - rootCmd := &Command{Use: "root", TraverseChildren: true} - - subCmd := &Command{Use: "sub", TraverseChildren: true} - rootCmd.AddCommand(subCmd) - - subsubCmd := &Command{ - Use: "subsub", - } - subCmd.AddCommand(subsubCmd) - - c, _, err := rootCmd.Traverse([]string{"sub", "subsub"}) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if c.Name() != subsubCmd.Name() { - t.Fatalf("Expected command: %q, got %q", subsubCmd.Name(), c.Name()) - } -} - -// TestUpdateName checks if c.Name() updates on changed c.Use. -// Related to https://github.com/spf13/cobra/pull/422#discussion_r143918343. -func TestUpdateName(t *testing.T) { - c := &Command{Use: "name xyz"} - originalName := c.Name() - - c.Use = "changedName abc" - if originalName == c.Name() || c.Name() != "changedName" { - t.Error("c.Name() should be updated on changed c.Use") - } -} - -type calledAsTestcase struct { - args []string - call string - want string - epm bool - tc bool -} - -func (tc *calledAsTestcase) test(t *testing.T) { - defer func(ov bool) { EnablePrefixMatching = ov }(EnablePrefixMatching) - EnablePrefixMatching = tc.epm - - var called *Command - run := func(c *Command, _ []string) { t.Logf("called: %q", c.Name()); called = c } - - parent := &Command{Use: "parent", Run: run} - child1 := &Command{Use: "child1", Run: run, Aliases: []string{"this"}} - child2 := &Command{Use: "child2", Run: run, Aliases: []string{"that"}} - - parent.AddCommand(child1) - parent.AddCommand(child2) - parent.SetArgs(tc.args) - - output := new(bytes.Buffer) - parent.SetOutput(output) - - parent.Execute() - - if called == nil { - if tc.call != "" { - t.Errorf("missing expected call to command: %s", tc.call) - } - return - } - - if called.Name() != tc.call { - t.Errorf("called command == %q; Wanted %q", called.Name(), tc.call) - } else if got := called.CalledAs(); got != tc.want { - t.Errorf("%s.CalledAs() == %q; Wanted: %q", tc.call, got, tc.want) - } -} - -func TestCalledAs(t *testing.T) { - tests := map[string]calledAsTestcase{ - "find/no-args": {nil, "parent", "parent", false, false}, - "find/real-name": {[]string{"child1"}, "child1", "child1", false, false}, - "find/full-alias": {[]string{"that"}, "child2", "that", false, false}, - "find/part-no-prefix": {[]string{"thi"}, "", "", false, false}, - "find/part-alias": {[]string{"thi"}, "child1", "this", true, false}, - "find/conflict": {[]string{"th"}, "", "", true, false}, - "traverse/no-args": {nil, "parent", "parent", false, true}, - "traverse/real-name": {[]string{"child1"}, "child1", "child1", false, true}, - "traverse/full-alias": {[]string{"that"}, "child2", "that", false, true}, - "traverse/part-no-prefix": {[]string{"thi"}, "", "", false, true}, - "traverse/part-alias": {[]string{"thi"}, "child1", "this", true, true}, - "traverse/conflict": {[]string{"th"}, "", "", true, true}, - } - - for name, tc := range tests { - t.Run(name, tc.test) - } -} diff --git a/vendor/github.com/spf13/cobra/command_win.go b/vendor/github.com/spf13/cobra/command_win.go deleted file mode 100644 index edec728e..00000000 --- a/vendor/github.com/spf13/cobra/command_win.go +++ /dev/null @@ -1,20 +0,0 @@ -// +build windows - -package cobra - -import ( - "os" - "time" - - "github.com/inconshreveable/mousetrap" -) - -var preExecHookFn = preExecHook - -func preExecHook(c *Command) { - if MousetrapHelpText != "" && mousetrap.StartedByExplorer() { - c.Print(MousetrapHelpText) - time.Sleep(5 * time.Second) - os.Exit(1) - } -} diff --git a/vendor/github.com/spf13/cobra/doc/cmd_test.go b/vendor/github.com/spf13/cobra/doc/cmd_test.go deleted file mode 100644 index d29c577d..00000000 --- a/vendor/github.com/spf13/cobra/doc/cmd_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package doc - -import ( - "strings" - "testing" - - "github.com/spf13/cobra" -) - -func emptyRun(*cobra.Command, []string) {} - -func init() { - rootCmd.PersistentFlags().StringP("rootflag", "r", "two", "") - rootCmd.PersistentFlags().StringP("strtwo", "t", "two", "help message for parent flag strtwo") - - echoCmd.PersistentFlags().StringP("strone", "s", "one", "help message for flag strone") - echoCmd.PersistentFlags().BoolP("persistentbool", "p", false, "help message for flag persistentbool") - echoCmd.Flags().IntP("intone", "i", 123, "help message for flag intone") - echoCmd.Flags().BoolP("boolone", "b", true, "help message for flag boolone") - - timesCmd.PersistentFlags().StringP("strtwo", "t", "2", "help message for child flag strtwo") - timesCmd.Flags().IntP("inttwo", "j", 234, "help message for flag inttwo") - timesCmd.Flags().BoolP("booltwo", "c", false, "help message for flag booltwo") - - printCmd.PersistentFlags().StringP("strthree", "s", "three", "help message for flag strthree") - printCmd.Flags().IntP("intthree", "i", 345, "help message for flag intthree") - printCmd.Flags().BoolP("boolthree", "b", true, "help message for flag boolthree") - - echoCmd.AddCommand(timesCmd, echoSubCmd, deprecatedCmd) - rootCmd.AddCommand(printCmd, echoCmd) -} - -var rootCmd = &cobra.Command{ - Use: "root", - Short: "Root short description", - Long: "Root long description", - Run: emptyRun, -} - -var echoCmd = &cobra.Command{ - Use: "echo [string to echo]", - Aliases: []string{"say"}, - Short: "Echo anything to the screen", - Long: "an utterly useless command for testing", - Example: "Just run cobra-test echo", -} - -var echoSubCmd = &cobra.Command{ - Use: "echosub [string to print]", - Short: "second sub command for echo", - Long: "an absolutely utterly useless command for testing gendocs!.", - Run: emptyRun, -} - -var timesCmd = &cobra.Command{ - Use: "times [# times] [string to echo]", - SuggestFor: []string{"counts"}, - Short: "Echo anything to the screen more times", - Long: `a slightly useless command for testing.`, - Run: emptyRun, -} - -var deprecatedCmd = &cobra.Command{ - Use: "deprecated [can't do anything here]", - Short: "A command which is deprecated", - Long: `an absolutely utterly useless command for testing deprecation!.`, - Deprecated: "Please use echo instead", -} - -var printCmd = &cobra.Command{ - Use: "print [string to print]", - Short: "Print anything to the screen", - Long: `an absolutely utterly useless command for testing.`, -} - -func checkStringContains(t *testing.T, got, expected string) { - if !strings.Contains(got, expected) { - t.Errorf("Expected to contain: \n %v\nGot:\n %v\n", expected, got) - } -} - -func checkStringOmits(t *testing.T, got, expected string) { - if strings.Contains(got, expected) { - t.Errorf("Expected to not contain: \n %v\nGot: %v", expected, got) - } -} diff --git a/vendor/github.com/spf13/cobra/doc/man_docs.go b/vendor/github.com/spf13/cobra/doc/man_docs.go deleted file mode 100644 index ce92332d..00000000 --- a/vendor/github.com/spf13/cobra/doc/man_docs.go +++ /dev/null @@ -1,236 +0,0 @@ -// Copyright 2015 Red Hat Inc. All rights reserved. -// -// 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 doc - -import ( - "bytes" - "fmt" - "io" - "os" - "path/filepath" - "sort" - "strings" - "time" - - "github.com/cpuguy83/go-md2man/md2man" - "github.com/spf13/cobra" - "github.com/spf13/pflag" -) - -// GenManTree will generate a man page for this command and all descendants -// in the directory given. The header may be nil. This function may not work -// correctly if your command names have `-` in them. If you have `cmd` with two -// subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third` -// it is undefined which help output will be in the file `cmd-sub-third.1`. -func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error { - return GenManTreeFromOpts(cmd, GenManTreeOptions{ - Header: header, - Path: dir, - CommandSeparator: "-", - }) -} - -// GenManTreeFromOpts generates a man page for the command and all descendants. -// The pages are written to the opts.Path directory. -func GenManTreeFromOpts(cmd *cobra.Command, opts GenManTreeOptions) error { - header := opts.Header - if header == nil { - header = &GenManHeader{} - } - for _, c := range cmd.Commands() { - if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() { - continue - } - if err := GenManTreeFromOpts(c, opts); err != nil { - return err - } - } - section := "1" - if header.Section != "" { - section = header.Section - } - - separator := "_" - if opts.CommandSeparator != "" { - separator = opts.CommandSeparator - } - basename := strings.Replace(cmd.CommandPath(), " ", separator, -1) - filename := filepath.Join(opts.Path, basename+"."+section) - f, err := os.Create(filename) - if err != nil { - return err - } - defer f.Close() - - headerCopy := *header - 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 - CommandSeparator string -} - -// GenManHeader is a lot like the .TH header at the start of man pages. These -// include the title, section, date, source, and manual. We will use the -// current time if Date if unset and will use "Auto generated by spf13/cobra" -// if the Source is unset. -type GenManHeader struct { - Title string - Section string - Date *time.Time - date string - Source string - Manual string -} - -// GenMan will generate a man page for the given command and write it to -// w. The header argument may be nil, however obviously w may not. -func GenMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error { - if header == nil { - header = &GenManHeader{} - } - fillHeader(header, cmd.CommandPath()) - - b := genMan(cmd, header) - _, err := w.Write(md2man.Render(b)) - return err -} - -func fillHeader(header *GenManHeader, name string) { - if header.Title == "" { - header.Title = strings.ToUpper(strings.Replace(name, " ", "\\-", -1)) - } - if header.Section == "" { - header.Section = "1" - } - if header.Date == nil { - now := time.Now() - header.Date = &now - } - header.date = (*header.Date).Format("Jan 2006") - if header.Source == "" { - header.Source = "Auto generated by spf13/cobra" - } -} - -func manPreamble(buf *bytes.Buffer, header *GenManHeader, cmd *cobra.Command, dashedName string) { - description := cmd.Long - if len(description) == 0 { - description = cmd.Short - } - - buf.WriteString(fmt.Sprintf(`%% %s(%s)%s -%% %s -%% %s -# NAME -`, header.Title, header.Section, header.date, header.Source, header.Manual)) - buf.WriteString(fmt.Sprintf("%s \\- %s\n\n", dashedName, cmd.Short)) - buf.WriteString("# SYNOPSIS\n") - buf.WriteString(fmt.Sprintf("**%s**\n\n", cmd.UseLine())) - buf.WriteString("# DESCRIPTION\n") - buf.WriteString(description + "\n\n") -} - -func manPrintFlags(buf *bytes.Buffer, flags *pflag.FlagSet) { - flags.VisitAll(func(flag *pflag.Flag) { - if len(flag.Deprecated) > 0 || flag.Hidden { - return - } - format := "" - if len(flag.Shorthand) > 0 && len(flag.ShorthandDeprecated) == 0 { - format = fmt.Sprintf("**-%s**, **--%s**", flag.Shorthand, flag.Name) - } else { - format = fmt.Sprintf("**--%s**", flag.Name) - } - if len(flag.NoOptDefVal) > 0 { - format += "[" - } - if flag.Value.Type() == "string" { - // put quotes on the value - format += "=%q" - } else { - format += "=%s" - } - if len(flag.NoOptDefVal) > 0 { - format += "]" - } - format += "\n\t%s\n\n" - buf.WriteString(fmt.Sprintf(format, flag.DefValue, flag.Usage)) - }) -} - -func manPrintOptions(buf *bytes.Buffer, command *cobra.Command) { - flags := command.NonInheritedFlags() - if flags.HasFlags() { - buf.WriteString("# OPTIONS\n") - manPrintFlags(buf, flags) - buf.WriteString("\n") - } - flags = command.InheritedFlags() - if flags.HasFlags() { - buf.WriteString("# OPTIONS INHERITED FROM PARENT COMMANDS\n") - manPrintFlags(buf, flags) - buf.WriteString("\n") - } -} - -func genMan(cmd *cobra.Command, header *GenManHeader) []byte { - cmd.InitDefaultHelpCmd() - cmd.InitDefaultHelpFlag() - - // something like `rootcmd-subcmd1-subcmd2` - dashCommandName := strings.Replace(cmd.CommandPath(), " ", "-", -1) - - buf := new(bytes.Buffer) - - manPreamble(buf, header, cmd, dashCommandName) - manPrintOptions(buf, cmd) - if len(cmd.Example) > 0 { - buf.WriteString("# EXAMPLE\n") - buf.WriteString(fmt.Sprintf("```\n%s\n```\n", cmd.Example)) - } - if hasSeeAlso(cmd) { - buf.WriteString("# SEE ALSO\n") - seealsos := make([]string, 0) - if cmd.HasParent() { - parentPath := cmd.Parent().CommandPath() - dashParentPath := strings.Replace(parentPath, " ", "-", -1) - seealso := fmt.Sprintf("**%s(%s)**", dashParentPath, header.Section) - seealsos = append(seealsos, seealso) - cmd.VisitParents(func(c *cobra.Command) { - if c.DisableAutoGenTag { - cmd.DisableAutoGenTag = c.DisableAutoGenTag - } - }) - } - children := cmd.Commands() - sort.Sort(byName(children)) - for _, c := range children { - if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() { - continue - } - seealso := fmt.Sprintf("**%s-%s(%s)**", dashCommandName, c.Name(), header.Section) - seealsos = append(seealsos, seealso) - } - buf.WriteString(strings.Join(seealsos, ", ") + "\n") - } - if !cmd.DisableAutoGenTag { - buf.WriteString(fmt.Sprintf("# HISTORY\n%s Auto generated by spf13/cobra\n", header.Date.Format("2-Jan-2006"))) - } - return buf.Bytes() -} diff --git a/vendor/github.com/spf13/cobra/doc/man_docs.md b/vendor/github.com/spf13/cobra/doc/man_docs.md deleted file mode 100644 index 3709160f..00000000 --- a/vendor/github.com/spf13/cobra/doc/man_docs.md +++ /dev/null @@ -1,31 +0,0 @@ -# Generating Man Pages For Your Own cobra.Command - -Generating man pages from a cobra command is incredibly easy. An example is as follows: - -```go -package main - -import ( - "log" - - "github.com/spf13/cobra" - "github.com/spf13/cobra/doc" -) - -func main() { - cmd := &cobra.Command{ - Use: "test", - Short: "my test program", - } - header := &doc.GenManHeader{ - Title: "MINE", - Section: "3", - } - err := doc.GenManTree(cmd, header, "/tmp") - if err != nil { - log.Fatal(err) - } -} -``` - -That will get you a man page `/tmp/test.3` diff --git a/vendor/github.com/spf13/cobra/doc/man_docs_test.go b/vendor/github.com/spf13/cobra/doc/man_docs_test.go deleted file mode 100644 index 62f85e47..00000000 --- a/vendor/github.com/spf13/cobra/doc/man_docs_test.go +++ /dev/null @@ -1,177 +0,0 @@ -package doc - -import ( - "bufio" - "bytes" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/spf13/cobra" -) - -func translate(in string) string { - return strings.Replace(in, "-", "\\-", -1) -} - -func TestGenManDoc(t *testing.T) { - header := &GenManHeader{ - Title: "Project", - Section: "2", - } - - // We generate on a subcommand so we have both subcommands and parents - buf := new(bytes.Buffer) - if err := GenMan(echoCmd, header, buf); err != nil { - t.Fatal(err) - } - output := buf.String() - - // Make sure parent has - in CommandPath() in SEE ALSO: - parentPath := echoCmd.Parent().CommandPath() - dashParentPath := strings.Replace(parentPath, " ", "-", -1) - expected := translate(dashParentPath) - expected = expected + "(" + header.Section + ")" - checkStringContains(t, output, expected) - - checkStringContains(t, output, translate(echoCmd.Name())) - checkStringContains(t, output, translate(echoCmd.Name())) - checkStringContains(t, output, "boolone") - checkStringContains(t, output, "rootflag") - checkStringContains(t, output, translate(rootCmd.Name())) - checkStringContains(t, output, translate(echoSubCmd.Name())) - checkStringOmits(t, output, translate(deprecatedCmd.Name())) - checkStringContains(t, output, translate("Auto generated")) -} - -func TestGenManNoGenTag(t *testing.T) { - echoCmd.DisableAutoGenTag = true - defer func() { echoCmd.DisableAutoGenTag = false }() - - header := &GenManHeader{ - Title: "Project", - Section: "2", - } - - // We generate on a subcommand so we have both subcommands and parents - buf := new(bytes.Buffer) - if err := GenMan(echoCmd, header, buf); err != nil { - t.Fatal(err) - } - output := buf.String() - - unexpected := translate("#HISTORY") - checkStringOmits(t, output, unexpected) -} - -func TestGenManSeeAlso(t *testing.T) { - rootCmd := &cobra.Command{Use: "root", Run: emptyRun} - aCmd := &cobra.Command{Use: "aaa", Run: emptyRun, Hidden: true} // #229 - bCmd := &cobra.Command{Use: "bbb", Run: emptyRun} - cCmd := &cobra.Command{Use: "ccc", Run: emptyRun} - rootCmd.AddCommand(aCmd, bCmd, cCmd) - - buf := new(bytes.Buffer) - header := &GenManHeader{} - if err := GenMan(rootCmd, header, buf); err != nil { - t.Fatal(err) - } - scanner := bufio.NewScanner(buf) - - if err := assertLineFound(scanner, ".SH SEE ALSO"); err != nil { - t.Fatalf("Couldn't find SEE ALSO section header: %v", err) - } - if err := assertNextLineEquals(scanner, ".PP"); err != nil { - t.Fatalf("First line after SEE ALSO wasn't break-indent: %v", err) - } - if err := assertNextLineEquals(scanner, `\fBroot\-bbb(1)\fP, \fBroot\-ccc(1)\fP`); err != nil { - t.Fatalf("Second line after SEE ALSO wasn't correct: %v", err) - } -} - -func TestManPrintFlagsHidesShortDeperecated(t *testing.T) { - c := &cobra.Command{} - c.Flags().StringP("foo", "f", "default", "Foo flag") - c.Flags().MarkShorthandDeprecated("foo", "don't use it no more") - - buf := new(bytes.Buffer) - manPrintFlags(buf, c.Flags()) - - got := buf.String() - expected := "**--foo**=\"default\"\n\tFoo flag\n\n" - if got != expected { - t.Errorf("Expected %v, got %v", expected, got) - } -} - -func TestGenManTree(t *testing.T) { - c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"} - header := &GenManHeader{Section: "2"} - tmpdir, err := ioutil.TempDir("", "test-gen-man-tree") - if err != nil { - t.Fatalf("Failed to create tmpdir: %s", err.Error()) - } - defer os.RemoveAll(tmpdir) - - if err := GenManTree(c, header, tmpdir); err != nil { - t.Fatalf("GenManTree failed: %s", err.Error()) - } - - if _, err := os.Stat(filepath.Join(tmpdir, "do.2")); err != nil { - t.Fatalf("Expected file 'do.2' to exist") - } - - if header.Title != "" { - t.Fatalf("Expected header.Title to be unmodified") - } -} - -func assertLineFound(scanner *bufio.Scanner, expectedLine string) error { - for scanner.Scan() { - line := scanner.Text() - if line == expectedLine { - return nil - } - } - - if err := scanner.Err(); err != nil { - return fmt.Errorf("scan failed: %s", err) - } - - return fmt.Errorf("hit EOF before finding %v", expectedLine) -} - -func assertNextLineEquals(scanner *bufio.Scanner, expectedLine string) error { - if scanner.Scan() { - line := scanner.Text() - if line == expectedLine { - return nil - } - return fmt.Errorf("got %v, not %v", line, expectedLine) - } - - if err := scanner.Err(); err != nil { - return fmt.Errorf("scan failed: %v", err) - } - - return fmt.Errorf("hit EOF before finding %v", expectedLine) -} - -func BenchmarkGenManToFile(b *testing.B) { - file, err := ioutil.TempFile("", "") - if err != nil { - b.Fatal(err) - } - defer os.Remove(file.Name()) - defer file.Close() - - b.ResetTimer() - for i := 0; i < b.N; i++ { - if err := GenMan(rootCmd, nil, file); err != nil { - b.Fatal(err) - } - } -} diff --git a/vendor/github.com/spf13/cobra/doc/man_examples_test.go b/vendor/github.com/spf13/cobra/doc/man_examples_test.go deleted file mode 100644 index db660426..00000000 --- a/vendor/github.com/spf13/cobra/doc/man_examples_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package doc_test - -import ( - "bytes" - "fmt" - - "github.com/spf13/cobra" - "github.com/spf13/cobra/doc" -) - -func ExampleGenManTree() { - cmd := &cobra.Command{ - Use: "test", - Short: "my test program", - } - header := &doc.GenManHeader{ - Title: "MINE", - Section: "3", - } - doc.GenManTree(cmd, header, "/tmp") -} - -func ExampleGenMan() { - cmd := &cobra.Command{ - Use: "test", - Short: "my test program", - } - header := &doc.GenManHeader{ - Title: "MINE", - Section: "3", - } - out := new(bytes.Buffer) - doc.GenMan(cmd, header, out) - fmt.Print(out.String()) -} diff --git a/vendor/github.com/spf13/cobra/doc/md_docs.go b/vendor/github.com/spf13/cobra/doc/md_docs.go deleted file mode 100644 index d7a2c2b6..00000000 --- a/vendor/github.com/spf13/cobra/doc/md_docs.go +++ /dev/null @@ -1,159 +0,0 @@ -//Copyright 2015 Red Hat Inc. All rights reserved. -// -// 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 doc - -import ( - "bytes" - "fmt" - "io" - "os" - "path/filepath" - "sort" - "strings" - "time" - - "github.com/spf13/cobra" -) - -func printOptions(buf *bytes.Buffer, cmd *cobra.Command, name string) error { - flags := cmd.NonInheritedFlags() - flags.SetOutput(buf) - if flags.HasFlags() { - buf.WriteString("### Options\n\n```\n") - flags.PrintDefaults() - buf.WriteString("```\n\n") - } - - parentFlags := cmd.InheritedFlags() - parentFlags.SetOutput(buf) - if parentFlags.HasFlags() { - buf.WriteString("### Options inherited from parent commands\n\n```\n") - parentFlags.PrintDefaults() - buf.WriteString("```\n\n") - } - return nil -} - -// GenMarkdown creates markdown output. -func GenMarkdown(cmd *cobra.Command, w io.Writer) error { - return GenMarkdownCustom(cmd, w, func(s string) string { return s }) -} - -// GenMarkdownCustom creates custom markdown output. -func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error { - cmd.InitDefaultHelpCmd() - cmd.InitDefaultHelpFlag() - - buf := new(bytes.Buffer) - name := cmd.CommandPath() - - short := cmd.Short - long := cmd.Long - if len(long) == 0 { - long = short - } - - buf.WriteString("## " + name + "\n\n") - buf.WriteString(short + "\n\n") - buf.WriteString("### Synopsis\n\n") - buf.WriteString(long + "\n\n") - - if cmd.Runnable() { - buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.UseLine())) - } - - if len(cmd.Example) > 0 { - buf.WriteString("### Examples\n\n") - buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.Example)) - } - - if err := printOptions(buf, cmd, name); err != nil { - return err - } - if hasSeeAlso(cmd) { - buf.WriteString("### SEE ALSO\n\n") - if cmd.HasParent() { - parent := cmd.Parent() - pname := parent.CommandPath() - link := pname + ".md" - link = strings.Replace(link, " ", "_", -1) - buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short)) - cmd.VisitParents(func(c *cobra.Command) { - if c.DisableAutoGenTag { - cmd.DisableAutoGenTag = c.DisableAutoGenTag - } - }) - } - - children := cmd.Commands() - sort.Sort(byName(children)) - - for _, child := range children { - if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() { - continue - } - cname := name + " " + child.Name() - link := cname + ".md" - link = strings.Replace(link, " ", "_", -1) - buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short)) - } - buf.WriteString("\n") - } - if !cmd.DisableAutoGenTag { - buf.WriteString("###### Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "\n") - } - _, err := buf.WriteTo(w) - return err -} - -// GenMarkdownTree will generate a markdown page for this command and all -// descendants in the directory given. The header may be nil. -// This function may not work correctly if your command names have `-` in them. -// If you have `cmd` with two subcmds, `sub` and `sub-third`, -// and `sub` has a subcommand called `third`, it is undefined which -// help output will be in the file `cmd-sub-third.1`. -func GenMarkdownTree(cmd *cobra.Command, dir string) error { - identity := func(s string) string { return s } - emptyStr := func(s string) string { return "" } - 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() { - continue - } - if err := GenMarkdownTreeCustom(c, dir, filePrepender, linkHandler); err != nil { - return err - } - } - - basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".md" - filename := filepath.Join(dir, basename) - f, err := os.Create(filename) - if err != nil { - return err - } - defer f.Close() - - if _, err := io.WriteString(f, filePrepender(filename)); err != nil { - return err - } - if err := GenMarkdownCustom(cmd, f, linkHandler); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/spf13/cobra/doc/md_docs_test.go b/vendor/github.com/spf13/cobra/doc/md_docs_test.go deleted file mode 100644 index b0fa68c0..00000000 --- a/vendor/github.com/spf13/cobra/doc/md_docs_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package doc - -import ( - "bytes" - "io/ioutil" - "os" - "path/filepath" - "testing" - - "github.com/spf13/cobra" -) - -func TestGenMdDoc(t *testing.T) { - // We generate on subcommand so we have both subcommands and parents. - buf := new(bytes.Buffer) - if err := GenMarkdown(echoCmd, buf); err != nil { - t.Fatal(err) - } - output := buf.String() - - checkStringContains(t, output, echoCmd.Long) - checkStringContains(t, output, echoCmd.Example) - checkStringContains(t, output, "boolone") - checkStringContains(t, output, "rootflag") - checkStringContains(t, output, rootCmd.Short) - checkStringContains(t, output, echoSubCmd.Short) - checkStringOmits(t, output, deprecatedCmd.Short) -} - -func TestGenMdNoTag(t *testing.T) { - rootCmd.DisableAutoGenTag = true - defer func() { rootCmd.DisableAutoGenTag = false }() - - buf := new(bytes.Buffer) - if err := GenMarkdown(rootCmd, buf); err != nil { - t.Fatal(err) - } - output := buf.String() - - checkStringOmits(t, output, "Auto generated") -} - -func TestGenMdTree(t *testing.T) { - c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"} - tmpdir, err := ioutil.TempDir("", "test-gen-md-tree") - if err != nil { - t.Fatalf("Failed to create tmpdir: %v", err) - } - defer os.RemoveAll(tmpdir) - - if err := GenMarkdownTree(c, tmpdir); err != nil { - t.Fatalf("GenMarkdownTree failed: %v", err) - } - - if _, err := os.Stat(filepath.Join(tmpdir, "do.md")); err != nil { - t.Fatalf("Expected file 'do.md' to exist") - } -} - -func BenchmarkGenMarkdownToFile(b *testing.B) { - file, err := ioutil.TempFile("", "") - if err != nil { - b.Fatal(err) - } - defer os.Remove(file.Name()) - defer file.Close() - - b.ResetTimer() - for i := 0; i < b.N; i++ { - if err := GenMarkdown(rootCmd, file); err != nil { - b.Fatal(err) - } - } -} diff --git a/vendor/github.com/spf13/cobra/doc/rest_docs.go b/vendor/github.com/spf13/cobra/doc/rest_docs.go deleted file mode 100644 index 4913e3ee..00000000 --- a/vendor/github.com/spf13/cobra/doc/rest_docs.go +++ /dev/null @@ -1,185 +0,0 @@ -//Copyright 2015 Red Hat Inc. All rights reserved. -// -// 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 doc - -import ( - "bytes" - "fmt" - "io" - "os" - "path/filepath" - "sort" - "strings" - "time" - - "github.com/spf13/cobra" -) - -func printOptionsReST(buf *bytes.Buffer, cmd *cobra.Command, name string) error { - flags := cmd.NonInheritedFlags() - flags.SetOutput(buf) - if flags.HasFlags() { - buf.WriteString("Options\n") - buf.WriteString("~~~~~~~\n\n::\n\n") - flags.PrintDefaults() - buf.WriteString("\n") - } - - parentFlags := cmd.InheritedFlags() - parentFlags.SetOutput(buf) - if parentFlags.HasFlags() { - buf.WriteString("Options inherited from parent commands\n") - buf.WriteString("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n::\n\n") - parentFlags.PrintDefaults() - buf.WriteString("\n") - } - return nil -} - -// linkHandler for default ReST hyperlink markup -func defaultLinkHandler(name, ref string) string { - return fmt.Sprintf("`%s <%s.rst>`_", name, ref) -} - -// GenReST creates reStructured Text output. -func GenReST(cmd *cobra.Command, w io.Writer) error { - return GenReSTCustom(cmd, w, defaultLinkHandler) -} - -// GenReSTCustom creates custom reStructured Text output. -func GenReSTCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string, string) string) error { - cmd.InitDefaultHelpCmd() - cmd.InitDefaultHelpFlag() - - buf := new(bytes.Buffer) - name := cmd.CommandPath() - - short := cmd.Short - long := cmd.Long - if len(long) == 0 { - long = short - } - ref := strings.Replace(name, " ", "_", -1) - - buf.WriteString(".. _" + ref + ":\n\n") - buf.WriteString(name + "\n") - buf.WriteString(strings.Repeat("-", len(name)) + "\n\n") - buf.WriteString(short + "\n\n") - buf.WriteString("Synopsis\n") - buf.WriteString("~~~~~~~~\n\n") - buf.WriteString("\n" + long + "\n\n") - - if cmd.Runnable() { - buf.WriteString(fmt.Sprintf("::\n\n %s\n\n", cmd.UseLine())) - } - - if len(cmd.Example) > 0 { - buf.WriteString("Examples\n") - buf.WriteString("~~~~~~~~\n\n") - buf.WriteString(fmt.Sprintf("::\n\n%s\n\n", indentString(cmd.Example, " "))) - } - - if err := printOptionsReST(buf, cmd, name); err != nil { - return err - } - if hasSeeAlso(cmd) { - buf.WriteString("SEE ALSO\n") - buf.WriteString("~~~~~~~~\n\n") - if cmd.HasParent() { - parent := cmd.Parent() - pname := parent.CommandPath() - ref = strings.Replace(pname, " ", "_", -1) - buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(pname, ref), parent.Short)) - cmd.VisitParents(func(c *cobra.Command) { - if c.DisableAutoGenTag { - cmd.DisableAutoGenTag = c.DisableAutoGenTag - } - }) - } - - children := cmd.Commands() - sort.Sort(byName(children)) - - for _, child := range children { - if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() { - continue - } - cname := name + " " + child.Name() - ref = strings.Replace(cname, " ", "_", -1) - buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(cname, ref), child.Short)) - } - buf.WriteString("\n") - } - if !cmd.DisableAutoGenTag { - buf.WriteString("*Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "*\n") - } - _, err := buf.WriteTo(w) - return err -} - -// GenReSTTree will generate a ReST page for this command and all -// descendants in the directory given. -// This function may not work correctly if your command names have `-` in them. -// If you have `cmd` with two subcmds, `sub` and `sub-third`, -// and `sub` has a subcommand called `third`, it is undefined which -// help output will be in the file `cmd-sub-third.1`. -func GenReSTTree(cmd *cobra.Command, dir string) error { - emptyStr := func(s string) string { return "" } - return GenReSTTreeCustom(cmd, dir, emptyStr, defaultLinkHandler) -} - -// GenReSTTreeCustom is the the same as GenReSTTree, but -// with custom filePrepender and linkHandler. -func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error { - for _, c := range cmd.Commands() { - if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() { - continue - } - if err := GenReSTTreeCustom(c, dir, filePrepender, linkHandler); err != nil { - return err - } - } - - basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".rst" - filename := filepath.Join(dir, basename) - f, err := os.Create(filename) - if err != nil { - return err - } - defer f.Close() - - if _, err := io.WriteString(f, filePrepender(filename)); err != nil { - return err - } - if err := GenReSTCustom(cmd, f, linkHandler); err != nil { - return err - } - return nil -} - -// adapted from: https://github.com/kr/text/blob/main/indent.go -func indentString(s, p string) string { - var res []byte - b := []byte(s) - prefix := []byte(p) - bol := true - for _, c := range b { - if bol && c != '\n' { - res = append(res, prefix...) - } - res = append(res, c) - bol = c == '\n' - } - return string(res) -} diff --git a/vendor/github.com/spf13/cobra/doc/rest_docs.md b/vendor/github.com/spf13/cobra/doc/rest_docs.md deleted file mode 100644 index 6098430e..00000000 --- a/vendor/github.com/spf13/cobra/doc/rest_docs.md +++ /dev/null @@ -1,114 +0,0 @@ -# Generating ReStructured Text Docs For Your Own cobra.Command - -Generating ReST pages from a cobra command is incredibly easy. An example is as follows: - -```go -package main - -import ( - "log" - - "github.com/spf13/cobra" - "github.com/spf13/cobra/doc" -) - -func main() { - cmd := &cobra.Command{ - Use: "test", - Short: "my test program", - } - err := doc.GenReSTTree(cmd, "/tmp") - if err != nil { - log.Fatal(err) - } -} -``` - -That will get you a ReST document `/tmp/test.rst` - -## Generate ReST docs for the entire command tree - -This program can actually generate docs for the kubectl command in the kubernetes project - -```go -package main - -import ( - "log" - "io/ioutil" - "os" - - "k8s.io/kubernetes/pkg/kubectl/cmd" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - - "github.com/spf13/cobra/doc" -) - -func main() { - kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard) - err := doc.GenReSTTree(kubectl, "./") - if err != nil { - log.Fatal(err) - } -} -``` - -This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./") - -## Generate ReST docs for a single command - -You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenReST` instead of `GenReSTTree` - -```go - out := new(bytes.Buffer) - err := doc.GenReST(cmd, out) - if err != nil { - log.Fatal(err) - } -``` - -This will write the ReST doc for ONLY "cmd" into the out, buffer. - -## Customize the output - -Both `GenReST` and `GenReSTTree` have alternate versions with callbacks to get some control of the output: - -```go -func GenReSTTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error { - //... -} -``` - -```go -func GenReSTCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string, string) string) error { - //... -} -``` - -The `filePrepender` will prepend the return value given the full filepath to the rendered ReST file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/): - -```go -const fmTemplate = `--- -date: %s -title: "%s" -slug: %s -url: %s ---- -` -filePrepender := func(filename string) string { - now := time.Now().Format(time.RFC3339) - name := filepath.Base(filename) - base := strings.TrimSuffix(name, path.Ext(name)) - url := "/commands/" + strings.ToLower(base) + "/" - return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url) -} -``` - -The `linkHandler` can be used to customize the rendered links to the commands, given a command name and reference. This is useful while converting rst to html or while generating documentation with tools like Sphinx where `:ref:` is used: - -```go -// Sphinx cross-referencing format -linkHandler := func(name, ref string) string { - return fmt.Sprintf(":ref:`%s <%s>`", name, ref) -} -``` diff --git a/vendor/github.com/spf13/cobra/doc/rest_docs_test.go b/vendor/github.com/spf13/cobra/doc/rest_docs_test.go deleted file mode 100644 index aa3186e8..00000000 --- a/vendor/github.com/spf13/cobra/doc/rest_docs_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package doc - -import ( - "bytes" - "io/ioutil" - "os" - "path/filepath" - "testing" - - "github.com/spf13/cobra" -) - -func TestGenRSTDoc(t *testing.T) { - // We generate on a subcommand so we have both subcommands and parents - buf := new(bytes.Buffer) - if err := GenReST(echoCmd, buf); err != nil { - t.Fatal(err) - } - output := buf.String() - - checkStringContains(t, output, echoCmd.Long) - checkStringContains(t, output, echoCmd.Example) - checkStringContains(t, output, "boolone") - checkStringContains(t, output, "rootflag") - checkStringContains(t, output, rootCmd.Short) - checkStringContains(t, output, echoSubCmd.Short) - checkStringOmits(t, output, deprecatedCmd.Short) -} - -func TestGenRSTNoTag(t *testing.T) { - rootCmd.DisableAutoGenTag = true - defer func() { rootCmd.DisableAutoGenTag = false }() - - buf := new(bytes.Buffer) - if err := GenReST(rootCmd, buf); err != nil { - t.Fatal(err) - } - output := buf.String() - - unexpected := "Auto generated" - checkStringOmits(t, output, unexpected) -} - -func TestGenRSTTree(t *testing.T) { - c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"} - - tmpdir, err := ioutil.TempDir("", "test-gen-rst-tree") - if err != nil { - t.Fatalf("Failed to create tmpdir: %s", err.Error()) - } - defer os.RemoveAll(tmpdir) - - if err := GenReSTTree(c, tmpdir); err != nil { - t.Fatalf("GenReSTTree failed: %s", err.Error()) - } - - if _, err := os.Stat(filepath.Join(tmpdir, "do.rst")); err != nil { - t.Fatalf("Expected file 'do.rst' to exist") - } -} - -func BenchmarkGenReSTToFile(b *testing.B) { - file, err := ioutil.TempFile("", "") - if err != nil { - b.Fatal(err) - } - defer os.Remove(file.Name()) - defer file.Close() - - b.ResetTimer() - for i := 0; i < b.N; i++ { - if err := GenReST(rootCmd, file); err != nil { - b.Fatal(err) - } - } -} diff --git a/vendor/github.com/spf13/cobra/doc/util.go b/vendor/github.com/spf13/cobra/doc/util.go deleted file mode 100644 index 8d3dbece..00000000 --- a/vendor/github.com/spf13/cobra/doc/util.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2015 Red Hat Inc. All rights reserved. -// -// 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 doc - -import ( - "strings" - - "github.com/spf13/cobra" -) - -// Test to see if we have a reason to print See Also information in docs -// Basically this is a test for a parent commend or a subcommand which is -// both not deprecated and not the autogenerated help command. -func hasSeeAlso(cmd *cobra.Command) bool { - if cmd.HasParent() { - return true - } - for _, c := range cmd.Commands() { - if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() { - continue - } - return true - } - return false -} - -// Temporary workaround for yaml lib generating incorrect yaml with long strings -// that do not contain \n. -func forceMultiLine(s string) string { - if len(s) > 60 && !strings.Contains(s, "\n") { - s = s + "\n" - } - return s -} - -type byName []*cobra.Command - -func (s byName) Len() int { return len(s) } -func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() } diff --git a/vendor/github.com/spf13/cobra/doc/yaml_docs.go b/vendor/github.com/spf13/cobra/doc/yaml_docs.go deleted file mode 100644 index ea00af07..00000000 --- a/vendor/github.com/spf13/cobra/doc/yaml_docs.go +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright 2016 French Ben. All rights reserved. -// -// 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 doc - -import ( - "fmt" - "io" - "os" - "path/filepath" - "sort" - "strings" - - "github.com/spf13/cobra" - "github.com/spf13/pflag" - "gopkg.in/yaml.v2" -) - -type cmdOption struct { - Name string - Shorthand string `yaml:",omitempty"` - DefaultValue string `yaml:"default_value,omitempty"` - Usage string `yaml:",omitempty"` -} - -type cmdDoc struct { - Name string - Synopsis string `yaml:",omitempty"` - Description string `yaml:",omitempty"` - Options []cmdOption `yaml:",omitempty"` - InheritedOptions []cmdOption `yaml:"inherited_options,omitempty"` - Example string `yaml:",omitempty"` - SeeAlso []string `yaml:"see_also,omitempty"` -} - -// GenYamlTree creates yaml structured ref files for this command and all descendants -// in the directory given. This function may not work -// correctly if your command names have `-` in them. If you have `cmd` with two -// subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third` -// it is undefined which help output will be in the file `cmd-sub-third.1`. -func GenYamlTree(cmd *cobra.Command, dir string) error { - identity := func(s string) string { return s } - emptyStr := func(s string) string { return "" } - return GenYamlTreeCustom(cmd, dir, emptyStr, identity) -} - -// GenYamlTreeCustom creates yaml structured ref files. -func GenYamlTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error { - for _, c := range cmd.Commands() { - if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() { - continue - } - if err := GenYamlTreeCustom(c, dir, filePrepender, linkHandler); err != nil { - return err - } - } - - basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".yaml" - filename := filepath.Join(dir, basename) - f, err := os.Create(filename) - if err != nil { - return err - } - defer f.Close() - - if _, err := io.WriteString(f, filePrepender(filename)); err != nil { - return err - } - if err := GenYamlCustom(cmd, f, linkHandler); err != nil { - return err - } - return nil -} - -// GenYaml creates yaml output. -func GenYaml(cmd *cobra.Command, w io.Writer) error { - return GenYamlCustom(cmd, w, func(s string) string { return s }) -} - -// GenYamlCustom creates custom yaml output. -func GenYamlCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error { - cmd.InitDefaultHelpCmd() - cmd.InitDefaultHelpFlag() - - yamlDoc := cmdDoc{} - yamlDoc.Name = cmd.CommandPath() - - yamlDoc.Synopsis = forceMultiLine(cmd.Short) - yamlDoc.Description = forceMultiLine(cmd.Long) - - if len(cmd.Example) > 0 { - yamlDoc.Example = cmd.Example - } - - flags := cmd.NonInheritedFlags() - if flags.HasFlags() { - yamlDoc.Options = genFlagResult(flags) - } - flags = cmd.InheritedFlags() - if flags.HasFlags() { - yamlDoc.InheritedOptions = genFlagResult(flags) - } - - if hasSeeAlso(cmd) { - result := []string{} - if cmd.HasParent() { - parent := cmd.Parent() - result = append(result, parent.CommandPath()+" - "+parent.Short) - } - children := cmd.Commands() - sort.Sort(byName(children)) - for _, child := range children { - if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() { - continue - } - result = append(result, child.Name()+" - "+child.Short) - } - yamlDoc.SeeAlso = result - } - - final, err := yaml.Marshal(&yamlDoc) - if err != nil { - fmt.Println(err) - os.Exit(1) - } - - if _, err := w.Write(final); err != nil { - return err - } - return nil -} - -func genFlagResult(flags *pflag.FlagSet) []cmdOption { - var result []cmdOption - - flags.VisitAll(func(flag *pflag.Flag) { - // Todo, when we mark a shorthand is deprecated, but specify an empty message. - // The flag.ShorthandDeprecated is empty as the shorthand is deprecated. - // Using len(flag.ShorthandDeprecated) > 0 can't handle this, others are ok. - if !(len(flag.ShorthandDeprecated) > 0) && len(flag.Shorthand) > 0 { - opt := cmdOption{ - flag.Name, - flag.Shorthand, - flag.DefValue, - forceMultiLine(flag.Usage), - } - result = append(result, opt) - } else { - opt := cmdOption{ - Name: flag.Name, - DefaultValue: forceMultiLine(flag.DefValue), - Usage: forceMultiLine(flag.Usage), - } - result = append(result, opt) - } - }) - - return result -} diff --git a/vendor/github.com/spf13/cobra/doc/yaml_docs.md b/vendor/github.com/spf13/cobra/doc/yaml_docs.md deleted file mode 100644 index 1a9b7c6a..00000000 --- a/vendor/github.com/spf13/cobra/doc/yaml_docs.md +++ /dev/null @@ -1,112 +0,0 @@ -# Generating Yaml Docs For Your Own cobra.Command - -Generating yaml files from a cobra command is incredibly easy. An example is as follows: - -```go -package main - -import ( - "log" - - "github.com/spf13/cobra" - "github.com/spf13/cobra/doc" -) - -func main() { - cmd := &cobra.Command{ - Use: "test", - Short: "my test program", - } - err := doc.GenYamlTree(cmd, "/tmp") - if err != nil { - log.Fatal(err) - } -} -``` - -That will get you a Yaml document `/tmp/test.yaml` - -## Generate yaml docs for the entire command tree - -This program can actually generate docs for the kubectl command in the kubernetes project - -```go -package main - -import ( - "io/ioutil" - "log" - "os" - - "k8s.io/kubernetes/pkg/kubectl/cmd" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - - "github.com/spf13/cobra/doc" -) - -func main() { - kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard) - err := doc.GenYamlTree(kubectl, "./") - if err != nil { - log.Fatal(err) - } -} -``` - -This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./") - -## Generate yaml docs for a single command - -You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenYaml` instead of `GenYamlTree` - -```go - out := new(bytes.Buffer) - doc.GenYaml(cmd, out) -``` - -This will write the yaml doc for ONLY "cmd" into the out, buffer. - -## Customize the output - -Both `GenYaml` and `GenYamlTree` have alternate versions with callbacks to get some control of the output: - -```go -func GenYamlTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error { - //... -} -``` - -```go -func GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error { - //... -} -``` - -The `filePrepender` will prepend the return value given the full filepath to the rendered Yaml file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/): - -```go -const fmTemplate = `--- -date: %s -title: "%s" -slug: %s -url: %s ---- -` - -filePrepender := func(filename string) string { - now := time.Now().Format(time.RFC3339) - name := filepath.Base(filename) - base := strings.TrimSuffix(name, path.Ext(name)) - url := "/commands/" + strings.ToLower(base) + "/" - return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url) -} -``` - -The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename: - -```go -linkHandler := func(name string) string { - base := strings.TrimSuffix(name, path.Ext(name)) - return "/commands/" + strings.ToLower(base) + "/" -} -``` diff --git a/vendor/github.com/spf13/cobra/doc/yaml_docs_test.go b/vendor/github.com/spf13/cobra/doc/yaml_docs_test.go deleted file mode 100644 index c5a63594..00000000 --- a/vendor/github.com/spf13/cobra/doc/yaml_docs_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package doc - -import ( - "bytes" - "io/ioutil" - "os" - "path/filepath" - "testing" - - "github.com/spf13/cobra" -) - -func TestGenYamlDoc(t *testing.T) { - // We generate on s subcommand so we have both subcommands and parents - buf := new(bytes.Buffer) - if err := GenYaml(echoCmd, buf); err != nil { - t.Fatal(err) - } - output := buf.String() - - checkStringContains(t, output, echoCmd.Long) - checkStringContains(t, output, echoCmd.Example) - checkStringContains(t, output, "boolone") - checkStringContains(t, output, "rootflag") - checkStringContains(t, output, rootCmd.Short) - checkStringContains(t, output, echoSubCmd.Short) -} - -func TestGenYamlNoTag(t *testing.T) { - rootCmd.DisableAutoGenTag = true - defer func() { rootCmd.DisableAutoGenTag = false }() - - buf := new(bytes.Buffer) - if err := GenYaml(rootCmd, buf); err != nil { - t.Fatal(err) - } - output := buf.String() - - checkStringOmits(t, output, "Auto generated") -} - -func TestGenYamlTree(t *testing.T) { - c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"} - - tmpdir, err := ioutil.TempDir("", "test-gen-yaml-tree") - if err != nil { - t.Fatalf("Failed to create tmpdir: %s", err.Error()) - } - defer os.RemoveAll(tmpdir) - - if err := GenYamlTree(c, tmpdir); err != nil { - t.Fatalf("GenYamlTree failed: %s", err.Error()) - } - - if _, err := os.Stat(filepath.Join(tmpdir, "do.yaml")); err != nil { - t.Fatalf("Expected file 'do.yaml' to exist") - } -} - -func BenchmarkGenYamlToFile(b *testing.B) { - file, err := ioutil.TempFile("", "") - if err != nil { - b.Fatal(err) - } - defer os.Remove(file.Name()) - defer file.Close() - - b.ResetTimer() - for i := 0; i < b.N; i++ { - if err := GenYaml(rootCmd, file); err != nil { - b.Fatal(err) - } - } -} diff --git a/vendor/github.com/spf13/cobra/md_docs.go b/vendor/github.com/spf13/cobra/md_docs.go new file mode 100644 index 00000000..6092c85a --- /dev/null +++ b/vendor/github.com/spf13/cobra/md_docs.go @@ -0,0 +1,138 @@ +//Copyright 2015 Red Hat Inc. All rights reserved. +// +// 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 cobra + +import ( + "bytes" + "fmt" + "os" + "sort" + "strings" + "time" +) + +func printOptions(out *bytes.Buffer, cmd *Command, name string) { + flags := cmd.NonInheritedFlags() + flags.SetOutput(out) + if flags.HasFlags() { + fmt.Fprintf(out, "### Options\n\n```\n") + flags.PrintDefaults() + fmt.Fprintf(out, "```\n\n") + } + + parentFlags := cmd.InheritedFlags() + parentFlags.SetOutput(out) + if parentFlags.HasFlags() { + fmt.Fprintf(out, "### Options inherited from parent commands\n\n```\n") + parentFlags.PrintDefaults() + fmt.Fprintf(out, "```\n\n") + } +} + +type byName []*Command + +func (s byName) Len() int { return len(s) } +func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() } + +func GenMarkdown(cmd *Command, out *bytes.Buffer) { + GenMarkdownCustom(cmd, out, func(s string) string { return s }) +} + +func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) { + name := cmd.CommandPath() + + short := cmd.Short + long := cmd.Long + if len(long) == 0 { + long = short + } + + fmt.Fprintf(out, "## %s\n\n", name) + fmt.Fprintf(out, "%s\n\n", short) + fmt.Fprintf(out, "### Synopsis\n\n") + fmt.Fprintf(out, "\n%s\n\n", long) + + if cmd.Runnable() { + fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.UseLine()) + } + + if len(cmd.Example) > 0 { + fmt.Fprintf(out, "### Examples\n\n") + fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.Example) + } + + printOptions(out, cmd, name) + + if len(cmd.Commands()) > 0 || cmd.HasParent() { + fmt.Fprintf(out, "### SEE ALSO\n") + if cmd.HasParent() { + parent := cmd.Parent() + pname := parent.CommandPath() + link := pname + ".md" + link = strings.Replace(link, " ", "_", -1) + fmt.Fprintf(out, "* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short) + } + + children := cmd.Commands() + sort.Sort(byName(children)) + + for _, child := range children { + if len(child.Deprecated) > 0 { + continue + } + cname := name + " " + child.Name() + link := cname + ".md" + link = strings.Replace(link, " ", "_", -1) + fmt.Fprintf(out, "* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short) + } + fmt.Fprintf(out, "\n") + } + + fmt.Fprintf(out, "###### Auto generated by spf13/cobra at %s\n", time.Now().UTC()) +} + +func GenMarkdownTree(cmd *Command, dir string) { + identity := func(s string) string { return s } + emptyStr := func(s string) string { return "" } + GenMarkdownTreeCustom(cmd, dir, emptyStr, identity) +} + +func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string) string) { + for _, c := range cmd.Commands() { + GenMarkdownTreeCustom(c, dir, filePrepender, linkHandler) + } + out := new(bytes.Buffer) + + GenMarkdownCustom(cmd, out, linkHandler) + + filename := cmd.CommandPath() + filename = dir + strings.Replace(filename, " ", "_", -1) + ".md" + outFile, err := os.Create(filename) + if err != nil { + fmt.Println(err) + os.Exit(1) + } + defer outFile.Close() + _, err = outFile.WriteString(filePrepender(filename)) + if err != nil { + fmt.Println(err) + os.Exit(1) + } + _, err = outFile.Write(out.Bytes()) + if err != nil { + fmt.Println(err) + os.Exit(1) + } +} diff --git a/vendor/github.com/spf13/cobra/doc/md_docs.md b/vendor/github.com/spf13/cobra/md_docs.md similarity index 69% rename from vendor/github.com/spf13/cobra/doc/md_docs.md rename to vendor/github.com/spf13/cobra/md_docs.md index 56ce9fe8..3a0d55ab 100644 --- a/vendor/github.com/spf13/cobra/doc/md_docs.md +++ b/vendor/github.com/spf13/cobra/md_docs.md @@ -1,31 +1,5 @@ # Generating Markdown Docs For Your Own cobra.Command -Generating man pages from a cobra command is incredibly easy. An example is as follows: - -```go -package main - -import ( - "log" - - "github.com/spf13/cobra" - "github.com/spf13/cobra/doc" -) - -func main() { - cmd := &cobra.Command{ - Use: "test", - Short: "my test program", - } - err := doc.GenMarkdownTree(cmd, "/tmp") - if err != nil { - log.Fatal(err) - } -} -``` - -That will get you a Markdown document `/tmp/test.md` - ## Generate markdown docs for the entire command tree This program can actually generate docs for the kubectl command in the kubernetes project @@ -34,22 +8,16 @@ This program can actually generate docs for the kubectl command in the kubernete package main import ( - "log" "io/ioutil" "os" - "k8s.io/kubernetes/pkg/kubectl/cmd" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - - "github.com/spf13/cobra/doc" + "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd" + "github.com/spf13/cobra" ) func main() { - kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard) - err := doc.GenMarkdownTree(kubectl, "./") - if err != nil { - log.Fatal(err) - } + kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard) + cobra.GenMarkdownTree(kubectl, "./") } ``` @@ -61,10 +29,7 @@ You may wish to have more control over the output, or only generate for a single ```go out := new(bytes.Buffer) - err := doc.GenMarkdown(cmd, out) - if err != nil { - log.Fatal(err) - } + cobra.GenMarkdown(cmd, out) ``` This will write the markdown doc for ONLY "cmd" into the out, buffer. @@ -74,14 +39,14 @@ This will write the markdown doc for ONLY "cmd" into the out, buffer. Both `GenMarkdown` and `GenMarkdownTree` have alternate versions with callbacks to get some control of the output: ```go -func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error { - //... +func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string) string) { + //... } ``` ```go -func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error { - //... +func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) { + //... } ``` @@ -113,3 +78,4 @@ linkHandler := func(name string) string { return "/commands/" + strings.ToLower(base) + "/" } ``` + diff --git a/vendor/github.com/spf13/cobra/md_docs_test.go b/vendor/github.com/spf13/cobra/md_docs_test.go new file mode 100644 index 00000000..defc9411 --- /dev/null +++ b/vendor/github.com/spf13/cobra/md_docs_test.go @@ -0,0 +1,67 @@ +package cobra + +import ( + "bytes" + "fmt" + "os" + "strings" + "testing" +) + +var _ = fmt.Println +var _ = os.Stderr + +func TestGenMdDoc(t *testing.T) { + c := initializeWithRootCmd() + // Need two commands to run the command alphabetical sort + cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated) + c.AddCommand(cmdPrint, cmdEcho) + cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp) + + out := new(bytes.Buffer) + + // We generate on s subcommand so we have both subcommands and parents + GenMarkdown(cmdEcho, out) + found := out.String() + + // Our description + expected := cmdEcho.Long + if !strings.Contains(found, expected) { + t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) + } + + // Better have our example + expected = cmdEcho.Example + if !strings.Contains(found, expected) { + t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) + } + + // A local flag + expected = "boolone" + if !strings.Contains(found, expected) { + t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) + } + + // persistent flag on parent + expected = "rootflag" + if !strings.Contains(found, expected) { + t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) + } + + // We better output info about our parent + expected = cmdRootWithRun.Short + if !strings.Contains(found, expected) { + t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) + } + + // And about subcommands + expected = cmdEchoSub.Short + if !strings.Contains(found, expected) { + t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) + } + + unexpected := cmdDeprecated.Short + if strings.Contains(found, unexpected) { + t.Errorf("Unexpected response.\nFound: %v\nBut should not have!!\n", unexpected) + } +} diff --git a/vendor/github.com/spf13/cobra/zsh_completions.go b/vendor/github.com/spf13/cobra/zsh_completions.go deleted file mode 100644 index 889c22e2..00000000 --- a/vendor/github.com/spf13/cobra/zsh_completions.go +++ /dev/null @@ -1,126 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "io" - "os" - "strings" -) - -// GenZshCompletionFile generates zsh completion file. -func (c *Command) GenZshCompletionFile(filename string) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.GenZshCompletion(outFile) -} - -// GenZshCompletion generates a zsh completion file and writes to the passed writer. -func (c *Command) GenZshCompletion(w io.Writer) error { - buf := new(bytes.Buffer) - - writeHeader(buf, c) - maxDepth := maxDepth(c) - writeLevelMapping(buf, maxDepth) - writeLevelCases(buf, maxDepth, c) - - _, err := buf.WriteTo(w) - return err -} - -func writeHeader(w io.Writer, cmd *Command) { - fmt.Fprintf(w, "#compdef %s\n\n", cmd.Name()) -} - -func maxDepth(c *Command) int { - if len(c.Commands()) == 0 { - return 0 - } - maxDepthSub := 0 - for _, s := range c.Commands() { - subDepth := maxDepth(s) - if subDepth > maxDepthSub { - maxDepthSub = subDepth - } - } - return 1 + maxDepthSub -} - -func writeLevelMapping(w io.Writer, numLevels int) { - fmt.Fprintln(w, `_arguments \`) - for i := 1; i <= numLevels; i++ { - fmt.Fprintf(w, ` '%d: :->level%d' \`, i, i) - fmt.Fprintln(w) - } - fmt.Fprintf(w, ` '%d: :%s'`, numLevels+1, "_files") - fmt.Fprintln(w) -} - -func writeLevelCases(w io.Writer, maxDepth int, root *Command) { - fmt.Fprintln(w, "case $state in") - defer fmt.Fprintln(w, "esac") - - for i := 1; i <= maxDepth; i++ { - fmt.Fprintf(w, " level%d)\n", i) - writeLevel(w, root, i) - fmt.Fprintln(w, " ;;") - } - fmt.Fprintln(w, " *)") - fmt.Fprintln(w, " _arguments '*: :_files'") - fmt.Fprintln(w, " ;;") -} - -func writeLevel(w io.Writer, root *Command, i int) { - fmt.Fprintf(w, " case $words[%d] in\n", i) - defer fmt.Fprintln(w, " esac") - - commands := filterByLevel(root, i) - byParent := groupByParent(commands) - - for p, c := range byParent { - names := names(c) - fmt.Fprintf(w, " %s)\n", p) - fmt.Fprintf(w, " _arguments '%d: :(%s)'\n", i, strings.Join(names, " ")) - fmt.Fprintln(w, " ;;") - } - fmt.Fprintln(w, " *)") - fmt.Fprintln(w, " _arguments '*: :_files'") - fmt.Fprintln(w, " ;;") - -} - -func filterByLevel(c *Command, l int) []*Command { - cs := make([]*Command, 0) - if l == 0 { - cs = append(cs, c) - return cs - } - for _, s := range c.Commands() { - cs = append(cs, filterByLevel(s, l-1)...) - } - return cs -} - -func groupByParent(commands []*Command) map[string][]*Command { - m := make(map[string][]*Command) - for _, c := range commands { - parent := c.Parent() - if parent == nil { - continue - } - m[parent.Name()] = append(m[parent.Name()], c) - } - return m -} - -func names(commands []*Command) []string { - ns := make([]string, len(commands)) - for i, c := range commands { - ns[i] = c.Name() - } - return ns -} diff --git a/vendor/github.com/spf13/cobra/zsh_completions_test.go b/vendor/github.com/spf13/cobra/zsh_completions_test.go deleted file mode 100644 index 34e69496..00000000 --- a/vendor/github.com/spf13/cobra/zsh_completions_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package cobra - -import ( - "bytes" - "strings" - "testing" -) - -func TestZshCompletion(t *testing.T) { - tcs := []struct { - name string - root *Command - expectedExpressions []string - }{ - { - name: "trivial", - root: &Command{Use: "trivialapp"}, - expectedExpressions: []string{"#compdef trivial"}, - }, - { - name: "linear", - root: func() *Command { - r := &Command{Use: "linear"} - - sub1 := &Command{Use: "sub1"} - r.AddCommand(sub1) - - sub2 := &Command{Use: "sub2"} - sub1.AddCommand(sub2) - - sub3 := &Command{Use: "sub3"} - sub2.AddCommand(sub3) - return r - }(), - expectedExpressions: []string{"sub1", "sub2", "sub3"}, - }, - { - name: "flat", - root: func() *Command { - r := &Command{Use: "flat"} - r.AddCommand(&Command{Use: "c1"}) - r.AddCommand(&Command{Use: "c2"}) - return r - }(), - expectedExpressions: []string{"(c1 c2)"}, - }, - { - name: "tree", - root: func() *Command { - r := &Command{Use: "tree"} - - sub1 := &Command{Use: "sub1"} - r.AddCommand(sub1) - - sub11 := &Command{Use: "sub11"} - sub12 := &Command{Use: "sub12"} - - sub1.AddCommand(sub11) - sub1.AddCommand(sub12) - - sub2 := &Command{Use: "sub2"} - r.AddCommand(sub2) - - sub21 := &Command{Use: "sub21"} - sub22 := &Command{Use: "sub22"} - - sub2.AddCommand(sub21) - sub2.AddCommand(sub22) - - return r - }(), - expectedExpressions: []string{"(sub11 sub12)", "(sub21 sub22)"}, - }, - } - - for _, tc := range tcs { - t.Run(tc.name, func(t *testing.T) { - buf := new(bytes.Buffer) - tc.root.GenZshCompletion(buf) - output := buf.String() - - for _, expectedExpression := range tc.expectedExpressions { - if !strings.Contains(output, expectedExpression) { - t.Errorf("Expected completion to contain %q somewhere; got %q", expectedExpression, output) - } - } - }) - } -} diff --git a/vendor/github.com/spf13/pflag/.gitignore b/vendor/github.com/spf13/pflag/.gitignore deleted file mode 100644 index c3da2901..00000000 --- a/vendor/github.com/spf13/pflag/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.idea/* - diff --git a/vendor/github.com/spf13/pflag/.travis.yml b/vendor/github.com/spf13/pflag/.travis.yml index f8a63b30..c4d88e37 100644 --- a/vendor/github.com/spf13/pflag/.travis.yml +++ b/vendor/github.com/spf13/pflag/.travis.yml @@ -3,19 +3,6 @@ sudo: false language: go go: - - 1.7.3 - - 1.8.1 - - tip - -matrix: - allow_failures: - - go: tip - -install: - - go get github.com/golang/lint/golint - - export PATH=$GOPATH/bin:$PATH - - go install ./... - -script: - - verify/all.sh -v - - go test ./... + - 1.3 + - 1.4 + - tip diff --git a/vendor/github.com/spf13/pflag/README.md b/vendor/github.com/spf13/pflag/README.md index b052414d..deee9316 100644 --- a/vendor/github.com/spf13/pflag/README.md +++ b/vendor/github.com/spf13/pflag/README.md @@ -1,6 +1,4 @@ [![Build Status](https://travis-ci.org/spf13/pflag.svg?branch=master)](https://travis-ci.org/spf13/pflag) -[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/pflag)](https://goreportcard.com/report/github.com/spf13/pflag) -[![GoDoc](https://godoc.org/github.com/spf13/pflag?status.svg)](https://godoc.org/github.com/spf13/pflag) ## Description @@ -87,7 +85,7 @@ fmt.Println("flagvar has value ", flagvar) ``` There are helpers function to get values later if you have the FlagSet but -it was difficult to keep up with all of the flag pointers in your code. +it was difficult to keep up with all of the the flag pointers in your code. If you have a pflag.FlagSet with a flag called 'flagname' of type int you can use GetInt() to get the int value. But notice that 'flagname' must exist and it must be an int. GetString("flagname") will fail. @@ -108,9 +106,9 @@ that give one-letter shorthands for flags. You can use these by appending var ip = flag.IntP("flagname", "f", 1234, "help message") var flagvar bool func init() { - flag.BoolVarP(&flagvar, "boolname", "b", true, "help message") + flag.BoolVarP("boolname", "b", true, "help message") } -flag.VarP(&flagVal, "varname", "v", "help message") +flag.VarP(&flagVar, "varname", "v", 1234, "help message") ``` Shorthand letters can be used with single dashes on the command line. @@ -218,79 +216,13 @@ func aliasNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName { myFlagSet.SetNormalizeFunc(aliasNormalizeFunc) ``` -## Deprecating a flag or its shorthand -It is possible to deprecate a flag, or just its shorthand. Deprecating a flag/shorthand hides it from help text and prints a usage message when the deprecated flag/shorthand is used. - -**Example #1**: You want to deprecate a flag named "badflag" as well as inform the users what flag they should use instead. -```go -// deprecate a flag by specifying its name and a usage message -flags.MarkDeprecated("badflag", "please use --good-flag instead") -``` -This hides "badflag" from help text, and prints `Flag --badflag has been deprecated, please use --good-flag instead` when "badflag" is used. - -**Example #2**: You want to keep a flag name "noshorthandflag" but deprecate its shortname "n". -```go -// deprecate a flag shorthand by specifying its flag name and a usage message -flags.MarkShorthandDeprecated("noshorthandflag", "please use --noshorthandflag only") -``` -This hides the shortname "n" from help text, and prints `Flag shorthand -n has been deprecated, please use --noshorthandflag only` when the shorthand "n" is used. - -Note that usage message is essential here, and it should not be empty. - -## Hidden flags -It is possible to mark a flag as hidden, meaning it will still function as normal, however will not show up in usage/help text. - -**Example**: You have a flag named "secretFlag" that you need for internal use only and don't want it showing up in help text, or for its usage text to be available. -```go -// hide a flag by specifying its name -flags.MarkHidden("secretFlag") -``` - -## Disable sorting of flags -`pflag` allows you to disable sorting of flags for help and usage message. - -**Example**: -```go -flags.BoolP("verbose", "v", false, "verbose output") -flags.String("coolflag", "yeaah", "it's really cool flag") -flags.Int("usefulflag", 777, "sometimes it's very useful") -flags.SortFlags = false -flags.PrintDefaults() -``` -**Output**: -``` - -v, --verbose verbose output - --coolflag string it's really cool flag (default "yeaah") - --usefulflag int sometimes it's very useful (default 777) -``` - - -## Supporting Go flags when using pflag -In order to support flags defined using Go's `flag` package, they must be added to the `pflag` flagset. This is usually necessary -to support flags defined by third-party dependencies (e.g. `golang/glog`). - -**Example**: You want to add the Go flags to the `CommandLine` flagset -```go -import ( - goflag "flag" - flag "github.com/spf13/pflag" -) - -var ip *int = flag.Int("flagname", 1234, "help message for flagname") - -func main() { - flag.CommandLine.AddGoFlagSet(goflag.CommandLine) - flag.Parse() -} -``` - ## More info You can see the full reference documentation of the pflag package [at godoc.org][3], or through go's standard documentation system by running `godoc -http=:6060` and browsing to -[http://localhost:6060/pkg/github.com/spf13/pflag][2] after +[http://localhost:6060/pkg/github.com/ogier/pflag][2] after installation. -[2]: http://localhost:6060/pkg/github.com/spf13/pflag -[3]: http://godoc.org/github.com/spf13/pflag +[2]: http://localhost:6060/pkg/github.com/ogier/pflag +[3]: http://godoc.org/github.com/ogier/pflag diff --git a/vendor/github.com/spf13/pflag/bool.go b/vendor/github.com/spf13/pflag/bool.go index c4c5c0bf..04c9b5af 100644 --- a/vendor/github.com/spf13/pflag/bool.go +++ b/vendor/github.com/spf13/pflag/bool.go @@ -1,6 +1,9 @@ package pflag -import "strconv" +import ( + "fmt" + "strconv" +) // optional interface to indicate boolean flags that can be // supplied without "=value" text @@ -27,7 +30,7 @@ func (b *boolValue) Type() string { return "bool" } -func (b *boolValue) String() string { return strconv.FormatBool(bool(*b)) } +func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) } func (b *boolValue) IsBoolFlag() bool { return true } @@ -50,7 +53,7 @@ func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) { f.BoolVarP(p, name, "", value, usage) } -// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash. +// Like BoolVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) { flag := f.VarPF(newBoolValue(value, p), name, shorthand, usage) flag.NoOptDefVal = "true" @@ -62,7 +65,7 @@ func BoolVar(p *bool, name string, value bool, usage string) { BoolVarP(p, name, "", value, usage) } -// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash. +// Like BoolVar, but accepts a shorthand letter that can be used after a single dash. func BoolVarP(p *bool, name, shorthand string, value bool, usage string) { flag := CommandLine.VarPF(newBoolValue(value, p), name, shorthand, usage) flag.NoOptDefVal = "true" @@ -74,7 +77,7 @@ func (f *FlagSet) Bool(name string, value bool, usage string) *bool { return f.BoolP(name, "", value, usage) } -// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash. +// Like Bool, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool { p := new(bool) f.BoolVarP(p, name, shorthand, value, usage) @@ -87,7 +90,7 @@ func Bool(name string, value bool, usage string) *bool { return BoolP(name, "", value, usage) } -// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash. +// Like Bool, but accepts a shorthand letter that can be used after a single dash. func BoolP(name, shorthand string, value bool, usage string) *bool { b := CommandLine.BoolP(name, shorthand, value, usage) return b diff --git a/vendor/github.com/spf13/pflag/bool_slice.go b/vendor/github.com/spf13/pflag/bool_slice.go deleted file mode 100644 index 5af02f1a..00000000 --- a/vendor/github.com/spf13/pflag/bool_slice.go +++ /dev/null @@ -1,147 +0,0 @@ -package pflag - -import ( - "io" - "strconv" - "strings" -) - -// -- boolSlice Value -type boolSliceValue struct { - value *[]bool - changed bool -} - -func newBoolSliceValue(val []bool, p *[]bool) *boolSliceValue { - bsv := new(boolSliceValue) - bsv.value = p - *bsv.value = val - return bsv -} - -// Set converts, and assigns, the comma-separated boolean argument string representation as the []bool value of this flag. -// If Set is called on a flag that already has a []bool assigned, the newly converted values will be appended. -func (s *boolSliceValue) Set(val string) error { - - // remove all quote characters - rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "") - - // read flag arguments with CSV parser - boolStrSlice, err := readAsCSV(rmQuote.Replace(val)) - if err != nil && err != io.EOF { - return err - } - - // parse boolean values into slice - out := make([]bool, 0, len(boolStrSlice)) - for _, boolStr := range boolStrSlice { - b, err := strconv.ParseBool(strings.TrimSpace(boolStr)) - if err != nil { - return err - } - out = append(out, b) - } - - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - - s.changed = true - - return nil -} - -// Type returns a string that uniquely represents this flag's type. -func (s *boolSliceValue) Type() string { - return "boolSlice" -} - -// String defines a "native" format for this boolean slice flag value. -func (s *boolSliceValue) String() string { - - boolStrSlice := make([]string, len(*s.value)) - for i, b := range *s.value { - boolStrSlice[i] = strconv.FormatBool(b) - } - - out, _ := writeAsCSV(boolStrSlice) - - return "[" + out + "]" -} - -func boolSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []bool{}, nil - } - ss := strings.Split(val, ",") - out := make([]bool, len(ss)) - for i, t := range ss { - var err error - out[i], err = strconv.ParseBool(t) - if err != nil { - return nil, err - } - } - return out, nil -} - -// GetBoolSlice returns the []bool value of a flag with the given name. -func (f *FlagSet) GetBoolSlice(name string) ([]bool, error) { - val, err := f.getFlagType(name, "boolSlice", boolSliceConv) - if err != nil { - return []bool{}, err - } - return val.([]bool), nil -} - -// BoolSliceVar defines a boolSlice flag with specified name, default value, and usage string. -// The argument p points to a []bool variable in which to store the value of the flag. -func (f *FlagSet) BoolSliceVar(p *[]bool, name string, value []bool, usage string) { - f.VarP(newBoolSliceValue(value, p), name, "", usage) -} - -// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) { - f.VarP(newBoolSliceValue(value, p), name, shorthand, usage) -} - -// BoolSliceVar defines a []bool flag with specified name, default value, and usage string. -// The argument p points to a []bool variable in which to store the value of the flag. -func BoolSliceVar(p *[]bool, name string, value []bool, usage string) { - CommandLine.VarP(newBoolSliceValue(value, p), name, "", usage) -} - -// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash. -func BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) { - CommandLine.VarP(newBoolSliceValue(value, p), name, shorthand, usage) -} - -// BoolSlice defines a []bool flag with specified name, default value, and usage string. -// The return value is the address of a []bool variable that stores the value of the flag. -func (f *FlagSet) BoolSlice(name string, value []bool, usage string) *[]bool { - p := []bool{} - f.BoolSliceVarP(&p, name, "", value, usage) - return &p -} - -// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool { - p := []bool{} - f.BoolSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// BoolSlice defines a []bool flag with specified name, default value, and usage string. -// The return value is the address of a []bool variable that stores the value of the flag. -func BoolSlice(name string, value []bool, usage string) *[]bool { - return CommandLine.BoolSliceP(name, "", value, usage) -} - -// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash. -func BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool { - return CommandLine.BoolSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/bool_slice_test.go b/vendor/github.com/spf13/pflag/bool_slice_test.go deleted file mode 100644 index b617dd23..00000000 --- a/vendor/github.com/spf13/pflag/bool_slice_test.go +++ /dev/null @@ -1,215 +0,0 @@ -package pflag - -import ( - "fmt" - "strconv" - "strings" - "testing" -) - -func setUpBSFlagSet(bsp *[]bool) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.BoolSliceVar(bsp, "bs", []bool{}, "Command separated list!") - return f -} - -func setUpBSFlagSetWithDefault(bsp *[]bool) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.BoolSliceVar(bsp, "bs", []bool{false, true}, "Command separated list!") - return f -} - -func TestEmptyBS(t *testing.T) { - var bs []bool - f := setUpBSFlagSet(&bs) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getBS, err := f.GetBoolSlice("bs") - if err != nil { - t.Fatal("got an error from GetBoolSlice():", err) - } - if len(getBS) != 0 { - t.Fatalf("got bs %v with len=%d but expected length=0", getBS, len(getBS)) - } -} - -func TestBS(t *testing.T) { - var bs []bool - f := setUpBSFlagSet(&bs) - - vals := []string{"1", "F", "TRUE", "0"} - arg := fmt.Sprintf("--bs=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range bs { - b, err := strconv.ParseBool(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if b != v { - t.Fatalf("expected is[%d] to be %s but got: %t", i, vals[i], v) - } - } - getBS, err := f.GetBoolSlice("bs") - if err != nil { - t.Fatalf("got error: %v", err) - } - for i, v := range getBS { - b, err := strconv.ParseBool(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if b != v { - t.Fatalf("expected bs[%d] to be %s but got: %t from GetBoolSlice", i, vals[i], v) - } - } -} - -func TestBSDefault(t *testing.T) { - var bs []bool - f := setUpBSFlagSetWithDefault(&bs) - - vals := []string{"false", "T"} - - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range bs { - b, err := strconv.ParseBool(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if b != v { - t.Fatalf("expected bs[%d] to be %t from GetBoolSlice but got: %t", i, b, v) - } - } - - getBS, err := f.GetBoolSlice("bs") - if err != nil { - t.Fatal("got an error from GetBoolSlice():", err) - } - for i, v := range getBS { - b, err := strconv.ParseBool(vals[i]) - if err != nil { - t.Fatal("got an error from GetBoolSlice():", err) - } - if b != v { - t.Fatalf("expected bs[%d] to be %t from GetBoolSlice but got: %t", i, b, v) - } - } -} - -func TestBSWithDefault(t *testing.T) { - var bs []bool - f := setUpBSFlagSetWithDefault(&bs) - - vals := []string{"FALSE", "1"} - arg := fmt.Sprintf("--bs=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range bs { - b, err := strconv.ParseBool(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if b != v { - t.Fatalf("expected bs[%d] to be %t but got: %t", i, b, v) - } - } - - getBS, err := f.GetBoolSlice("bs") - if err != nil { - t.Fatal("got an error from GetBoolSlice():", err) - } - for i, v := range getBS { - b, err := strconv.ParseBool(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if b != v { - t.Fatalf("expected bs[%d] to be %t from GetBoolSlice but got: %t", i, b, v) - } - } -} - -func TestBSCalledTwice(t *testing.T) { - var bs []bool - f := setUpBSFlagSet(&bs) - - in := []string{"T,F", "T"} - expected := []bool{true, false, true} - argfmt := "--bs=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range bs { - if expected[i] != v { - t.Fatalf("expected bs[%d] to be %t but got %t", i, expected[i], v) - } - } -} - -func TestBSBadQuoting(t *testing.T) { - - tests := []struct { - Want []bool - FlagArg []string - }{ - { - Want: []bool{true, false, true}, - FlagArg: []string{"1", "0", "true"}, - }, - { - Want: []bool{true, false}, - FlagArg: []string{"True", "F"}, - }, - { - Want: []bool{true, false}, - FlagArg: []string{"T", "0"}, - }, - { - Want: []bool{true, false}, - FlagArg: []string{"1", "0"}, - }, - { - Want: []bool{true, false, false}, - FlagArg: []string{"true,false", "false"}, - }, - { - Want: []bool{true, false, false, true, false, true, false}, - FlagArg: []string{`"true,false,false,1,0, T"`, " false "}, - }, - { - Want: []bool{false, false, true, false, true, false, true}, - FlagArg: []string{`"0, False, T,false , true,F"`, "true"}, - }, - } - - for i, test := range tests { - - var bs []bool - f := setUpBSFlagSet(&bs) - - if err := f.Parse([]string{fmt.Sprintf("--bs=%s", strings.Join(test.FlagArg, ","))}); err != nil { - t.Fatalf("flag parsing failed with error: %s\nparsing:\t%#v\nwant:\t\t%#v", - err, test.FlagArg, test.Want[i]) - } - - for j, b := range bs { - if b != test.Want[j] { - t.Fatalf("bad value parsed for test %d on bool %d:\nwant:\t%t\ngot:\t%t", i, j, test.Want[j], b) - } - } - } -} diff --git a/vendor/github.com/spf13/pflag/bool_test.go b/vendor/github.com/spf13/pflag/bool_test.go index a4319e79..afd25ae2 100644 --- a/vendor/github.com/spf13/pflag/bool_test.go +++ b/vendor/github.com/spf13/pflag/bool_test.go @@ -6,6 +6,7 @@ package pflag import ( "bytes" + "fmt" "strconv" "testing" ) @@ -47,7 +48,7 @@ func (v *triStateValue) String() string { if *v == triStateMaybe { return strTriStateMaybe } - return strconv.FormatBool(*v == triStateTrue) + return fmt.Sprintf("%v", bool(*v == triStateTrue)) } // The type of the flag as required by the pflag.Value interface @@ -171,9 +172,9 @@ func TestBoolP(t *testing.T) { t.Error("expected no error, got ", err) } if *b != true { - t.Errorf("expected b=true got b=%v", *b) + t.Errorf("expected b=true got b=%s", b) } if *c != false { - t.Errorf("expect c=false got c=%v", *c) + t.Errorf("expect c=false got c=%s", c) } } diff --git a/vendor/github.com/spf13/pflag/bytes.go b/vendor/github.com/spf13/pflag/bytes.go deleted file mode 100644 index 12c58db9..00000000 --- a/vendor/github.com/spf13/pflag/bytes.go +++ /dev/null @@ -1,105 +0,0 @@ -package pflag - -import ( - "encoding/hex" - "fmt" - "strings" -) - -// BytesHex adapts []byte for use as a flag. Value of flag is HEX encoded -type bytesHexValue []byte - -func (bytesHex bytesHexValue) String() string { - return fmt.Sprintf("%X", []byte(bytesHex)) -} - -func (bytesHex *bytesHexValue) Set(value string) error { - bin, err := hex.DecodeString(strings.TrimSpace(value)) - - if err != nil { - return err - } - - *bytesHex = bin - - return nil -} - -func (*bytesHexValue) Type() string { - return "bytesHex" -} - -func newBytesHexValue(val []byte, p *[]byte) *bytesHexValue { - *p = val - return (*bytesHexValue)(p) -} - -func bytesHexConv(sval string) (interface{}, error) { - - bin, err := hex.DecodeString(sval) - - if err == nil { - return bin, nil - } - - return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err) -} - -// GetBytesHex return the []byte value of a flag with the given name -func (f *FlagSet) GetBytesHex(name string) ([]byte, error) { - val, err := f.getFlagType(name, "bytesHex", bytesHexConv) - - if err != nil { - return []byte{}, err - } - - return val.([]byte), nil -} - -// BytesHexVar defines an []byte flag with specified name, default value, and usage string. -// The argument p points to an []byte variable in which to store the value of the flag. -func (f *FlagSet) BytesHexVar(p *[]byte, name string, value []byte, usage string) { - f.VarP(newBytesHexValue(value, p), name, "", usage) -} - -// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) { - f.VarP(newBytesHexValue(value, p), name, shorthand, usage) -} - -// BytesHexVar defines an []byte flag with specified name, default value, and usage string. -// The argument p points to an []byte variable in which to store the value of the flag. -func BytesHexVar(p *[]byte, name string, value []byte, usage string) { - CommandLine.VarP(newBytesHexValue(value, p), name, "", usage) -} - -// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash. -func BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) { - CommandLine.VarP(newBytesHexValue(value, p), name, shorthand, usage) -} - -// BytesHex defines an []byte flag with specified name, default value, and usage string. -// The return value is the address of an []byte variable that stores the value of the flag. -func (f *FlagSet) BytesHex(name string, value []byte, usage string) *[]byte { - p := new([]byte) - f.BytesHexVarP(p, name, "", value, usage) - return p -} - -// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BytesHexP(name, shorthand string, value []byte, usage string) *[]byte { - p := new([]byte) - f.BytesHexVarP(p, name, shorthand, value, usage) - return p -} - -// BytesHex defines an []byte flag with specified name, default value, and usage string. -// The return value is the address of an []byte variable that stores the value of the flag. -func BytesHex(name string, value []byte, usage string) *[]byte { - return CommandLine.BytesHexP(name, "", value, usage) -} - -// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash. -func BytesHexP(name, shorthand string, value []byte, usage string) *[]byte { - return CommandLine.BytesHexP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/bytes_test.go b/vendor/github.com/spf13/pflag/bytes_test.go deleted file mode 100644 index cc4a769d..00000000 --- a/vendor/github.com/spf13/pflag/bytes_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package pflag - -import ( - "fmt" - "os" - "testing" -) - -func setUpBytesHex(bytesHex *[]byte) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.BytesHexVar(bytesHex, "bytes", []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, "Some bytes in HEX") - f.BytesHexVarP(bytesHex, "bytes2", "B", []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, "Some bytes in HEX") - return f -} - -func TestBytesHex(t *testing.T) { - testCases := []struct { - input string - success bool - expected string - }{ - /// Positive cases - {"", true, ""}, // Is empty string OK ? - {"01", true, "01"}, - {"0101", true, "0101"}, - {"1234567890abcdef", true, "1234567890ABCDEF"}, - {"1234567890ABCDEF", true, "1234567890ABCDEF"}, - - // Negative cases - {"0", false, ""}, // Short string - {"000", false, ""}, /// Odd-length string - {"qq", false, ""}, /// non-hex character - } - - devnull, _ := os.Open(os.DevNull) - os.Stderr = devnull - - for i := range testCases { - var bytesHex []byte - f := setUpBytesHex(&bytesHex) - - tc := &testCases[i] - - // --bytes - args := []string{ - fmt.Sprintf("--bytes=%s", tc.input), - fmt.Sprintf("-B %s", tc.input), - fmt.Sprintf("--bytes2=%s", tc.input), - } - - for _, arg := range args { - err := f.Parse([]string{arg}) - - if err != nil && tc.success == true { - t.Errorf("expected success, got %q", err) - continue - } else if err == nil && tc.success == false { - // bytesHex, err := f.GetBytesHex("bytes") - t.Errorf("expected failure while processing %q", tc.input) - continue - } else if tc.success { - bytesHex, err := f.GetBytesHex("bytes") - if err != nil { - t.Errorf("Got error trying to fetch the IP flag: %v", err) - } - if fmt.Sprintf("%X", bytesHex) != tc.expected { - t.Errorf("expected %q, got '%X'", tc.expected, bytesHex) - } - } - } - } -} diff --git a/vendor/github.com/spf13/pflag/count.go b/vendor/github.com/spf13/pflag/count.go index aa126e44..d0613688 100644 --- a/vendor/github.com/spf13/pflag/count.go +++ b/vendor/github.com/spf13/pflag/count.go @@ -1,6 +1,9 @@ package pflag -import "strconv" +import ( + "fmt" + "strconv" +) // -- count Value type countValue int @@ -11,13 +14,13 @@ func newCountValue(val int, p *int) *countValue { } func (i *countValue) Set(s string) error { - // "+1" means that no specific value was passed, so increment - if s == "+1" { + v, err := strconv.ParseInt(s, 0, 64) + // -1 means that no specific value was passed, so increment + if v == -1 { *i = countValue(*i + 1) - return nil + } else { + *i = countValue(v) } - v, err := strconv.ParseInt(s, 0, 0) - *i = countValue(v) return err } @@ -25,7 +28,7 @@ func (i *countValue) Type() string { return "count" } -func (i *countValue) String() string { return strconv.Itoa(int(*i)) } +func (i *countValue) String() string { return fmt.Sprintf("%v", *i) } func countConv(sval string) (interface{}, error) { i, err := strconv.Atoi(sval) @@ -35,7 +38,6 @@ func countConv(sval string) (interface{}, error) { return i, nil } -// GetCount return the int value of a flag with the given name func (f *FlagSet) GetCount(name string) (int, error) { val, err := f.getFlagType(name, "count", countConv) if err != nil { @@ -44,53 +46,39 @@ func (f *FlagSet) GetCount(name string) (int, error) { return val.(int), nil } -// CountVar defines a count flag with specified name, default value, and usage string. -// The argument p points to an int variable in which to store the value of the flag. -// A count flag will add 1 to its value evey time it is found on the command line func (f *FlagSet) CountVar(p *int, name string, usage string) { f.CountVarP(p, name, "", usage) } -// CountVarP is like CountVar only take a shorthand for the flag name. func (f *FlagSet) CountVarP(p *int, name, shorthand string, usage string) { flag := f.VarPF(newCountValue(0, p), name, shorthand, usage) - flag.NoOptDefVal = "+1" + flag.NoOptDefVal = "-1" } -// CountVar like CountVar only the flag is placed on the CommandLine instead of a given flag set func CountVar(p *int, name string, usage string) { CommandLine.CountVar(p, name, usage) } -// CountVarP is like CountVar only take a shorthand for the flag name. func CountVarP(p *int, name, shorthand string, usage string) { CommandLine.CountVarP(p, name, shorthand, usage) } -// Count defines a count flag with specified name, default value, and usage string. -// The return value is the address of an int variable that stores the value of the flag. -// A count flag will add 1 to its value evey time it is found on the command line func (f *FlagSet) Count(name string, usage string) *int { p := new(int) f.CountVarP(p, name, "", usage) return p } -// CountP is like Count only takes a shorthand for the flag name. func (f *FlagSet) CountP(name, shorthand string, usage string) *int { p := new(int) f.CountVarP(p, name, shorthand, usage) return p } -// Count defines a count flag with specified name, default value, and usage string. -// The return value is the address of an int variable that stores the value of the flag. -// A count flag will add 1 to its value evey time it is found on the command line func Count(name string, usage string) *int { return CommandLine.CountP(name, "", usage) } -// CountP is like Count only takes a shorthand for the flag name. func CountP(name, shorthand string, usage string) *int { return CommandLine.CountP(name, shorthand, usage) } diff --git a/vendor/github.com/spf13/pflag/count_test.go b/vendor/github.com/spf13/pflag/count_test.go index 3785d375..716765cb 100644 --- a/vendor/github.com/spf13/pflag/count_test.go +++ b/vendor/github.com/spf13/pflag/count_test.go @@ -1,10 +1,13 @@ package pflag import ( + "fmt" "os" "testing" ) +var _ = fmt.Printf + func setUpCount(c *int) *FlagSet { f := NewFlagSet("test", ContinueOnError) f.CountVarP(c, "verbose", "v", "a counter") @@ -17,14 +20,10 @@ func TestCount(t *testing.T) { success bool expected int }{ - {[]string{}, true, 0}, - {[]string{"-v"}, true, 1}, {[]string{"-vvv"}, true, 3}, {[]string{"-v", "-v", "-v"}, true, 3}, {[]string{"-v", "--verbose", "-v"}, true, 3}, {[]string{"-v=3", "-v"}, true, 4}, - {[]string{"--verbose=0"}, true, 0}, - {[]string{"-v=0"}, true, 0}, {[]string{"-v=a"}, false, 0}, } @@ -49,7 +48,7 @@ func TestCount(t *testing.T) { t.Errorf("Got error trying to fetch the counter flag") } if c != tc.expected { - t.Errorf("expected %d, got %d", tc.expected, c) + t.Errorf("expected %q, got %q", tc.expected, c) } } } diff --git a/vendor/github.com/spf13/pflag/duration.go b/vendor/github.com/spf13/pflag/duration.go index e9debef8..382ffd3c 100644 --- a/vendor/github.com/spf13/pflag/duration.go +++ b/vendor/github.com/spf13/pflag/duration.go @@ -43,7 +43,7 @@ func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration f.VarP(newDurationValue(value, p), name, "", usage) } -// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash. +// Like DurationVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) { f.VarP(newDurationValue(value, p), name, shorthand, usage) } @@ -54,7 +54,7 @@ func DurationVar(p *time.Duration, name string, value time.Duration, usage strin CommandLine.VarP(newDurationValue(value, p), name, "", usage) } -// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash. +// Like DurationVar, but accepts a shorthand letter that can be used after a single dash. func DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) { CommandLine.VarP(newDurationValue(value, p), name, shorthand, usage) } @@ -67,7 +67,7 @@ func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time return p } -// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash. +// Like Duration, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration { p := new(time.Duration) f.DurationVarP(p, name, shorthand, value, usage) @@ -80,7 +80,7 @@ func Duration(name string, value time.Duration, usage string) *time.Duration { return CommandLine.DurationP(name, "", value, usage) } -// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash. +// Like Duration, but accepts a shorthand letter that can be used after a single dash. func DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration { return CommandLine.DurationP(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/duration_slice.go b/vendor/github.com/spf13/pflag/duration_slice.go deleted file mode 100644 index 52c6b6dc..00000000 --- a/vendor/github.com/spf13/pflag/duration_slice.go +++ /dev/null @@ -1,128 +0,0 @@ -package pflag - -import ( - "fmt" - "strings" - "time" -) - -// -- durationSlice Value -type durationSliceValue struct { - value *[]time.Duration - changed bool -} - -func newDurationSliceValue(val []time.Duration, p *[]time.Duration) *durationSliceValue { - dsv := new(durationSliceValue) - dsv.value = p - *dsv.value = val - return dsv -} - -func (s *durationSliceValue) Set(val string) error { - ss := strings.Split(val, ",") - out := make([]time.Duration, len(ss)) - for i, d := range ss { - var err error - out[i], err = time.ParseDuration(d) - if err != nil { - return err - } - - } - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - s.changed = true - return nil -} - -func (s *durationSliceValue) Type() string { - return "durationSlice" -} - -func (s *durationSliceValue) String() string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = fmt.Sprintf("%s", d) - } - return "[" + strings.Join(out, ",") + "]" -} - -func durationSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []time.Duration{}, nil - } - ss := strings.Split(val, ",") - out := make([]time.Duration, len(ss)) - for i, d := range ss { - var err error - out[i], err = time.ParseDuration(d) - if err != nil { - return nil, err - } - - } - return out, nil -} - -// GetDurationSlice returns the []time.Duration value of a flag with the given name -func (f *FlagSet) GetDurationSlice(name string) ([]time.Duration, error) { - val, err := f.getFlagType(name, "durationSlice", durationSliceConv) - if err != nil { - return []time.Duration{}, err - } - return val.([]time.Duration), nil -} - -// DurationSliceVar defines a durationSlice flag with specified name, default value, and usage string. -// The argument p points to a []time.Duration variable in which to store the value of the flag. -func (f *FlagSet) DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) { - f.VarP(newDurationSliceValue(value, p), name, "", usage) -} - -// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) { - f.VarP(newDurationSliceValue(value, p), name, shorthand, usage) -} - -// DurationSliceVar defines a duration[] flag with specified name, default value, and usage string. -// The argument p points to a duration[] variable in which to store the value of the flag. -func DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) { - CommandLine.VarP(newDurationSliceValue(value, p), name, "", usage) -} - -// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash. -func DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) { - CommandLine.VarP(newDurationSliceValue(value, p), name, shorthand, usage) -} - -// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string. -// The return value is the address of a []time.Duration variable that stores the value of the flag. -func (f *FlagSet) DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration { - p := []time.Duration{} - f.DurationSliceVarP(&p, name, "", value, usage) - return &p -} - -// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration { - p := []time.Duration{} - f.DurationSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string. -// The return value is the address of a []time.Duration variable that stores the value of the flag. -func DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration { - return CommandLine.DurationSliceP(name, "", value, usage) -} - -// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash. -func DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration { - return CommandLine.DurationSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/duration_slice_test.go b/vendor/github.com/spf13/pflag/duration_slice_test.go deleted file mode 100644 index 489b012f..00000000 --- a/vendor/github.com/spf13/pflag/duration_slice_test.go +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code ds governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag - -import ( - "fmt" - "strings" - "testing" - "time" -) - -func setUpDSFlagSet(dsp *[]time.Duration) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.DurationSliceVar(dsp, "ds", []time.Duration{}, "Command separated list!") - return f -} - -func setUpDSFlagSetWithDefault(dsp *[]time.Duration) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.DurationSliceVar(dsp, "ds", []time.Duration{0, 1}, "Command separated list!") - return f -} - -func TestEmptyDS(t *testing.T) { - var ds []time.Duration - f := setUpDSFlagSet(&ds) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getDS, err := f.GetDurationSlice("ds") - if err != nil { - t.Fatal("got an error from GetDurationSlice():", err) - } - if len(getDS) != 0 { - t.Fatalf("got ds %v with len=%d but expected length=0", getDS, len(getDS)) - } -} - -func TestDS(t *testing.T) { - var ds []time.Duration - f := setUpDSFlagSet(&ds) - - vals := []string{"1ns", "2ms", "3m", "4h"} - arg := fmt.Sprintf("--ds=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ds { - d, err := time.ParseDuration(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected ds[%d] to be %s but got: %d", i, vals[i], v) - } - } - getDS, err := f.GetDurationSlice("ds") - if err != nil { - t.Fatalf("got error: %v", err) - } - for i, v := range getDS { - d, err := time.ParseDuration(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected ds[%d] to be %s but got: %d from GetDurationSlice", i, vals[i], v) - } - } -} - -func TestDSDefault(t *testing.T) { - var ds []time.Duration - f := setUpDSFlagSetWithDefault(&ds) - - vals := []string{"0s", "1ns"} - - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ds { - d, err := time.ParseDuration(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected ds[%d] to be %d but got: %d", i, d, v) - } - } - - getDS, err := f.GetDurationSlice("ds") - if err != nil { - t.Fatal("got an error from GetDurationSlice():", err) - } - for i, v := range getDS { - d, err := time.ParseDuration(vals[i]) - if err != nil { - t.Fatal("got an error from GetDurationSlice():", err) - } - if d != v { - t.Fatalf("expected ds[%d] to be %d from GetDurationSlice but got: %d", i, d, v) - } - } -} - -func TestDSWithDefault(t *testing.T) { - var ds []time.Duration - f := setUpDSFlagSetWithDefault(&ds) - - vals := []string{"1ns", "2ns"} - arg := fmt.Sprintf("--ds=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ds { - d, err := time.ParseDuration(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected ds[%d] to be %d but got: %d", i, d, v) - } - } - - getDS, err := f.GetDurationSlice("ds") - if err != nil { - t.Fatal("got an error from GetDurationSlice():", err) - } - for i, v := range getDS { - d, err := time.ParseDuration(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected ds[%d] to be %d from GetDurationSlice but got: %d", i, d, v) - } - } -} - -func TestDSCalledTwice(t *testing.T) { - var ds []time.Duration - f := setUpDSFlagSet(&ds) - - in := []string{"1ns,2ns", "3ns"} - expected := []time.Duration{1, 2, 3} - argfmt := "--ds=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ds { - if expected[i] != v { - t.Fatalf("expected ds[%d] to be %d but got: %d", i, expected[i], v) - } - } -} diff --git a/vendor/github.com/spf13/pflag/example_test.go b/vendor/github.com/spf13/pflag/example_test.go index abd7806f..9be7a49f 100644 --- a/vendor/github.com/spf13/pflag/example_test.go +++ b/vendor/github.com/spf13/pflag/example_test.go @@ -2,35 +2,76 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +// These examples demonstrate more intricate uses of the flag package. package pflag_test import ( + "errors" "fmt" + "strings" + "time" - "github.com/spf13/pflag" + flag "github.com/spf13/pflag" ) -func ExampleShorthandLookup() { - name := "verbose" - short := name[:1] +// Example 1: A single string flag called "species" with default value "gopher". +var species = flag.String("species", "gopher", "the species we are studying") - pflag.BoolP(name, short, false, "verbose output") +// Example 2: A flag with a shorthand letter. +var gopherType = flag.StringP("gopher_type", "g", "pocket", "the variety of gopher") - // len(short) must be == 1 - flag := pflag.ShorthandLookup(short) +// Example 3: A user-defined flag type, a slice of durations. +type interval []time.Duration - fmt.Println(flag.Name) +// String is the method to format the flag's value, part of the flag.Value interface. +// The String method's output will be used in diagnostics. +func (i *interval) String() string { + return fmt.Sprint(*i) } -func ExampleFlagSet_ShorthandLookup() { - name := "verbose" - short := name[:1] - - fs := pflag.NewFlagSet("Example", pflag.ContinueOnError) - fs.BoolP(name, short, false, "verbose output") - - // len(short) must be == 1 - flag := fs.ShorthandLookup(short) - - fmt.Println(flag.Name) +func (i *interval) Type() string { + return "interval" +} + +// Set is the method to set the flag value, part of the flag.Value interface. +// Set's argument is a string to be parsed to set the flag. +// It's a comma-separated list, so we split it. +func (i *interval) Set(value string) error { + // If we wanted to allow the flag to be set multiple times, + // accumulating values, we would delete this if statement. + // That would permit usages such as + // -deltaT 10s -deltaT 15s + // and other combinations. + if len(*i) > 0 { + return errors.New("interval flag already set") + } + for _, dt := range strings.Split(value, ",") { + duration, err := time.ParseDuration(dt) + if err != nil { + return err + } + *i = append(*i, duration) + } + return nil +} + +// Define a flag to accumulate durations. Because it has a special type, +// we need to use the Var function and therefore create the flag during +// init. + +var intervalFlag interval + +func init() { + // Tie the command-line flag to the intervalFlag variable and + // set a usage message. + flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events") +} + +func Example() { + // All the interesting pieces are with the variables declared above, but + // to enable the flag package to see the flags defined there, one must + // execute, typically at the start of main (not init!): + // flag.Parse() + // We don't run it here because this is not a main function and + // the testing suite has already parsed the flags. } diff --git a/vendor/github.com/spf13/pflag/flag.go b/vendor/github.com/spf13/pflag/flag.go index 5eadc84e..c45ad0f0 100644 --- a/vendor/github.com/spf13/pflag/flag.go +++ b/vendor/github.com/spf13/pflag/flag.go @@ -3,105 +3,104 @@ // license that can be found in the LICENSE file. /* -Package pflag is a drop-in replacement for Go's flag package, implementing -POSIX/GNU-style --flags. + pflag is a drop-in replacement for Go's flag package, implementing + POSIX/GNU-style --flags. -pflag is compatible with the GNU extensions to the POSIX recommendations -for command-line options. See -http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html + pflag is compatible with the GNU extensions to the POSIX recommendations + for command-line options. See + http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html -Usage: + Usage: -pflag is a drop-in replacement of Go's native flag package. If you import -pflag under the name "flag" then all code should continue to function -with no changes. + pflag is a drop-in replacement of Go's native flag package. If you import + pflag under the name "flag" then all code should continue to function + with no changes. - import flag "github.com/spf13/pflag" + import flag "github.com/ogier/pflag" -There is one exception to this: if you directly instantiate the Flag struct -there is one more field "Shorthand" that you will need to set. -Most code never instantiates this struct directly, and instead uses -functions such as String(), BoolVar(), and Var(), and is therefore -unaffected. + There is one exception to this: if you directly instantiate the Flag struct + there is one more field "Shorthand" that you will need to set. + Most code never instantiates this struct directly, and instead uses + functions such as String(), BoolVar(), and Var(), and is therefore + unaffected. -Define flags using flag.String(), Bool(), Int(), etc. + Define flags using flag.String(), Bool(), Int(), etc. -This declares an integer flag, -flagname, stored in the pointer ip, with type *int. - var ip = flag.Int("flagname", 1234, "help message for flagname") -If you like, you can bind the flag to a variable using the Var() functions. - var flagvar int - func init() { - flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") - } -Or you can create custom flags that satisfy the Value interface (with -pointer receivers) and couple them to flag parsing by - flag.Var(&flagVal, "name", "help message for flagname") -For such flags, the default value is just the initial value of the variable. + This declares an integer flag, -flagname, stored in the pointer ip, with type *int. + var ip = flag.Int("flagname", 1234, "help message for flagname") + If you like, you can bind the flag to a variable using the Var() functions. + var flagvar int + func init() { + flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") + } + Or you can create custom flags that satisfy the Value interface (with + pointer receivers) and couple them to flag parsing by + flag.Var(&flagVal, "name", "help message for flagname") + For such flags, the default value is just the initial value of the variable. -After all flags are defined, call - flag.Parse() -to parse the command line into the defined flags. + After all flags are defined, call + flag.Parse() + to parse the command line into the defined flags. -Flags may then be used directly. If you're using the flags themselves, -they are all pointers; if you bind to variables, they're values. - fmt.Println("ip has value ", *ip) - fmt.Println("flagvar has value ", flagvar) + Flags may then be used directly. If you're using the flags themselves, + they are all pointers; if you bind to variables, they're values. + fmt.Println("ip has value ", *ip) + fmt.Println("flagvar has value ", flagvar) -After parsing, the arguments after the flag are available as the -slice flag.Args() or individually as flag.Arg(i). -The arguments are indexed from 0 through flag.NArg()-1. + After parsing, the arguments after the flag are available as the + slice flag.Args() or individually as flag.Arg(i). + The arguments are indexed from 0 through flag.NArg()-1. -The pflag package also defines some new functions that are not in flag, -that give one-letter shorthands for flags. You can use these by appending -'P' to the name of any function that defines a flag. - var ip = flag.IntP("flagname", "f", 1234, "help message") - var flagvar bool - func init() { - flag.BoolVarP("boolname", "b", true, "help message") - } - flag.VarP(&flagVar, "varname", "v", 1234, "help message") -Shorthand letters can be used with single dashes on the command line. -Boolean shorthand flags can be combined with other shorthand flags. + The pflag package also defines some new functions that are not in flag, + that give one-letter shorthands for flags. You can use these by appending + 'P' to the name of any function that defines a flag. + var ip = flag.IntP("flagname", "f", 1234, "help message") + var flagvar bool + func init() { + flag.BoolVarP("boolname", "b", true, "help message") + } + flag.VarP(&flagVar, "varname", "v", 1234, "help message") + Shorthand letters can be used with single dashes on the command line. + Boolean shorthand flags can be combined with other shorthand flags. -Command line flag syntax: - --flag // boolean flags only - --flag=x + Command line flag syntax: + --flag // boolean flags only + --flag=x -Unlike the flag package, a single dash before an option means something -different than a double dash. Single dashes signify a series of shorthand -letters for flags. All but the last shorthand letter must be boolean flags. - // boolean flags - -f - -abc - // non-boolean flags - -n 1234 - -Ifile - // mixed - -abcs "hello" - -abcn1234 + Unlike the flag package, a single dash before an option means something + different than a double dash. Single dashes signify a series of shorthand + letters for flags. All but the last shorthand letter must be boolean flags. + // boolean flags + -f + -abc + // non-boolean flags + -n 1234 + -Ifile + // mixed + -abcs "hello" + -abcn1234 -Flag parsing stops after the terminator "--". Unlike the flag package, -flags can be interspersed with arguments anywhere on the command line -before this terminator. + Flag parsing stops after the terminator "--". Unlike the flag package, + flags can be interspersed with arguments anywhere on the command line + before this terminator. -Integer flags accept 1234, 0664, 0x1234 and may be negative. -Boolean flags (in their long form) accept 1, 0, t, f, true, false, -TRUE, FALSE, True, False. -Duration flags accept any input valid for time.ParseDuration. + Integer flags accept 1234, 0664, 0x1234 and may be negative. + Boolean flags (in their long form) accept 1, 0, t, f, true, false, + TRUE, FALSE, True, False. + Duration flags accept any input valid for time.ParseDuration. -The default set of command-line flags is controlled by -top-level functions. The FlagSet type allows one to define -independent sets of flags, such as to implement subcommands -in a command-line interface. The methods of FlagSet are -analogous to the top-level functions for the command-line -flag set. + The default set of command-line flags is controlled by + top-level functions. The FlagSet type allows one to define + independent sets of flags, such as to implement subcommands + in a command-line interface. The methods of FlagSet are + analogous to the top-level functions for the command-line + flag set. */ package pflag import ( "bytes" "errors" - goflag "flag" "fmt" "io" "os" @@ -116,20 +115,11 @@ var ErrHelp = errors.New("pflag: help requested") type ErrorHandling int const ( - // ContinueOnError will return an err from Parse() if an error is found ContinueOnError ErrorHandling = iota - // ExitOnError will call os.Exit(2) if an error is found when parsing ExitOnError - // PanicOnError will panic() if an error is found when parsing flags PanicOnError ) -// ParseErrorsWhitelist defines the parsing errors that can be ignored -type ParseErrorsWhitelist struct { - // UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags - UnknownFlags bool -} - // NormalizedName is a flag name that has been normalized according to rules // for the FlagSet (e.g. making '-' and '_' equivalent). type NormalizedName string @@ -141,45 +131,30 @@ type FlagSet struct { // a custom error handler. Usage func() - // SortFlags is used to indicate, if user wants to have sorted flags in - // help/usage messages. - SortFlags bool - - // ParseErrorsWhitelist is used to configure a whitelist of errors - ParseErrorsWhitelist ParseErrorsWhitelist - name string parsed bool actual map[NormalizedName]*Flag - orderedActual []*Flag - sortedActual []*Flag formal map[NormalizedName]*Flag - orderedFormal []*Flag - sortedFormal []*Flag shorthands map[byte]*Flag args []string // arguments after flags - argsLenAtDash int // len(args) when a '--' was located when parsing, or -1 if no -- + exitOnError bool // does the program exit if there's an error? errorHandling ErrorHandling output io.Writer // nil means stderr; use out() accessor interspersed bool // allow interspersed option/non-option args normalizeNameFunc func(f *FlagSet, name string) NormalizedName - - addedGoFlagSets []*goflag.FlagSet } // A Flag represents the state of a flag. type Flag struct { - Name string // name as it appears on command line - Shorthand string // one-letter abbreviated flag - Usage string // help message - Value Value // value as set - DefValue string // default value (as text); for usage message - Changed bool // If the user set the value (or if left to default) - NoOptDefVal string // default value (as text); if the flag is on the command line without any options - Deprecated string // If this flag is deprecated, this string is the new or now thing to use - Hidden bool // used by cobra.Command to allow flags to be hidden from help/usage text - ShorthandDeprecated string // If the shorthand of this flag is deprecated, this string is the new or now thing to use - Annotations map[string][]string // used by cobra.Command bash autocomple code + Name string // name as it appears on command line + Shorthand string // one-letter abbreviated flag + Usage string // help message + Value Value // value as set + DefValue string // default value (as text); for usage message + Changed bool // If the user set the value (or if left to default) + NoOptDefVal string //default value (as text); if the flag is on the command line without any options + Deprecated string // If this flag is deprecated, this string is the new or now thing to use + Annotations map[string][]string // used by cobra.Command bash autocomple code } // Value is the interface to the dynamic value stored in a flag. @@ -206,31 +181,16 @@ func sortFlags(flags map[NormalizedName]*Flag) []*Flag { return result } -// SetNormalizeFunc allows you to add a function which can translate flag names. -// Flags added to the FlagSet will be translated and then when anything tries to -// look up the flag that will also be translated. So it would be possible to create -// a flag named "getURL" and have it translated to "geturl". A user could then pass -// "--getUrl" which may also be translated to "geturl" and everything will work. func (f *FlagSet) SetNormalizeFunc(n func(f *FlagSet, name string) NormalizedName) { f.normalizeNameFunc = n - f.sortedFormal = f.sortedFormal[:0] - for fname, flag := range f.formal { - nname := f.normalizeFlagName(flag.Name) - if fname == nname { - continue - } - flag.Name = string(nname) - delete(f.formal, fname) - f.formal[nname] = flag - if _, set := f.actual[fname]; set { - delete(f.actual, fname) - f.actual[nname] = flag - } + for k, v := range f.formal { + delete(f.formal, k) + nname := f.normalizeFlagName(string(k)) + f.formal[nname] = v + v.Name = string(nname) } } -// GetNormalizeFunc returns the previously set NormalizeFunc of a function which -// does no translation, if not set previously. func (f *FlagSet) GetNormalizeFunc() func(f *FlagSet, name string) NormalizedName { if f.normalizeNameFunc != nil { return f.normalizeNameFunc @@ -256,78 +216,34 @@ func (f *FlagSet) SetOutput(output io.Writer) { f.output = output } -// VisitAll visits the flags in lexicographical order or -// in primordial order if f.SortFlags is false, calling fn for each. +// VisitAll visits the flags in lexicographical order, calling fn for each. // It visits all flags, even those not set. func (f *FlagSet) VisitAll(fn func(*Flag)) { - if len(f.formal) == 0 { - return - } - - var flags []*Flag - if f.SortFlags { - if len(f.formal) != len(f.sortedFormal) { - f.sortedFormal = sortFlags(f.formal) - } - flags = f.sortedFormal - } else { - flags = f.orderedFormal - } - - for _, flag := range flags { + for _, flag := range sortFlags(f.formal) { fn(flag) } } -// HasFlags returns a bool to indicate if the FlagSet has any flags defined. func (f *FlagSet) HasFlags() bool { return len(f.formal) > 0 } -// HasAvailableFlags returns a bool to indicate if the FlagSet has any flags -// that are not hidden. -func (f *FlagSet) HasAvailableFlags() bool { - for _, flag := range f.formal { - if !flag.Hidden { - return true - } - } - return false -} - -// VisitAll visits the command-line flags in lexicographical order or -// in primordial order if f.SortFlags is false, calling fn for each. -// It visits all flags, even those not set. +// VisitAll visits the command-line flags in lexicographical order, calling +// fn for each. It visits all flags, even those not set. func VisitAll(fn func(*Flag)) { CommandLine.VisitAll(fn) } -// Visit visits the flags in lexicographical order or -// in primordial order if f.SortFlags is false, calling fn for each. +// Visit visits the flags in lexicographical order, calling fn for each. // It visits only those flags that have been set. func (f *FlagSet) Visit(fn func(*Flag)) { - if len(f.actual) == 0 { - return - } - - var flags []*Flag - if f.SortFlags { - if len(f.actual) != len(f.sortedActual) { - f.sortedActual = sortFlags(f.actual) - } - flags = f.sortedActual - } else { - flags = f.orderedActual - } - - for _, flag := range flags { + for _, flag := range sortFlags(f.actual) { fn(flag) } } -// Visit visits the command-line flags in lexicographical order or -// in primordial order if f.SortFlags is false, calling fn for each. -// It visits only those flags that have been set. +// Visit visits the command-line flags in lexicographical order, calling fn +// for each. It visits only those flags that have been set. func Visit(fn func(*Flag)) { CommandLine.Visit(fn) } @@ -337,22 +253,6 @@ func (f *FlagSet) Lookup(name string) *Flag { return f.lookup(f.normalizeFlagName(name)) } -// ShorthandLookup returns the Flag structure of the short handed flag, -// returning nil if none exists. -// It panics, if len(name) > 1. -func (f *FlagSet) ShorthandLookup(name string) *Flag { - if name == "" { - return nil - } - if len(name) > 1 { - msg := fmt.Sprintf("can not look up shorthand which is more than one ASCII character: %q", name) - fmt.Fprintf(f.out(), msg) - panic(msg) - } - c := name[0] - return f.shorthands[c] -} - // lookup returns the Flag structure of the named flag, returning nil if none exists. func (f *FlagSet) lookup(name NormalizedName) *Flag { return f.formal[name] @@ -379,52 +279,13 @@ func (f *FlagSet) getFlagType(name string, ftype string, convFunc func(sval stri return result, nil } -// ArgsLenAtDash will return the length of f.Args at the moment when a -- was -// found during arg parsing. This allows your program to know which args were -// before the -- and which came after. -func (f *FlagSet) ArgsLenAtDash() int { - return f.argsLenAtDash -} - -// MarkDeprecated indicated that a flag is deprecated in your program. It will -// continue to function but will not show up in help or usage messages. Using -// this flag will also print the given usageMessage. +// Mark a flag deprecated in your program func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error { flag := f.Lookup(name) if flag == nil { return fmt.Errorf("flag %q does not exist", name) } - if usageMessage == "" { - return fmt.Errorf("deprecated message for flag %q must be set", name) - } flag.Deprecated = usageMessage - flag.Hidden = true - return nil -} - -// MarkShorthandDeprecated will mark the shorthand of a flag deprecated in your -// program. It will continue to function but will not show up in help or usage -// messages. Using this flag will also print the given usageMessage. -func (f *FlagSet) MarkShorthandDeprecated(name string, usageMessage string) error { - flag := f.Lookup(name) - if flag == nil { - return fmt.Errorf("flag %q does not exist", name) - } - if usageMessage == "" { - return fmt.Errorf("deprecated message for flag %q must be set", name) - } - flag.ShorthandDeprecated = usageMessage - return nil -} - -// MarkHidden sets a flag to 'hidden' in your program. It will continue to -// function but will not show up in help or usage messages. -func (f *FlagSet) MarkHidden(name string) error { - flag := f.Lookup(name) - if flag == nil { - return fmt.Errorf("flag %q does not exist", name) - } - flag.Hidden = true return nil } @@ -434,12 +295,6 @@ func Lookup(name string) *Flag { return CommandLine.Lookup(name) } -// ShorthandLookup returns the Flag structure of the short handed flag, -// returning nil if none exists. -func ShorthandLookup(name string) *Flag { - return CommandLine.ShorthandLookup(name) -} - // Set sets the value of the named flag. func (f *FlagSet) Set(name, value string) error { normalName := f.normalizeFlagName(name) @@ -447,37 +302,21 @@ func (f *FlagSet) Set(name, value string) error { if !ok { return fmt.Errorf("no such flag -%v", name) } - err := flag.Value.Set(value) if err != nil { - var flagName string - if flag.Shorthand != "" && flag.ShorthandDeprecated == "" { - flagName = fmt.Sprintf("-%s, --%s", flag.Shorthand, flag.Name) - } else { - flagName = fmt.Sprintf("--%s", flag.Name) - } - return fmt.Errorf("invalid argument %q for %q flag: %v", value, flagName, err) + return err } - - if !flag.Changed { - if f.actual == nil { - f.actual = make(map[NormalizedName]*Flag) - } - f.actual[normalName] = flag - f.orderedActual = append(f.orderedActual, flag) - - flag.Changed = true + if f.actual == nil { + f.actual = make(map[NormalizedName]*Flag) } - - if flag.Deprecated != "" { - fmt.Fprintf(f.out(), "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated) + f.actual[normalName] = flag + flag.Changed = true + if len(flag.Deprecated) > 0 { + fmt.Fprintf(os.Stderr, "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated) } return nil } -// SetAnnotation allows one to set arbitrary annotations on a flag in the FlagSet. -// This is sometimes used by spf13/cobra programs which want to generate additional -// bash completion information. func (f *FlagSet) SetAnnotation(name, key string, values []string) error { normalName := f.normalizeFlagName(name) flag, ok := f.formal[normalName] @@ -491,8 +330,6 @@ func (f *FlagSet) SetAnnotation(name, key string, values []string) error { return nil } -// Changed returns true if the flag was explicitly set during Parse() and false -// otherwise func (f *FlagSet) Changed(name string) bool { flag := f.Lookup(name) // If a flag doesn't exist, it wasn't changed.... @@ -510,233 +347,54 @@ func Set(name, value string) error { // PrintDefaults prints, to standard error unless configured // otherwise, the default values of all defined flags in the set. func (f *FlagSet) PrintDefaults() { - usages := f.FlagUsages() - fmt.Fprint(f.out(), usages) -} - -// defaultIsZeroValue returns true if the default value for this flag represents -// a zero value. -func (f *Flag) defaultIsZeroValue() bool { - switch f.Value.(type) { - case boolFlag: - return f.DefValue == "false" - case *durationValue: - // Beginning in Go 1.7, duration zero values are "0s" - return f.DefValue == "0" || f.DefValue == "0s" - case *intValue, *int8Value, *int32Value, *int64Value, *uintValue, *uint8Value, *uint16Value, *uint32Value, *uint64Value, *countValue, *float32Value, *float64Value: - return f.DefValue == "0" - case *stringValue: - return f.DefValue == "" - case *ipValue, *ipMaskValue, *ipNetValue: - return f.DefValue == "" - case *intSliceValue, *stringSliceValue, *stringArrayValue: - return f.DefValue == "[]" - default: - switch f.Value.String() { - case "false": - return true - case "": - return true - case "": - return true - case "0": - return true - } - return false - } -} - -// UnquoteUsage extracts a back-quoted name from the usage -// string for a flag and returns it and the un-quoted usage. -// Given "a `name` to show" it returns ("name", "a name to show"). -// If there are no back quotes, the name is an educated guess of the -// type of the flag's value, or the empty string if the flag is boolean. -func UnquoteUsage(flag *Flag) (name string, usage string) { - // Look for a back-quoted name, but avoid the strings package. - usage = flag.Usage - for i := 0; i < len(usage); i++ { - if usage[i] == '`' { - for j := i + 1; j < len(usage); j++ { - if usage[j] == '`' { - name = usage[i+1 : j] - usage = usage[:i] + name + usage[j+1:] - return name, usage - } - } - break // Only one back quote; use type name. - } - } - - name = flag.Value.Type() - switch name { - case "bool": - name = "" - case "float64": - name = "float" - case "int64": - name = "int" - case "uint64": - name = "uint" - case "stringSlice": - name = "strings" - case "intSlice": - name = "ints" - case "uintSlice": - name = "uints" - case "boolSlice": - name = "bools" - } - - return -} - -// Splits the string `s` on whitespace into an initial substring up to -// `i` runes in length and the remainder. Will go `slop` over `i` if -// that encompasses the entire string (which allows the caller to -// avoid short orphan words on the final line). -func wrapN(i, slop int, s string) (string, string) { - if i+slop > len(s) { - return s, "" - } - - w := strings.LastIndexAny(s[:i], " \t\n") - if w <= 0 { - return s, "" - } - nlPos := strings.LastIndex(s[:i], "\n") - if nlPos > 0 && nlPos < w { - return s[:nlPos], s[nlPos+1:] - } - return s[:w], s[w+1:] -} - -// Wraps the string `s` to a maximum width `w` with leading indent -// `i`. The first line is not indented (this is assumed to be done by -// caller). Pass `w` == 0 to do no wrapping -func wrap(i, w int, s string) string { - if w == 0 { - return strings.Replace(s, "\n", "\n"+strings.Repeat(" ", i), -1) - } - - // space between indent i and end of line width w into which - // we should wrap the text. - wrap := w - i - - var r, l string - - // Not enough space for sensible wrapping. Wrap as a block on - // the next line instead. - if wrap < 24 { - i = 16 - wrap = w - i - r += "\n" + strings.Repeat(" ", i) - } - // If still not enough space then don't even try to wrap. - if wrap < 24 { - return strings.Replace(s, "\n", r, -1) - } - - // Try to avoid short orphan words on the final line, by - // allowing wrapN to go a bit over if that would fit in the - // remainder of the line. - slop := 5 - wrap = wrap - slop - - // Handle first line, which is indented by the caller (or the - // special case above) - l, s = wrapN(wrap, slop, s) - r = r + strings.Replace(l, "\n", "\n"+strings.Repeat(" ", i), -1) - - // Now wrap the rest - for s != "" { - var t string - - t, s = wrapN(wrap, slop, s) - r = r + "\n" + strings.Repeat(" ", i) + strings.Replace(t, "\n", "\n"+strings.Repeat(" ", i), -1) - } - - return r - -} - -// FlagUsagesWrapped returns a string containing the usage information -// for all flags in the FlagSet. Wrapped to `cols` columns (0 for no -// wrapping) -func (f *FlagSet) FlagUsagesWrapped(cols int) string { - buf := new(bytes.Buffer) - - lines := make([]string, 0, len(f.formal)) - - maxlen := 0 f.VisitAll(func(flag *Flag) { - if flag.Hidden { + if len(flag.Deprecated) > 0 { return } - - line := "" - if flag.Shorthand != "" && flag.ShorthandDeprecated == "" { - line = fmt.Sprintf(" -%s, --%s", flag.Shorthand, flag.Name) + format := "" + // ex: w/ option string argument '-%s, --%s[=%q]: %s\n' + if len(flag.Shorthand) > 0 { + format = " -%s, --%s" } else { - line = fmt.Sprintf(" --%s", flag.Name) + format = " %s --%s" } - - varname, usage := UnquoteUsage(flag) - if varname != "" { - line += " " + varname + if len(flag.NoOptDefVal) > 0 { + format = format + "[" } - if flag.NoOptDefVal != "" { - switch flag.Value.Type() { - case "string": - line += fmt.Sprintf("[=\"%s\"]", flag.NoOptDefVal) - case "bool": - if flag.NoOptDefVal != "true" { - line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) - } - case "count": - if flag.NoOptDefVal != "+1" { - line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) - } - default: - line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) - } + if _, ok := flag.Value.(*stringValue); ok { + format = format + "=%q" + } else { + format = format + "=%s" } - - // This special character will be replaced with spacing once the - // correct alignment is calculated - line += "\x00" - if len(line) > maxlen { - maxlen = len(line) + if len(flag.NoOptDefVal) > 0 { + format = format + "]" } - - line += usage - if !flag.defaultIsZeroValue() { - if flag.Value.Type() == "string" { - line += fmt.Sprintf(" (default %q)", flag.DefValue) - } else { - line += fmt.Sprintf(" (default %s)", flag.DefValue) - } - } - if len(flag.Deprecated) != 0 { - line += fmt.Sprintf(" (DEPRECATED: %s)", flag.Deprecated) - } - - lines = append(lines, line) + format = format + ": %s\n" + fmt.Fprintf(f.out(), format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage) }) - - for _, line := range lines { - sidx := strings.Index(line, "\x00") - spacing := strings.Repeat(" ", maxlen-sidx) - // maxlen + 2 comes from + 1 for the \x00 and + 1 for the (deliberate) off-by-one in maxlen-sidx - fmt.Fprintln(buf, line[:sidx], spacing, wrap(maxlen+2, cols, line[sidx+1:])) - } - - return buf.String() } -// FlagUsages returns a string containing the usage information for all flags in -// the FlagSet func (f *FlagSet) FlagUsages() string { - return f.FlagUsagesWrapped(0) + x := new(bytes.Buffer) + + f.VisitAll(func(flag *Flag) { + if len(flag.Deprecated) > 0 { + return + } + format := "--%s=%s: %s\n" + if _, ok := flag.Value.(*stringValue); ok { + // put quotes on the value + format = "--%s=%q: %s\n" + } + if len(flag.Shorthand) > 0 { + format = " -%s, " + format + } else { + format = " %s " + format + } + fmt.Fprintf(x, format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage) + }) + + return x.String() } // PrintDefaults prints to standard error the default values of all defined command-line flags. @@ -756,8 +414,6 @@ func defaultUsage(f *FlagSet) { // Usage prints to standard error a usage message documenting all defined command-line flags. // The function is a variable that may be changed to point to a custom function. -// By default it prints a simple header and calls PrintDefaults; for details about the -// format of the output and how to control it, see the documentation for PrintDefaults. var Usage = func() { fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) PrintDefaults() @@ -806,7 +462,7 @@ func (f *FlagSet) Var(value Value, name string, usage string) { f.VarP(value, name, "", usage) } -// VarPF is like VarP, but returns the flag created +// Like VarP, but returns the flag created func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag { // Remember the default value as a string; it won't change. flag := &Flag{ @@ -820,17 +476,17 @@ func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag { return flag } -// VarP is like Var, but accepts a shorthand letter that can be used after a single dash. +// Like Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) VarP(value Value, name, shorthand, usage string) { - f.VarPF(value, name, shorthand, usage) + _ = f.VarPF(value, name, shorthand, usage) } -// AddFlag will add the flag to the FlagSet func (f *FlagSet) AddFlag(flag *Flag) { - normalizedFlagName := f.normalizeFlagName(flag.Name) + // Call normalizeFlagName function only once + var normalizedFlagName NormalizedName = f.normalizeFlagName(flag.Name) - _, alreadyThere := f.formal[normalizedFlagName] - if alreadyThere { + _, alreadythere := f.formal[normalizedFlagName] + if alreadythere { msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name) fmt.Fprintln(f.out(), msg) panic(msg) // Happens only if flags are declared with identical names @@ -841,42 +497,26 @@ func (f *FlagSet) AddFlag(flag *Flag) { flag.Name = string(normalizedFlagName) f.formal[normalizedFlagName] = flag - f.orderedFormal = append(f.orderedFormal, flag) - if flag.Shorthand == "" { + if len(flag.Shorthand) == 0 { return } if len(flag.Shorthand) > 1 { - msg := fmt.Sprintf("%q shorthand is more than one ASCII character", flag.Shorthand) - fmt.Fprintf(f.out(), msg) - panic(msg) + fmt.Fprintf(f.out(), "%s shorthand more than ASCII character: %s\n", f.name, flag.Shorthand) + panic("shorthand is more than one character") } if f.shorthands == nil { f.shorthands = make(map[byte]*Flag) } c := flag.Shorthand[0] - used, alreadyThere := f.shorthands[c] - if alreadyThere { - msg := fmt.Sprintf("unable to redefine %q shorthand in %q flagset: it's already used for %q flag", c, f.name, used.Name) - fmt.Fprintf(f.out(), msg) - panic(msg) + old, alreadythere := f.shorthands[c] + if alreadythere { + fmt.Fprintf(f.out(), "%s shorthand reused: %q for %s already used for %s\n", f.name, c, flag.Name, old.Name) + panic("shorthand redefinition") } f.shorthands[c] = flag } -// AddFlagSet adds one FlagSet to another. If a flag is already present in f -// the flag from newSet will be ignored. -func (f *FlagSet) AddFlagSet(newSet *FlagSet) { - if newSet == nil { - return - } - newSet.VisitAll(func(flag *Flag) { - if f.Lookup(flag.Name) == nil { - f.AddFlag(flag) - } - }) -} - // Var defines a flag with the specified name and usage string. The type and // value of the flag are represented by the first argument, of type Value, which // typically holds a user-defined implementation of Value. For instance, the @@ -887,7 +527,7 @@ func Var(value Value, name string, usage string) { CommandLine.VarP(value, name, "", usage) } -// VarP is like Var, but accepts a shorthand letter that can be used after a single dash. +// Like Var, but accepts a shorthand letter that can be used after a single dash. func VarP(value Value, name, shorthand, usage string) { CommandLine.VarP(value, name, shorthand, usage) } @@ -896,10 +536,8 @@ func VarP(value Value, name, shorthand, usage string) { // returns the error. func (f *FlagSet) failf(format string, a ...interface{}) error { err := fmt.Errorf(format, a...) - if f.errorHandling != ContinueOnError { - fmt.Fprintln(f.out(), err) - f.usage() - } + fmt.Fprintln(f.out(), err) + f.usage() return err } @@ -915,61 +553,45 @@ func (f *FlagSet) usage() { } } -//--unknown (args will be empty) -//--unknown --next-flag ... (args will be --next-flag ...) -//--unknown arg ... (args will be arg ...) -func stripUnknownFlagValue(args []string) []string { - if len(args) == 0 { - //--unknown - return args +func (f *FlagSet) setFlag(flag *Flag, value string, origArg string) error { + if err := flag.Value.Set(value); err != nil { + return f.failf("invalid argument %q for %s: %v", value, origArg, err) } - - first := args[0] - if first[0] == '-' { - //--unknown --next-flag ... - return args + // mark as visited for Visit() + if f.actual == nil { + f.actual = make(map[NormalizedName]*Flag) } - - //--unknown arg ... (args will be arg ...) - return args[1:] + f.actual[f.normalizeFlagName(flag.Name)] = flag + flag.Changed = true + if len(flag.Deprecated) > 0 { + fmt.Fprintf(os.Stderr, "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated) + } + return nil } -func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) { +func (f *FlagSet) parseLongArg(s string, args []string) (a []string, err error) { a = args name := s[2:] if len(name) == 0 || name[0] == '-' || name[0] == '=' { err = f.failf("bad flag syntax: %s", s) return } - split := strings.SplitN(name, "=", 2) name = split[0] - flag, exists := f.formal[f.normalizeFlagName(name)] - - if !exists { - switch { - case name == "help": + flag, alreadythere := f.formal[f.normalizeFlagName(name)] + if !alreadythere { + if name == "help" { // special case for nice help message. f.usage() return a, ErrHelp - case f.ParseErrorsWhitelist.UnknownFlags: - // --unknown=unknownval arg ... - // we do not want to lose arg in this case - if len(split) >= 2 { - return a, nil - } - - return stripUnknownFlagValue(a), nil - default: - err = f.failf("unknown flag: --%s", name) - return } + err = f.failf("unknown flag: --%s", name) + return } - var value string if len(split) == 2 { // '--flag=arg' value = split[1] - } else if flag.NoOptDefVal != "" { + } else if len(flag.NoOptDefVal) > 0 { // '--flag' (arg was optional) value = flag.NoOptDefVal } else if len(a) > 0 { @@ -981,86 +603,52 @@ func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []strin err = f.failf("flag needs an argument: %s", s) return } - - err = fn(flag, value) - if err != nil { - f.failf(err.Error()) - } + err = f.setFlag(flag, value, s) return } -func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) { - if strings.HasPrefix(shorthands, "test.") { - return - } - +func (f *FlagSet) parseSingleShortArg(shorthands string, args []string) (outShorts string, outArgs []string, err error) { outArgs = args outShorts = shorthands[1:] c := shorthands[0] - flag, exists := f.shorthands[c] - if !exists { - switch { - case c == 'h': + flag, alreadythere := f.shorthands[c] + if !alreadythere { + if c == 'h' { // special case for nice help message. f.usage() err = ErrHelp return - case f.ParseErrorsWhitelist.UnknownFlags: - // '-f=arg arg ...' - // we do not want to lose arg in this case - if len(shorthands) > 2 && shorthands[1] == '=' { - outShorts = "" - return - } - - outArgs = stripUnknownFlagValue(outArgs) - return - default: - err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands) - return } + //TODO continue on error + err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands) + return } - var value string if len(shorthands) > 2 && shorthands[1] == '=' { - // '-f=arg' value = shorthands[2:] outShorts = "" - } else if flag.NoOptDefVal != "" { - // '-f' (arg was optional) + } else if len(flag.NoOptDefVal) > 0 { value = flag.NoOptDefVal } else if len(shorthands) > 1 { - // '-farg' value = shorthands[1:] outShorts = "" } else if len(args) > 0 { - // '-f arg' value = args[0] outArgs = args[1:] } else { - // '-f' (arg was required) err = f.failf("flag needs an argument: %q in -%s", c, shorthands) return } - - if flag.ShorthandDeprecated != "" { - fmt.Fprintf(f.out(), "Flag shorthand -%s has been deprecated, %s\n", flag.Shorthand, flag.ShorthandDeprecated) - } - - err = fn(flag, value) - if err != nil { - f.failf(err.Error()) - } + err = f.setFlag(flag, value, shorthands) return } -func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []string, err error) { +func (f *FlagSet) parseShortArg(s string, args []string) (a []string, err error) { a = args shorthands := s[1:] - // "shorthands" can be a series of shorthand letters of flags (e.g. "-vvv"). for len(shorthands) > 0 { - shorthands, a, err = f.parseSingleShortArg(shorthands, args, fn) + shorthands, a, err = f.parseSingleShortArg(shorthands, args) if err != nil { return } @@ -1069,7 +657,7 @@ func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []stri return } -func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) { +func (f *FlagSet) parseArgs(args []string) (err error) { for len(args) > 0 { s := args[0] args = args[1:] @@ -1085,13 +673,12 @@ func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) { if s[1] == '-' { if len(s) == 2 { // "--" terminates the flags - f.argsLenAtDash = len(f.args) f.args = append(f.args, args...) break } - args, err = f.parseLongArg(s, args, fn) + args, err = f.parseLongArg(s, args) } else { - args, err = f.parseShortArg(s, args, fn) + args, err = f.parseShortArg(s, args) } if err != nil { return @@ -1105,50 +692,9 @@ func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) { // are defined and before flags are accessed by the program. // The return value will be ErrHelp if -help was set but not defined. func (f *FlagSet) Parse(arguments []string) error { - if f.addedGoFlagSets != nil { - for _, goFlagSet := range f.addedGoFlagSets { - goFlagSet.Parse(nil) - } - } - f.parsed = true - - if len(arguments) < 0 { - return nil - } - - f.args = make([]string, 0, len(arguments)) - - set := func(flag *Flag, value string) error { - return f.Set(flag.Name, value) - } - - err := f.parseArgs(arguments, set) - if err != nil { - switch f.errorHandling { - case ContinueOnError: - return err - case ExitOnError: - fmt.Println(err) - os.Exit(2) - case PanicOnError: - panic(err) - } - } - return nil -} - -type parseFunc func(flag *Flag, value string) error - -// ParseAll parses flag definitions from the argument list, which should not -// include the command name. The arguments for fn are flag and value. Must be -// called after all flags in the FlagSet are defined and before flags are -// accessed by the program. The return value will be ErrHelp if -help was set -// but not defined. -func (f *FlagSet) ParseAll(arguments []string, fn func(flag *Flag, value string) error) error { f.parsed = true f.args = make([]string, 0, len(arguments)) - - err := f.parseArgs(arguments, fn) + err := f.parseArgs(arguments) if err != nil { switch f.errorHandling { case ContinueOnError: @@ -1174,15 +720,7 @@ func Parse() { CommandLine.Parse(os.Args[1:]) } -// ParseAll parses the command-line flags from os.Args[1:] and called fn for each. -// The arguments for fn are flag and value. Must be called after all flags are -// defined and before flags are accessed by the program. -func ParseAll(fn func(flag *Flag, value string) error) { - // Ignore errors; CommandLine is set for ExitOnError. - CommandLine.ParseAll(os.Args[1:], fn) -} - -// SetInterspersed sets whether to support interspersed option/non-option arguments. +// Whether to support interspersed option/non-option arguments. func SetInterspersed(interspersed bool) { CommandLine.SetInterspersed(interspersed) } @@ -1192,23 +730,21 @@ func Parsed() bool { return CommandLine.Parsed() } -// CommandLine is the default set of command-line flags, parsed from os.Args. +// The default set of command-line flags, parsed from os.Args. var CommandLine = NewFlagSet(os.Args[0], ExitOnError) -// NewFlagSet returns a new, empty flag set with the specified name, -// error handling property and SortFlags set to true. +// NewFlagSet returns a new, empty flag set with the specified name and +// error handling property. func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet { f := &FlagSet{ name: name, errorHandling: errorHandling, - argsLenAtDash: -1, interspersed: true, - SortFlags: true, } return f } -// SetInterspersed sets whether to support interspersed option/non-option arguments. +// Whether to support interspersed option/non-option arguments. func (f *FlagSet) SetInterspersed(interspersed bool) { f.interspersed = interspersed } @@ -1219,5 +755,4 @@ func (f *FlagSet) SetInterspersed(interspersed bool) { func (f *FlagSet) Init(name string, errorHandling ErrorHandling) { f.name = name f.errorHandling = errorHandling - f.argsLenAtDash = -1 } diff --git a/vendor/github.com/spf13/pflag/flag_test.go b/vendor/github.com/spf13/pflag/flag_test.go index f600f0ae..e654553c 100644 --- a/vendor/github.com/spf13/pflag/flag_test.go +++ b/vendor/github.com/spf13/pflag/flag_test.go @@ -13,22 +13,21 @@ import ( "os" "reflect" "sort" - "strconv" "strings" "testing" "time" ) var ( - testBool = Bool("test_bool", false, "bool value") - testInt = Int("test_int", 0, "int value") - testInt64 = Int64("test_int64", 0, "int64 value") - testUint = Uint("test_uint", 0, "uint value") - testUint64 = Uint64("test_uint64", 0, "uint64 value") - testString = String("test_string", "0", "string value") - testFloat = Float64("test_float64", 0, "float64 value") - testDuration = Duration("test_duration", 0, "time.Duration value") - testOptionalInt = Int("test_optional_int", 0, "optional int value") + test_bool = Bool("test_bool", false, "bool value") + test_int = Int("test_int", 0, "int value") + test_int64 = Int64("test_int64", 0, "int64 value") + test_uint = Uint("test_uint", 0, "uint value") + test_uint64 = Uint64("test_uint64", 0, "uint64 value") + test_string = String("test_string", "0", "string value") + test_float64 = Float64("test_float64", 0, "float64 value") + test_duration = Duration("test_duration", 0, "time.Duration value") + test_optional_int = Int("test_optional_int", 0, "optional int value") normalizeFlagNameInvocations = 0 ) @@ -106,25 +105,8 @@ func TestUsage(t *testing.T) { if GetCommandLine().Parse([]string{"--x"}) == nil { t.Error("parse did not fail for unknown flag") } - if called { - t.Error("did call Usage while using ContinueOnError") - } -} - -func TestAddFlagSet(t *testing.T) { - oldSet := NewFlagSet("old", ContinueOnError) - newSet := NewFlagSet("new", ContinueOnError) - - oldSet.String("flag1", "flag1", "flag1") - oldSet.String("flag2", "flag2", "flag2") - - newSet.String("flag2", "flag2", "flag2") - newSet.String("flag3", "flag3", "flag3") - - oldSet.AddFlagSet(newSet) - - if len(oldSet.formal) != 3 { - t.Errorf("Unexpected result adding a FlagSet to a FlagSet %v", oldSet) + if !called { + t.Error("did not call Usage for unknown flag") } } @@ -168,7 +150,6 @@ func testParse(f *FlagSet, t *testing.T) { bool3Flag := f.Bool("bool3", false, "bool3 value") intFlag := f.Int("int", 0, "int value") int8Flag := f.Int8("int8", 0, "int value") - int16Flag := f.Int16("int16", 0, "int value") int32Flag := f.Int32("int32", 0, "int value") int64Flag := f.Int64("int64", 0, "int64 value") uintFlag := f.Uint("uint", 0, "uint value") @@ -193,7 +174,6 @@ func testParse(f *FlagSet, t *testing.T) { "--bool3=false", "--int=22", "--int8=-8", - "--int16=-16", "--int32=-32", "--int64=0x23", "--uint", "24", @@ -238,15 +218,9 @@ func testParse(f *FlagSet, t *testing.T) { if *int8Flag != -8 { t.Error("int8 flag should be 0x23, is ", *int8Flag) } - if *int16Flag != -16 { - t.Error("int16 flag should be -16, is ", *int16Flag) - } if v, err := f.GetInt8("int8"); err != nil || v != *int8Flag { t.Error("GetInt8 does not work.") } - if v, err := f.GetInt16("int16"); err != nil || v != *int16Flag { - t.Error("GetInt16 does not work.") - } if *int32Flag != -32 { t.Error("int32 flag should be 0x23, is ", *int32Flag) } @@ -317,7 +291,7 @@ func testParse(f *FlagSet, t *testing.T) { t.Error("mask flag should be 255.255.255.0, is ", (*maskFlag).String()) } if v, err := f.GetIPv4Mask("mask"); err != nil || v.String() != (*maskFlag).String() { - t.Errorf("GetIP returned %v maskFlag was %v error was %v", v, *maskFlag, err) + t.Errorf("GetIP returned %v but maskFlag was %v", v, *maskFlag, err) } if *durationFlag != 2*time.Minute { t.Error("duration flag should be 2m, is ", *durationFlag) @@ -341,130 +315,6 @@ func testParse(f *FlagSet, t *testing.T) { } } -func testParseAll(f *FlagSet, t *testing.T) { - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - f.BoolP("boola", "a", false, "bool value") - f.BoolP("boolb", "b", false, "bool2 value") - f.BoolP("boolc", "c", false, "bool3 value") - f.BoolP("boold", "d", false, "bool4 value") - f.StringP("stringa", "s", "0", "string value") - f.StringP("stringz", "z", "0", "string value") - f.StringP("stringx", "x", "0", "string value") - f.StringP("stringy", "y", "0", "string value") - f.Lookup("stringx").NoOptDefVal = "1" - args := []string{ - "-ab", - "-cs=xx", - "--stringz=something", - "-d=true", - "-x", - "-y", - "ee", - } - want := []string{ - "boola", "true", - "boolb", "true", - "boolc", "true", - "stringa", "xx", - "stringz", "something", - "boold", "true", - "stringx", "1", - "stringy", "ee", - } - got := []string{} - store := func(flag *Flag, value string) error { - got = append(got, flag.Name) - if len(value) > 0 { - got = append(got, value) - } - return nil - } - if err := f.ParseAll(args, store); err != nil { - t.Errorf("expected no error, got %s", err) - } - if !f.Parsed() { - t.Errorf("f.Parse() = false after Parse") - } - if !reflect.DeepEqual(got, want) { - t.Errorf("f.ParseAll() fail to restore the args") - t.Errorf("Got: %v", got) - t.Errorf("Want: %v", want) - } -} - -func testParseWithUnknownFlags(f *FlagSet, t *testing.T) { - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - f.ParseErrorsWhitelist.UnknownFlags = true - - f.BoolP("boola", "a", false, "bool value") - f.BoolP("boolb", "b", false, "bool2 value") - f.BoolP("boolc", "c", false, "bool3 value") - f.BoolP("boold", "d", false, "bool4 value") - f.BoolP("boole", "e", false, "bool4 value") - f.StringP("stringa", "s", "0", "string value") - f.StringP("stringz", "z", "0", "string value") - f.StringP("stringx", "x", "0", "string value") - f.StringP("stringy", "y", "0", "string value") - f.StringP("stringo", "o", "0", "string value") - f.Lookup("stringx").NoOptDefVal = "1" - args := []string{ - "-ab", - "-cs=xx", - "--stringz=something", - "--unknown1", - "unknown1Value", - "-d=true", - "-x", - "--unknown2=unknown2Value", - "-u=unknown3Value", - "-p", - "unknown4Value", - "-q", //another unknown with bool value - "-y", - "ee", - "--unknown7=unknown7value", - "--stringo=ovalue", - "--unknown8=unknown8value", - "--boole", - "--unknown6", - } - want := []string{ - "boola", "true", - "boolb", "true", - "boolc", "true", - "stringa", "xx", - "stringz", "something", - "boold", "true", - "stringx", "1", - "stringy", "ee", - "stringo", "ovalue", - "boole", "true", - } - got := []string{} - store := func(flag *Flag, value string) error { - got = append(got, flag.Name) - if len(value) > 0 { - got = append(got, value) - } - return nil - } - if err := f.ParseAll(args, store); err != nil { - t.Errorf("expected no error, got %s", err) - } - if !f.Parsed() { - t.Errorf("f.Parse() = false after Parse") - } - if !reflect.DeepEqual(got, want) { - t.Errorf("f.ParseAll() fail to restore the args") - t.Errorf("Got: %v", got) - t.Errorf("Want: %v", want) - } -} - func TestShorthand(t *testing.T) { f := NewFlagSet("shorthand", ContinueOnError) if f.Parsed() { @@ -520,45 +370,6 @@ func TestShorthand(t *testing.T) { } else if f.Args()[1] != notaflag { t.Errorf("expected argument %q got %q", notaflag, f.Args()[1]) } - if f.ArgsLenAtDash() != 1 { - t.Errorf("expected argsLenAtDash %d got %d", f.ArgsLenAtDash(), 1) - } -} - -func TestShorthandLookup(t *testing.T) { - f := NewFlagSet("shorthand", ContinueOnError) - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - f.BoolP("boola", "a", false, "bool value") - f.BoolP("boolb", "b", false, "bool2 value") - args := []string{ - "-ab", - } - f.SetOutput(ioutil.Discard) - if err := f.Parse(args); err != nil { - t.Error("expected no error, got ", err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - flag := f.ShorthandLookup("a") - if flag == nil { - t.Errorf("f.ShorthandLookup(\"a\") returned nil") - } - if flag.Name != "boola" { - t.Errorf("f.ShorthandLookup(\"a\") found %q instead of \"boola\"", flag.Name) - } - flag = f.ShorthandLookup("") - if flag != nil { - t.Errorf("f.ShorthandLookup(\"\") did not return nil") - } - defer func() { - recover() - }() - flag = f.ShorthandLookup("ab") - // should NEVER get here. lookup should panic. defer'd func should recover it. - t.Errorf("f.ShorthandLookup(\"ab\") did not panic") } func TestParse(t *testing.T) { @@ -566,26 +377,16 @@ func TestParse(t *testing.T) { testParse(GetCommandLine(), t) } -func TestParseAll(t *testing.T) { - ResetForTesting(func() { t.Error("bad parse") }) - testParseAll(GetCommandLine(), t) -} - -func TestIgnoreUnknownFlags(t *testing.T) { - ResetForTesting(func() { t.Error("bad parse") }) - testParseWithUnknownFlags(GetCommandLine(), t) -} - func TestFlagSetParse(t *testing.T) { testParse(NewFlagSet("test", ContinueOnError), t) } func TestChangedHelper(t *testing.T) { f := NewFlagSet("changedtest", ContinueOnError) - f.Bool("changed", false, "changed bool") - f.Bool("settrue", true, "true to true") - f.Bool("setfalse", false, "false to false") - f.Bool("unchanged", false, "unchanged bool") + _ = f.Bool("changed", false, "changed bool") + _ = f.Bool("settrue", true, "true to true") + _ = f.Bool("setfalse", false, "false to false") + _ = f.Bool("unchanged", false, "unchanged bool") args := []string{"--changed", "--settrue", "--setfalse=false"} if err := f.Parse(args); err != nil { @@ -606,9 +407,6 @@ func TestChangedHelper(t *testing.T) { if f.Changed("invalid") { t.Errorf("--invalid was changed!") } - if f.ArgsLenAtDash() != -1 { - t.Errorf("Expected argsLenAtDash: %d but got %d", -1, f.ArgsLenAtDash()) - } } func replaceSeparators(name string, from []string, to string) string { @@ -688,6 +486,7 @@ func aliasAndWordSepFlagNames(f *FlagSet, name string) NormalizedName { switch name { case oldName: name = newName + break } return NormalizedName(name) @@ -741,70 +540,6 @@ func TestNormalizationFuncShouldChangeFlagName(t *testing.T) { } } -// Related to https://github.com/spf13/cobra/issues/521. -func TestNormalizationSharedFlags(t *testing.T) { - f := NewFlagSet("set f", ContinueOnError) - g := NewFlagSet("set g", ContinueOnError) - nfunc := wordSepNormalizeFunc - testName := "valid_flag" - normName := nfunc(nil, testName) - if testName == string(normName) { - t.Error("TestNormalizationSharedFlags meaningless: the original and normalized flag names are identical:", testName) - } - - f.Bool(testName, false, "bool value") - g.AddFlagSet(f) - - f.SetNormalizeFunc(nfunc) - g.SetNormalizeFunc(nfunc) - - if len(f.formal) != 1 { - t.Error("Normalizing flags should not result in duplications in the flag set:", f.formal) - } - if f.orderedFormal[0].Name != string(normName) { - t.Error("Flag name not normalized") - } - for k := range f.formal { - if k != "valid.flag" { - t.Errorf("The key in the flag map should have been normalized: wanted \"%s\", got \"%s\" instead", normName, k) - } - } - - if !reflect.DeepEqual(f.formal, g.formal) || !reflect.DeepEqual(f.orderedFormal, g.orderedFormal) { - t.Error("Two flag sets sharing the same flags should stay consistent after being normalized. Original set:", f.formal, "Duplicate set:", g.formal) - } -} - -func TestNormalizationSetFlags(t *testing.T) { - f := NewFlagSet("normalized", ContinueOnError) - nfunc := wordSepNormalizeFunc - testName := "valid_flag" - normName := nfunc(nil, testName) - if testName == string(normName) { - t.Error("TestNormalizationSetFlags meaningless: the original and normalized flag names are identical:", testName) - } - - f.Bool(testName, false, "bool value") - f.Set(testName, "true") - f.SetNormalizeFunc(nfunc) - - if len(f.formal) != 1 { - t.Error("Normalizing flags should not result in duplications in the flag set:", f.formal) - } - if f.orderedFormal[0].Name != string(normName) { - t.Error("Flag name not normalized") - } - for k := range f.formal { - if k != "valid.flag" { - t.Errorf("The key in the flag map should have been normalized: wanted \"%s\", got \"%s\" instead", normName, k) - } - } - - if !reflect.DeepEqual(f.formal, f.actual) { - t.Error("The map of set flags should get normalized. Formal:", f.formal, "Actual:", f.actual) - } -} - // Declare a user-defined flag type. type flagVar []string @@ -961,19 +696,12 @@ func TestTermination(t *testing.T) { if f.Args()[1] != arg2 { t.Errorf("expected argument %q got %q", arg2, f.Args()[1]) } - if f.ArgsLenAtDash() != 0 { - t.Errorf("expected argsLenAtDash %d got %d", 0, f.ArgsLenAtDash()) - } } -func getDeprecatedFlagSet() *FlagSet { +func TestDeprecatedFlagInDocs(t *testing.T) { f := NewFlagSet("bob", ContinueOnError) f.Bool("badflag", true, "always true") f.MarkDeprecated("badflag", "use --good-flag instead") - return f -} -func TestDeprecatedFlagInDocs(t *testing.T) { - f := getDeprecatedFlagSet() out := new(bytes.Buffer) f.SetOutput(out) @@ -984,42 +712,6 @@ func TestDeprecatedFlagInDocs(t *testing.T) { } } -func TestUnHiddenDeprecatedFlagInDocs(t *testing.T) { - f := getDeprecatedFlagSet() - flg := f.Lookup("badflag") - if flg == nil { - t.Fatalf("Unable to lookup 'bob' in TestUnHiddenDeprecatedFlagInDocs") - } - flg.Hidden = false - - out := new(bytes.Buffer) - f.SetOutput(out) - f.PrintDefaults() - - defaults := out.String() - if !strings.Contains(defaults, "badflag") { - t.Errorf("Did not find deprecated flag in usage!") - } - if !strings.Contains(defaults, "use --good-flag instead") { - t.Errorf("Did not find 'use --good-flag instead' in defaults") - } -} - -func TestDeprecatedFlagShorthandInDocs(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - name := "noshorthandflag" - f.BoolP(name, "n", true, "always true") - f.MarkShorthandDeprecated("noshorthandflag", fmt.Sprintf("use --%s instead", name)) - - out := new(bytes.Buffer) - f.SetOutput(out) - f.PrintDefaults() - - if strings.Contains(out.String(), "-n,") { - t.Errorf("found deprecated flag shorthand in usage!") - } -} - func parseReturnStderr(t *testing.T, f *FlagSet, args []string) (string, error) { oldStderr := os.Stderr r, w, _ := os.Pipe() @@ -1059,24 +751,6 @@ func TestDeprecatedFlagUsage(t *testing.T) { } } -func TestDeprecatedFlagShorthandUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - name := "noshorthandflag" - f.BoolP(name, "n", true, "always true") - usageMsg := fmt.Sprintf("use --%s instead", name) - f.MarkShorthandDeprecated(name, usageMsg) - - args := []string{"-n"} - out, err := parseReturnStderr(t, f, args) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - if !strings.Contains(out, usageMsg) { - t.Errorf("usageMsg not printed when using a deprecated flag!") - } -} - func TestDeprecatedFlagUsageNormalized(t *testing.T) { f := NewFlagSet("bob", ContinueOnError) f.Bool("bad-double_flag", true, "always true") @@ -1107,153 +781,3 @@ func TestMultipleNormalizeFlagNameInvocations(t *testing.T) { t.Fatal("Expected normalizeFlagNameInvocations to be 1; got ", normalizeFlagNameInvocations) } } - -// -func TestHiddenFlagInUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("secretFlag", true, "shhh") - f.MarkHidden("secretFlag") - - out := new(bytes.Buffer) - f.SetOutput(out) - f.PrintDefaults() - - if strings.Contains(out.String(), "secretFlag") { - t.Errorf("found hidden flag in usage!") - } -} - -// -func TestHiddenFlagUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("secretFlag", true, "shhh") - f.MarkHidden("secretFlag") - - args := []string{"--secretFlag"} - out, err := parseReturnStderr(t, f, args) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - if strings.Contains(out, "shhh") { - t.Errorf("usage message printed when using a hidden flag!") - } -} - -const defaultOutput = ` --A for bootstrapping, allow 'any' type - --Alongflagname disable bounds checking - -C, --CCC a boolean defaulting to true (default true) - --D path set relative path for local imports - -E, --EEE num[=1234] a num with NoOptDefVal (default 4321) - --F number a non-zero number (default 2.7) - --G float a float that defaults to zero - --IP ip IP address with no default - --IPMask ipMask Netmask address with no default - --IPNet ipNet IP network with no default - --Ints ints int slice with zero default - --N int a non-zero int (default 27) - --ND1 string[="bar"] a string with NoOptDefVal (default "foo") - --ND2 num[=4321] a num with NoOptDefVal (default 1234) - --StringArray stringArray string array with zero default - --StringSlice strings string slice with zero default - --Z int an int that defaults to zero - --custom custom custom Value implementation - --customP custom a VarP with default (default 10) - --maxT timeout set timeout for dial - -v, --verbose count verbosity -` - -// Custom value that satisfies the Value interface. -type customValue int - -func (cv *customValue) String() string { return fmt.Sprintf("%v", *cv) } - -func (cv *customValue) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 64) - *cv = customValue(v) - return err -} - -func (cv *customValue) Type() string { return "custom" } - -func TestPrintDefaults(t *testing.T) { - fs := NewFlagSet("print defaults test", ContinueOnError) - var buf bytes.Buffer - fs.SetOutput(&buf) - fs.Bool("A", false, "for bootstrapping, allow 'any' type") - fs.Bool("Alongflagname", false, "disable bounds checking") - fs.BoolP("CCC", "C", true, "a boolean defaulting to true") - fs.String("D", "", "set relative `path` for local imports") - fs.Float64("F", 2.7, "a non-zero `number`") - fs.Float64("G", 0, "a float that defaults to zero") - fs.Int("N", 27, "a non-zero int") - fs.IntSlice("Ints", []int{}, "int slice with zero default") - fs.IP("IP", nil, "IP address with no default") - fs.IPMask("IPMask", nil, "Netmask address with no default") - fs.IPNet("IPNet", net.IPNet{}, "IP network with no default") - fs.Int("Z", 0, "an int that defaults to zero") - fs.Duration("maxT", 0, "set `timeout` for dial") - fs.String("ND1", "foo", "a string with NoOptDefVal") - fs.Lookup("ND1").NoOptDefVal = "bar" - fs.Int("ND2", 1234, "a `num` with NoOptDefVal") - fs.Lookup("ND2").NoOptDefVal = "4321" - fs.IntP("EEE", "E", 4321, "a `num` with NoOptDefVal") - fs.ShorthandLookup("E").NoOptDefVal = "1234" - fs.StringSlice("StringSlice", []string{}, "string slice with zero default") - fs.StringArray("StringArray", []string{}, "string array with zero default") - fs.CountP("verbose", "v", "verbosity") - - var cv customValue - fs.Var(&cv, "custom", "custom Value implementation") - - cv2 := customValue(10) - fs.VarP(&cv2, "customP", "", "a VarP with default") - - fs.PrintDefaults() - got := buf.String() - if got != defaultOutput { - fmt.Println("\n" + got) - fmt.Println("\n" + defaultOutput) - t.Errorf("got %q want %q\n", got, defaultOutput) - } -} - -func TestVisitAllFlagOrder(t *testing.T) { - fs := NewFlagSet("TestVisitAllFlagOrder", ContinueOnError) - fs.SortFlags = false - // https://github.com/spf13/pflag/issues/120 - fs.SetNormalizeFunc(func(f *FlagSet, name string) NormalizedName { - return NormalizedName(name) - }) - - names := []string{"C", "B", "A", "D"} - for _, name := range names { - fs.Bool(name, false, "") - } - - i := 0 - fs.VisitAll(func(f *Flag) { - if names[i] != f.Name { - t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name) - } - i++ - }) -} - -func TestVisitFlagOrder(t *testing.T) { - fs := NewFlagSet("TestVisitFlagOrder", ContinueOnError) - fs.SortFlags = false - names := []string{"C", "B", "A", "D"} - for _, name := range names { - fs.Bool(name, false, "") - fs.Set(name, "true") - } - - i := 0 - fs.Visit(func(f *Flag) { - if names[i] != f.Name { - t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name) - } - i++ - }) -} diff --git a/vendor/github.com/spf13/pflag/float32.go b/vendor/github.com/spf13/pflag/float32.go index a243f81f..30174cb2 100644 --- a/vendor/github.com/spf13/pflag/float32.go +++ b/vendor/github.com/spf13/pflag/float32.go @@ -1,6 +1,9 @@ package pflag -import "strconv" +import ( + "fmt" + "strconv" +) // -- float32 Value type float32Value float32 @@ -20,7 +23,7 @@ func (f *float32Value) Type() string { return "float32" } -func (f *float32Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 32) } +func (f *float32Value) String() string { return fmt.Sprintf("%v", *f) } func float32Conv(sval string) (interface{}, error) { v, err := strconv.ParseFloat(sval, 32) @@ -45,7 +48,7 @@ func (f *FlagSet) Float32Var(p *float32, name string, value float32, usage strin f.VarP(newFloat32Value(value, p), name, "", usage) } -// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash. +// Like Float32Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Float32VarP(p *float32, name, shorthand string, value float32, usage string) { f.VarP(newFloat32Value(value, p), name, shorthand, usage) } @@ -56,7 +59,7 @@ func Float32Var(p *float32, name string, value float32, usage string) { CommandLine.VarP(newFloat32Value(value, p), name, "", usage) } -// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash. +// Like Float32Var, but accepts a shorthand letter that can be used after a single dash. func Float32VarP(p *float32, name, shorthand string, value float32, usage string) { CommandLine.VarP(newFloat32Value(value, p), name, shorthand, usage) } @@ -69,7 +72,7 @@ func (f *FlagSet) Float32(name string, value float32, usage string) *float32 { return p } -// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash. +// Like Float32, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Float32P(name, shorthand string, value float32, usage string) *float32 { p := new(float32) f.Float32VarP(p, name, shorthand, value, usage) @@ -82,7 +85,7 @@ func Float32(name string, value float32, usage string) *float32 { return CommandLine.Float32P(name, "", value, usage) } -// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash. +// Like Float32, but accepts a shorthand letter that can be used after a single dash. func Float32P(name, shorthand string, value float32, usage string) *float32 { return CommandLine.Float32P(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/float64.go b/vendor/github.com/spf13/pflag/float64.go index 04b5492a..10e17e4b 100644 --- a/vendor/github.com/spf13/pflag/float64.go +++ b/vendor/github.com/spf13/pflag/float64.go @@ -1,6 +1,9 @@ package pflag -import "strconv" +import ( + "fmt" + "strconv" +) // -- float64 Value type float64Value float64 @@ -20,7 +23,7 @@ func (f *float64Value) Type() string { return "float64" } -func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 64) } +func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) } func float64Conv(sval string) (interface{}, error) { return strconv.ParseFloat(sval, 64) @@ -41,7 +44,7 @@ func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage strin f.VarP(newFloat64Value(value, p), name, "", usage) } -// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash. +// Like Float64Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Float64VarP(p *float64, name, shorthand string, value float64, usage string) { f.VarP(newFloat64Value(value, p), name, shorthand, usage) } @@ -52,7 +55,7 @@ func Float64Var(p *float64, name string, value float64, usage string) { CommandLine.VarP(newFloat64Value(value, p), name, "", usage) } -// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash. +// Like Float64Var, but accepts a shorthand letter that can be used after a single dash. func Float64VarP(p *float64, name, shorthand string, value float64, usage string) { CommandLine.VarP(newFloat64Value(value, p), name, shorthand, usage) } @@ -65,7 +68,7 @@ func (f *FlagSet) Float64(name string, value float64, usage string) *float64 { return p } -// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash. +// Like Float64, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Float64P(name, shorthand string, value float64, usage string) *float64 { p := new(float64) f.Float64VarP(p, name, shorthand, value, usage) @@ -78,7 +81,7 @@ func Float64(name string, value float64, usage string) *float64 { return CommandLine.Float64P(name, "", value, usage) } -// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash. +// Like Float64, but accepts a shorthand letter that can be used after a single dash. func Float64P(name, shorthand string, value float64, usage string) *float64 { return CommandLine.Float64P(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/golangflag.go b/vendor/github.com/spf13/pflag/golangflag.go deleted file mode 100644 index d3dd72b7..00000000 --- a/vendor/github.com/spf13/pflag/golangflag.go +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag - -import ( - goflag "flag" - "reflect" - "strings" -) - -// flagValueWrapper implements pflag.Value around a flag.Value. The main -// difference here is the addition of the Type method that returns a string -// name of the type. As this is generally unknown, we approximate that with -// reflection. -type flagValueWrapper struct { - inner goflag.Value - flagType string -} - -// We are just copying the boolFlag interface out of goflag as that is what -// they use to decide if a flag should get "true" when no arg is given. -type goBoolFlag interface { - goflag.Value - IsBoolFlag() bool -} - -func wrapFlagValue(v goflag.Value) Value { - // If the flag.Value happens to also be a pflag.Value, just use it directly. - if pv, ok := v.(Value); ok { - return pv - } - - pv := &flagValueWrapper{ - inner: v, - } - - t := reflect.TypeOf(v) - if t.Kind() == reflect.Interface || t.Kind() == reflect.Ptr { - t = t.Elem() - } - - pv.flagType = strings.TrimSuffix(t.Name(), "Value") - return pv -} - -func (v *flagValueWrapper) String() string { - return v.inner.String() -} - -func (v *flagValueWrapper) Set(s string) error { - return v.inner.Set(s) -} - -func (v *flagValueWrapper) Type() string { - return v.flagType -} - -// PFlagFromGoFlag will return a *pflag.Flag given a *flag.Flag -// If the *flag.Flag.Name was a single character (ex: `v`) it will be accessiblei -// with both `-v` and `--v` in flags. If the golang flag was more than a single -// character (ex: `verbose`) it will only be accessible via `--verbose` -func PFlagFromGoFlag(goflag *goflag.Flag) *Flag { - // Remember the default value as a string; it won't change. - flag := &Flag{ - Name: goflag.Name, - Usage: goflag.Usage, - Value: wrapFlagValue(goflag.Value), - // Looks like golang flags don't set DefValue correctly :-( - //DefValue: goflag.DefValue, - DefValue: goflag.Value.String(), - } - // Ex: if the golang flag was -v, allow both -v and --v to work - if len(flag.Name) == 1 { - flag.Shorthand = flag.Name - } - if fv, ok := goflag.Value.(goBoolFlag); ok && fv.IsBoolFlag() { - flag.NoOptDefVal = "true" - } - return flag -} - -// AddGoFlag will add the given *flag.Flag to the pflag.FlagSet -func (f *FlagSet) AddGoFlag(goflag *goflag.Flag) { - if f.Lookup(goflag.Name) != nil { - return - } - newflag := PFlagFromGoFlag(goflag) - f.AddFlag(newflag) -} - -// AddGoFlagSet will add the given *flag.FlagSet to the pflag.FlagSet -func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet) { - if newSet == nil { - return - } - newSet.VisitAll(func(goflag *goflag.Flag) { - f.AddGoFlag(goflag) - }) - if f.addedGoFlagSets == nil { - f.addedGoFlagSets = make([]*goflag.FlagSet, 0) - } - f.addedGoFlagSets = append(f.addedGoFlagSets, newSet) -} diff --git a/vendor/github.com/spf13/pflag/golangflag_test.go b/vendor/github.com/spf13/pflag/golangflag_test.go deleted file mode 100644 index 5bd831bf..00000000 --- a/vendor/github.com/spf13/pflag/golangflag_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag - -import ( - goflag "flag" - "testing" -) - -func TestGoflags(t *testing.T) { - goflag.String("stringFlag", "stringFlag", "stringFlag") - goflag.Bool("boolFlag", false, "boolFlag") - - f := NewFlagSet("test", ContinueOnError) - - f.AddGoFlagSet(goflag.CommandLine) - err := f.Parse([]string{"--stringFlag=bob", "--boolFlag"}) - if err != nil { - t.Fatal("expected no error; get", err) - } - - getString, err := f.GetString("stringFlag") - if err != nil { - t.Fatal("expected no error; get", err) - } - if getString != "bob" { - t.Fatalf("expected getString=bob but got getString=%s", getString) - } - - getBool, err := f.GetBool("boolFlag") - if err != nil { - t.Fatal("expected no error; get", err) - } - if getBool != true { - t.Fatalf("expected getBool=true but got getBool=%v", getBool) - } - if !f.Parsed() { - t.Fatal("f.Parsed() return false after f.Parse() called") - } - - // in fact it is useless. because `go test` called flag.Parse() - if !goflag.CommandLine.Parsed() { - t.Fatal("goflag.CommandLine.Parsed() return false after f.Parse() called") - } -} diff --git a/vendor/github.com/spf13/pflag/int.go b/vendor/github.com/spf13/pflag/int.go index 1474b89d..23f70ddd 100644 --- a/vendor/github.com/spf13/pflag/int.go +++ b/vendor/github.com/spf13/pflag/int.go @@ -1,6 +1,9 @@ package pflag -import "strconv" +import ( + "fmt" + "strconv" +) // -- int Value type intValue int @@ -20,7 +23,7 @@ func (i *intValue) Type() string { return "int" } -func (i *intValue) String() string { return strconv.Itoa(int(*i)) } +func (i *intValue) String() string { return fmt.Sprintf("%v", *i) } func intConv(sval string) (interface{}, error) { return strconv.Atoi(sval) @@ -41,7 +44,7 @@ func (f *FlagSet) IntVar(p *int, name string, value int, usage string) { f.VarP(newIntValue(value, p), name, "", usage) } -// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash. +// Like IntVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IntVarP(p *int, name, shorthand string, value int, usage string) { f.VarP(newIntValue(value, p), name, shorthand, usage) } @@ -52,7 +55,7 @@ func IntVar(p *int, name string, value int, usage string) { CommandLine.VarP(newIntValue(value, p), name, "", usage) } -// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash. +// Like IntVar, but accepts a shorthand letter that can be used after a single dash. func IntVarP(p *int, name, shorthand string, value int, usage string) { CommandLine.VarP(newIntValue(value, p), name, shorthand, usage) } @@ -65,7 +68,7 @@ func (f *FlagSet) Int(name string, value int, usage string) *int { return p } -// IntP is like Int, but accepts a shorthand letter that can be used after a single dash. +// Like Int, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IntP(name, shorthand string, value int, usage string) *int { p := new(int) f.IntVarP(p, name, shorthand, value, usage) @@ -78,7 +81,7 @@ func Int(name string, value int, usage string) *int { return CommandLine.IntP(name, "", value, usage) } -// IntP is like Int, but accepts a shorthand letter that can be used after a single dash. +// Like Int, but accepts a shorthand letter that can be used after a single dash. func IntP(name, shorthand string, value int, usage string) *int { return CommandLine.IntP(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/int16.go b/vendor/github.com/spf13/pflag/int16.go deleted file mode 100644 index f1a01d05..00000000 --- a/vendor/github.com/spf13/pflag/int16.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- int16 Value -type int16Value int16 - -func newInt16Value(val int16, p *int16) *int16Value { - *p = val - return (*int16Value)(p) -} - -func (i *int16Value) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 16) - *i = int16Value(v) - return err -} - -func (i *int16Value) Type() string { - return "int16" -} - -func (i *int16Value) String() string { return strconv.FormatInt(int64(*i), 10) } - -func int16Conv(sval string) (interface{}, error) { - v, err := strconv.ParseInt(sval, 0, 16) - if err != nil { - return 0, err - } - return int16(v), nil -} - -// GetInt16 returns the int16 value of a flag with the given name -func (f *FlagSet) GetInt16(name string) (int16, error) { - val, err := f.getFlagType(name, "int16", int16Conv) - if err != nil { - return 0, err - } - return val.(int16), nil -} - -// Int16Var defines an int16 flag with specified name, default value, and usage string. -// The argument p points to an int16 variable in which to store the value of the flag. -func (f *FlagSet) Int16Var(p *int16, name string, value int16, usage string) { - f.VarP(newInt16Value(value, p), name, "", usage) -} - -// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int16VarP(p *int16, name, shorthand string, value int16, usage string) { - f.VarP(newInt16Value(value, p), name, shorthand, usage) -} - -// Int16Var defines an int16 flag with specified name, default value, and usage string. -// The argument p points to an int16 variable in which to store the value of the flag. -func Int16Var(p *int16, name string, value int16, usage string) { - CommandLine.VarP(newInt16Value(value, p), name, "", usage) -} - -// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash. -func Int16VarP(p *int16, name, shorthand string, value int16, usage string) { - CommandLine.VarP(newInt16Value(value, p), name, shorthand, usage) -} - -// Int16 defines an int16 flag with specified name, default value, and usage string. -// The return value is the address of an int16 variable that stores the value of the flag. -func (f *FlagSet) Int16(name string, value int16, usage string) *int16 { - p := new(int16) - f.Int16VarP(p, name, "", value, usage) - return p -} - -// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int16P(name, shorthand string, value int16, usage string) *int16 { - p := new(int16) - f.Int16VarP(p, name, shorthand, value, usage) - return p -} - -// Int16 defines an int16 flag with specified name, default value, and usage string. -// The return value is the address of an int16 variable that stores the value of the flag. -func Int16(name string, value int16, usage string) *int16 { - return CommandLine.Int16P(name, "", value, usage) -} - -// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash. -func Int16P(name, shorthand string, value int16, usage string) *int16 { - return CommandLine.Int16P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/int32.go b/vendor/github.com/spf13/pflag/int32.go index 9b95944f..515f90bb 100644 --- a/vendor/github.com/spf13/pflag/int32.go +++ b/vendor/github.com/spf13/pflag/int32.go @@ -1,6 +1,9 @@ package pflag -import "strconv" +import ( + "fmt" + "strconv" +) // -- int32 Value type int32Value int32 @@ -20,7 +23,7 @@ func (i *int32Value) Type() string { return "int32" } -func (i *int32Value) String() string { return strconv.FormatInt(int64(*i), 10) } +func (i *int32Value) String() string { return fmt.Sprintf("%v", *i) } func int32Conv(sval string) (interface{}, error) { v, err := strconv.ParseInt(sval, 0, 32) @@ -45,7 +48,7 @@ func (f *FlagSet) Int32Var(p *int32, name string, value int32, usage string) { f.VarP(newInt32Value(value, p), name, "", usage) } -// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash. +// Like Int32Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Int32VarP(p *int32, name, shorthand string, value int32, usage string) { f.VarP(newInt32Value(value, p), name, shorthand, usage) } @@ -56,7 +59,7 @@ func Int32Var(p *int32, name string, value int32, usage string) { CommandLine.VarP(newInt32Value(value, p), name, "", usage) } -// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash. +// Like Int32Var, but accepts a shorthand letter that can be used after a single dash. func Int32VarP(p *int32, name, shorthand string, value int32, usage string) { CommandLine.VarP(newInt32Value(value, p), name, shorthand, usage) } @@ -69,7 +72,7 @@ func (f *FlagSet) Int32(name string, value int32, usage string) *int32 { return p } -// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash. +// Like Int32, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Int32P(name, shorthand string, value int32, usage string) *int32 { p := new(int32) f.Int32VarP(p, name, shorthand, value, usage) @@ -82,7 +85,7 @@ func Int32(name string, value int32, usage string) *int32 { return CommandLine.Int32P(name, "", value, usage) } -// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash. +// Like Int32, but accepts a shorthand letter that can be used after a single dash. func Int32P(name, shorthand string, value int32, usage string) *int32 { return CommandLine.Int32P(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/int64.go b/vendor/github.com/spf13/pflag/int64.go index 0026d781..b77ade41 100644 --- a/vendor/github.com/spf13/pflag/int64.go +++ b/vendor/github.com/spf13/pflag/int64.go @@ -1,6 +1,9 @@ package pflag -import "strconv" +import ( + "fmt" + "strconv" +) // -- int64 Value type int64Value int64 @@ -20,7 +23,7 @@ func (i *int64Value) Type() string { return "int64" } -func (i *int64Value) String() string { return strconv.FormatInt(int64(*i), 10) } +func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) } func int64Conv(sval string) (interface{}, error) { return strconv.ParseInt(sval, 0, 64) @@ -41,7 +44,7 @@ func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) { f.VarP(newInt64Value(value, p), name, "", usage) } -// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash. +// Like Int64Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Int64VarP(p *int64, name, shorthand string, value int64, usage string) { f.VarP(newInt64Value(value, p), name, shorthand, usage) } @@ -52,7 +55,7 @@ func Int64Var(p *int64, name string, value int64, usage string) { CommandLine.VarP(newInt64Value(value, p), name, "", usage) } -// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash. +// Like Int64Var, but accepts a shorthand letter that can be used after a single dash. func Int64VarP(p *int64, name, shorthand string, value int64, usage string) { CommandLine.VarP(newInt64Value(value, p), name, shorthand, usage) } @@ -65,7 +68,7 @@ func (f *FlagSet) Int64(name string, value int64, usage string) *int64 { return p } -// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash. +// Like Int64, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Int64P(name, shorthand string, value int64, usage string) *int64 { p := new(int64) f.Int64VarP(p, name, shorthand, value, usage) @@ -78,7 +81,7 @@ func Int64(name string, value int64, usage string) *int64 { return CommandLine.Int64P(name, "", value, usage) } -// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash. +// Like Int64, but accepts a shorthand letter that can be used after a single dash. func Int64P(name, shorthand string, value int64, usage string) *int64 { return CommandLine.Int64P(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/int8.go b/vendor/github.com/spf13/pflag/int8.go index 4da92228..c51cb4ff 100644 --- a/vendor/github.com/spf13/pflag/int8.go +++ b/vendor/github.com/spf13/pflag/int8.go @@ -1,6 +1,9 @@ package pflag -import "strconv" +import ( + "fmt" + "strconv" +) // -- int8 Value type int8Value int8 @@ -20,7 +23,7 @@ func (i *int8Value) Type() string { return "int8" } -func (i *int8Value) String() string { return strconv.FormatInt(int64(*i), 10) } +func (i *int8Value) String() string { return fmt.Sprintf("%v", *i) } func int8Conv(sval string) (interface{}, error) { v, err := strconv.ParseInt(sval, 0, 8) @@ -45,7 +48,7 @@ func (f *FlagSet) Int8Var(p *int8, name string, value int8, usage string) { f.VarP(newInt8Value(value, p), name, "", usage) } -// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash. +// Like Int8Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Int8VarP(p *int8, name, shorthand string, value int8, usage string) { f.VarP(newInt8Value(value, p), name, shorthand, usage) } @@ -56,7 +59,7 @@ func Int8Var(p *int8, name string, value int8, usage string) { CommandLine.VarP(newInt8Value(value, p), name, "", usage) } -// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash. +// Like Int8Var, but accepts a shorthand letter that can be used after a single dash. func Int8VarP(p *int8, name, shorthand string, value int8, usage string) { CommandLine.VarP(newInt8Value(value, p), name, shorthand, usage) } @@ -69,7 +72,7 @@ func (f *FlagSet) Int8(name string, value int8, usage string) *int8 { return p } -// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash. +// Like Int8, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Int8P(name, shorthand string, value int8, usage string) *int8 { p := new(int8) f.Int8VarP(p, name, shorthand, value, usage) @@ -82,7 +85,7 @@ func Int8(name string, value int8, usage string) *int8 { return CommandLine.Int8P(name, "", value, usage) } -// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash. +// Like Int8, but accepts a shorthand letter that can be used after a single dash. func Int8P(name, shorthand string, value int8, usage string) *int8 { return CommandLine.Int8P(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/int_slice.go b/vendor/github.com/spf13/pflag/int_slice.go index 1e7c9edd..7c6ed79f 100644 --- a/vendor/github.com/spf13/pflag/int_slice.go +++ b/vendor/github.com/spf13/pflag/int_slice.go @@ -85,7 +85,7 @@ func (f *FlagSet) IntSliceVar(p *[]int, name string, value []int, usage string) f.VarP(newIntSliceValue(value, p), name, "", usage) } -// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash. +// Like IntSliceVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) { f.VarP(newIntSliceValue(value, p), name, shorthand, usage) } @@ -96,7 +96,7 @@ func IntSliceVar(p *[]int, name string, value []int, usage string) { CommandLine.VarP(newIntSliceValue(value, p), name, "", usage) } -// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash. +// Like IntSliceVar, but accepts a shorthand letter that can be used after a single dash. func IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) { CommandLine.VarP(newIntSliceValue(value, p), name, shorthand, usage) } @@ -104,14 +104,14 @@ func IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) { // IntSlice defines a []int flag with specified name, default value, and usage string. // The return value is the address of a []int variable that stores the value of the flag. func (f *FlagSet) IntSlice(name string, value []int, usage string) *[]int { - p := []int{} + p := make([]int, 0) f.IntSliceVarP(&p, name, "", value, usage) return &p } -// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash. +// Like IntSlice, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IntSliceP(name, shorthand string, value []int, usage string) *[]int { - p := []int{} + p := make([]int, 0) f.IntSliceVarP(&p, name, shorthand, value, usage) return &p } @@ -122,7 +122,7 @@ func IntSlice(name string, value []int, usage string) *[]int { return CommandLine.IntSliceP(name, "", value, usage) } -// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash. +// Like IntSlice, but accepts a shorthand letter that can be used after a single dash. func IntSliceP(name, shorthand string, value []int, usage string) *[]int { return CommandLine.IntSliceP(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/int_slice_test.go b/vendor/github.com/spf13/pflag/int_slice_test.go index 745aecb9..13a6551b 100644 --- a/vendor/github.com/spf13/pflag/int_slice_test.go +++ b/vendor/github.com/spf13/pflag/int_slice_test.go @@ -60,9 +60,6 @@ func TestIS(t *testing.T) { } } getIS, err := f.GetIntSlice("is") - if err != nil { - t.Fatalf("got error: %v", err) - } for i, v := range getIS { d, err := strconv.Atoi(vals[i]) if err != nil { @@ -90,7 +87,7 @@ func TestISDefault(t *testing.T) { t.Fatalf("got error: %v", err) } if d != v { - t.Fatalf("expected is[%d] to be %d but got: %d", i, d, v) + t.Fatalf("expected is[%d] to be %s but got: %s", i, d, v) } } @@ -104,7 +101,7 @@ func TestISDefault(t *testing.T) { t.Fatal("got an error from GetIntSlice():", err) } if d != v { - t.Fatalf("expected is[%d] to be %d from GetIntSlice but got: %d", i, d, v) + t.Fatalf("expected is[%d] to be %s from GetIntSlice but got: %s", i, d, v) } } } @@ -125,7 +122,7 @@ func TestISWithDefault(t *testing.T) { t.Fatalf("got error: %v", err) } if d != v { - t.Fatalf("expected is[%d] to be %d but got: %d", i, d, v) + t.Fatalf("expected is[%d] to be %s but got: %s", i, d, v) } } @@ -139,7 +136,7 @@ func TestISWithDefault(t *testing.T) { t.Fatalf("got error: %v", err) } if d != v { - t.Fatalf("expected is[%d] to be %d from GetIntSlice but got: %d", i, d, v) + t.Fatalf("expected is[%d] to be %s from GetIntSlice but got: %s", i, d, v) } } } @@ -159,7 +156,7 @@ func TestISCalledTwice(t *testing.T) { } for i, v := range is { if expected[i] != v { - t.Fatalf("expected is[%d] to be %d but got: %d", i, expected[i], v) + t.Fatalf("expected is[%d] to be %s but got: %s", i, expected[i], v) } } } diff --git a/vendor/github.com/spf13/pflag/ip.go b/vendor/github.com/spf13/pflag/ip.go index 3d414ba6..baa442b5 100644 --- a/vendor/github.com/spf13/pflag/ip.go +++ b/vendor/github.com/spf13/pflag/ip.go @@ -6,6 +6,8 @@ import ( "strings" ) +var _ = strings.TrimSpace + // -- net.IP value type ipValue net.IP @@ -51,7 +53,7 @@ func (f *FlagSet) IPVar(p *net.IP, name string, value net.IP, usage string) { f.VarP(newIPValue(value, p), name, "", usage) } -// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash. +// Like IPVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) { f.VarP(newIPValue(value, p), name, shorthand, usage) } @@ -62,7 +64,7 @@ func IPVar(p *net.IP, name string, value net.IP, usage string) { CommandLine.VarP(newIPValue(value, p), name, "", usage) } -// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash. +// Like IPVar, but accepts a shorthand letter that can be used after a single dash. func IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) { CommandLine.VarP(newIPValue(value, p), name, shorthand, usage) } @@ -75,7 +77,7 @@ func (f *FlagSet) IP(name string, value net.IP, usage string) *net.IP { return p } -// IPP is like IP, but accepts a shorthand letter that can be used after a single dash. +// Like IP, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IPP(name, shorthand string, value net.IP, usage string) *net.IP { p := new(net.IP) f.IPVarP(p, name, shorthand, value, usage) @@ -88,7 +90,7 @@ func IP(name string, value net.IP, usage string) *net.IP { return CommandLine.IPP(name, "", value, usage) } -// IPP is like IP, but accepts a shorthand letter that can be used after a single dash. +// Like IP, but accepts a shorthand letter that can be used after a single dash. func IPP(name, shorthand string, value net.IP, usage string) *net.IP { return CommandLine.IPP(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/ip_slice.go b/vendor/github.com/spf13/pflag/ip_slice.go deleted file mode 100644 index 7dd196fe..00000000 --- a/vendor/github.com/spf13/pflag/ip_slice.go +++ /dev/null @@ -1,148 +0,0 @@ -package pflag - -import ( - "fmt" - "io" - "net" - "strings" -) - -// -- ipSlice Value -type ipSliceValue struct { - value *[]net.IP - changed bool -} - -func newIPSliceValue(val []net.IP, p *[]net.IP) *ipSliceValue { - ipsv := new(ipSliceValue) - ipsv.value = p - *ipsv.value = val - return ipsv -} - -// Set converts, and assigns, the comma-separated IP argument string representation as the []net.IP value of this flag. -// If Set is called on a flag that already has a []net.IP assigned, the newly converted values will be appended. -func (s *ipSliceValue) Set(val string) error { - - // remove all quote characters - rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "") - - // read flag arguments with CSV parser - ipStrSlice, err := readAsCSV(rmQuote.Replace(val)) - if err != nil && err != io.EOF { - return err - } - - // parse ip values into slice - out := make([]net.IP, 0, len(ipStrSlice)) - for _, ipStr := range ipStrSlice { - ip := net.ParseIP(strings.TrimSpace(ipStr)) - if ip == nil { - return fmt.Errorf("invalid string being converted to IP address: %s", ipStr) - } - out = append(out, ip) - } - - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - - s.changed = true - - return nil -} - -// Type returns a string that uniquely represents this flag's type. -func (s *ipSliceValue) Type() string { - return "ipSlice" -} - -// String defines a "native" format for this net.IP slice flag value. -func (s *ipSliceValue) String() string { - - ipStrSlice := make([]string, len(*s.value)) - for i, ip := range *s.value { - ipStrSlice[i] = ip.String() - } - - out, _ := writeAsCSV(ipStrSlice) - - return "[" + out + "]" -} - -func ipSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Emtpy string would cause a slice with one (empty) entry - if len(val) == 0 { - return []net.IP{}, nil - } - ss := strings.Split(val, ",") - out := make([]net.IP, len(ss)) - for i, sval := range ss { - ip := net.ParseIP(strings.TrimSpace(sval)) - if ip == nil { - return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval) - } - out[i] = ip - } - return out, nil -} - -// GetIPSlice returns the []net.IP value of a flag with the given name -func (f *FlagSet) GetIPSlice(name string) ([]net.IP, error) { - val, err := f.getFlagType(name, "ipSlice", ipSliceConv) - if err != nil { - return []net.IP{}, err - } - return val.([]net.IP), nil -} - -// IPSliceVar defines a ipSlice flag with specified name, default value, and usage string. -// The argument p points to a []net.IP variable in which to store the value of the flag. -func (f *FlagSet) IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) { - f.VarP(newIPSliceValue(value, p), name, "", usage) -} - -// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) { - f.VarP(newIPSliceValue(value, p), name, shorthand, usage) -} - -// IPSliceVar defines a []net.IP flag with specified name, default value, and usage string. -// The argument p points to a []net.IP variable in which to store the value of the flag. -func IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) { - CommandLine.VarP(newIPSliceValue(value, p), name, "", usage) -} - -// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash. -func IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) { - CommandLine.VarP(newIPSliceValue(value, p), name, shorthand, usage) -} - -// IPSlice defines a []net.IP flag with specified name, default value, and usage string. -// The return value is the address of a []net.IP variable that stores the value of that flag. -func (f *FlagSet) IPSlice(name string, value []net.IP, usage string) *[]net.IP { - p := []net.IP{} - f.IPSliceVarP(&p, name, "", value, usage) - return &p -} - -// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP { - p := []net.IP{} - f.IPSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// IPSlice defines a []net.IP flag with specified name, default value, and usage string. -// The return value is the address of a []net.IP variable that stores the value of the flag. -func IPSlice(name string, value []net.IP, usage string) *[]net.IP { - return CommandLine.IPSliceP(name, "", value, usage) -} - -// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash. -func IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP { - return CommandLine.IPSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/ip_slice_test.go b/vendor/github.com/spf13/pflag/ip_slice_test.go deleted file mode 100644 index b0c681c5..00000000 --- a/vendor/github.com/spf13/pflag/ip_slice_test.go +++ /dev/null @@ -1,222 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "strings" - "testing" -) - -func setUpIPSFlagSet(ipsp *[]net.IP) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.IPSliceVar(ipsp, "ips", []net.IP{}, "Command separated list!") - return f -} - -func setUpIPSFlagSetWithDefault(ipsp *[]net.IP) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.IPSliceVar(ipsp, "ips", - []net.IP{ - net.ParseIP("192.168.1.1"), - net.ParseIP("0:0:0:0:0:0:0:1"), - }, - "Command separated list!") - return f -} - -func TestEmptyIP(t *testing.T) { - var ips []net.IP - f := setUpIPSFlagSet(&ips) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getIPS, err := f.GetIPSlice("ips") - if err != nil { - t.Fatal("got an error from GetIPSlice():", err) - } - if len(getIPS) != 0 { - t.Fatalf("got ips %v with len=%d but expected length=0", getIPS, len(getIPS)) - } -} - -func TestIPS(t *testing.T) { - var ips []net.IP - f := setUpIPSFlagSet(&ips) - - vals := []string{"192.168.1.1", "10.0.0.1", "0:0:0:0:0:0:0:2"} - arg := fmt.Sprintf("--ips=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ips { - if ip := net.ParseIP(vals[i]); ip == nil { - t.Fatalf("invalid string being converted to IP address: %s", vals[i]) - } else if !ip.Equal(v) { - t.Fatalf("expected ips[%d] to be %s but got: %s from GetIPSlice", i, vals[i], v) - } - } -} - -func TestIPSDefault(t *testing.T) { - var ips []net.IP - f := setUpIPSFlagSetWithDefault(&ips) - - vals := []string{"192.168.1.1", "0:0:0:0:0:0:0:1"} - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ips { - if ip := net.ParseIP(vals[i]); ip == nil { - t.Fatalf("invalid string being converted to IP address: %s", vals[i]) - } else if !ip.Equal(v) { - t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getIPS, err := f.GetIPSlice("ips") - if err != nil { - t.Fatal("got an error from GetIPSlice") - } - for i, v := range getIPS { - if ip := net.ParseIP(vals[i]); ip == nil { - t.Fatalf("invalid string being converted to IP address: %s", vals[i]) - } else if !ip.Equal(v) { - t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v) - } - } -} - -func TestIPSWithDefault(t *testing.T) { - var ips []net.IP - f := setUpIPSFlagSetWithDefault(&ips) - - vals := []string{"192.168.1.1", "0:0:0:0:0:0:0:1"} - arg := fmt.Sprintf("--ips=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ips { - if ip := net.ParseIP(vals[i]); ip == nil { - t.Fatalf("invalid string being converted to IP address: %s", vals[i]) - } else if !ip.Equal(v) { - t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getIPS, err := f.GetIPSlice("ips") - if err != nil { - t.Fatal("got an error from GetIPSlice") - } - for i, v := range getIPS { - if ip := net.ParseIP(vals[i]); ip == nil { - t.Fatalf("invalid string being converted to IP address: %s", vals[i]) - } else if !ip.Equal(v) { - t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v) - } - } -} - -func TestIPSCalledTwice(t *testing.T) { - var ips []net.IP - f := setUpIPSFlagSet(&ips) - - in := []string{"192.168.1.2,0:0:0:0:0:0:0:1", "10.0.0.1"} - expected := []net.IP{net.ParseIP("192.168.1.2"), net.ParseIP("0:0:0:0:0:0:0:1"), net.ParseIP("10.0.0.1")} - argfmt := "ips=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ips { - if !expected[i].Equal(v) { - t.Fatalf("expected ips[%d] to be %s but got: %s", i, expected[i], v) - } - } -} - -func TestIPSBadQuoting(t *testing.T) { - - tests := []struct { - Want []net.IP - FlagArg []string - }{ - { - Want: []net.IP{ - net.ParseIP("a4ab:61d:f03e:5d7d:fad7:d4c2:a1a5:568"), - net.ParseIP("203.107.49.208"), - net.ParseIP("14.57.204.90"), - }, - FlagArg: []string{ - "a4ab:61d:f03e:5d7d:fad7:d4c2:a1a5:568", - "203.107.49.208", - "14.57.204.90", - }, - }, - { - Want: []net.IP{ - net.ParseIP("204.228.73.195"), - net.ParseIP("86.141.15.94"), - }, - FlagArg: []string{ - "204.228.73.195", - "86.141.15.94", - }, - }, - { - Want: []net.IP{ - net.ParseIP("c70c:db36:3001:890f:c6ea:3f9b:7a39:cc3f"), - net.ParseIP("4d17:1d6e:e699:bd7a:88c5:5e7e:ac6a:4472"), - }, - FlagArg: []string{ - "c70c:db36:3001:890f:c6ea:3f9b:7a39:cc3f", - "4d17:1d6e:e699:bd7a:88c5:5e7e:ac6a:4472", - }, - }, - { - Want: []net.IP{ - net.ParseIP("5170:f971:cfac:7be3:512a:af37:952c:bc33"), - net.ParseIP("93.21.145.140"), - net.ParseIP("2cac:61d3:c5ff:6caf:73e0:1b1a:c336:c1ca"), - }, - FlagArg: []string{ - " 5170:f971:cfac:7be3:512a:af37:952c:bc33 , 93.21.145.140 ", - "2cac:61d3:c5ff:6caf:73e0:1b1a:c336:c1ca", - }, - }, - { - Want: []net.IP{ - net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"), - net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"), - net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"), - net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"), - }, - FlagArg: []string{ - `"2e5e:66b2:6441:848:5b74:76ea:574c:3a7b, 2e5e:66b2:6441:848:5b74:76ea:574c:3a7b,2e5e:66b2:6441:848:5b74:76ea:574c:3a7b "`, - " 2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"}, - }, - } - - for i, test := range tests { - - var ips []net.IP - f := setUpIPSFlagSet(&ips) - - if err := f.Parse([]string{fmt.Sprintf("--ips=%s", strings.Join(test.FlagArg, ","))}); err != nil { - t.Fatalf("flag parsing failed with error: %s\nparsing:\t%#v\nwant:\t\t%s", - err, test.FlagArg, test.Want[i]) - } - - for j, b := range ips { - if !b.Equal(test.Want[j]) { - t.Fatalf("bad value parsed for test %d on net.IP %d:\nwant:\t%s\ngot:\t%s", i, j, test.Want[j], b) - } - } - } -} diff --git a/vendor/github.com/spf13/pflag/ipmask.go b/vendor/github.com/spf13/pflag/ipmask.go index 5bd44bd2..1b10efb4 100644 --- a/vendor/github.com/spf13/pflag/ipmask.go +++ b/vendor/github.com/spf13/pflag/ipmask.go @@ -28,7 +28,7 @@ func (i *ipMaskValue) Type() string { return "ipMask" } -// ParseIPv4Mask written in IP form (e.g. 255.255.255.0). +// Parse IPv4 netmask written in IP form (e.g. 255.255.255.0). // This function should really belong to the net package. func ParseIPv4Mask(s string) net.IPMask { mask := net.ParseIP(s) @@ -79,7 +79,7 @@ func (f *FlagSet) IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage f.VarP(newIPMaskValue(value, p), name, "", usage) } -// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. +// Like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) { f.VarP(newIPMaskValue(value, p), name, shorthand, usage) } @@ -90,7 +90,7 @@ func IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) { CommandLine.VarP(newIPMaskValue(value, p), name, "", usage) } -// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. +// Like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. func IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) { CommandLine.VarP(newIPMaskValue(value, p), name, shorthand, usage) } @@ -103,7 +103,7 @@ func (f *FlagSet) IPMask(name string, value net.IPMask, usage string) *net.IPMas return p } -// IPMaskP is like IPMask, but accepts a shorthand letter that can be used after a single dash. +// Like IPMask, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask { p := new(net.IPMask) f.IPMaskVarP(p, name, shorthand, value, usage) @@ -116,7 +116,7 @@ func IPMask(name string, value net.IPMask, usage string) *net.IPMask { return CommandLine.IPMaskP(name, "", value, usage) } -// IPMaskP is like IP, but accepts a shorthand letter that can be used after a single dash. +// Like IP, but accepts a shorthand letter that can be used after a single dash. func IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask { return CommandLine.IPMaskP(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/ipnet.go b/vendor/github.com/spf13/pflag/ipnet.go index e2c1b8bc..23b7fd3c 100644 --- a/vendor/github.com/spf13/pflag/ipnet.go +++ b/vendor/github.com/spf13/pflag/ipnet.go @@ -7,29 +7,31 @@ import ( ) // IPNet adapts net.IPNet for use as a flag. -type ipNetValue net.IPNet +type IPNetValue net.IPNet -func (ipnet ipNetValue) String() string { +func (ipnet IPNetValue) String() string { n := net.IPNet(ipnet) return n.String() } -func (ipnet *ipNetValue) Set(value string) error { +func (ipnet *IPNetValue) Set(value string) error { _, n, err := net.ParseCIDR(strings.TrimSpace(value)) if err != nil { return err } - *ipnet = ipNetValue(*n) + *ipnet = IPNetValue(*n) return nil } -func (*ipNetValue) Type() string { +func (*IPNetValue) Type() string { return "ipNet" } -func newIPNetValue(val net.IPNet, p *net.IPNet) *ipNetValue { +var _ = strings.TrimSpace + +func newIPNetValue(val net.IPNet, p *net.IPNet) *IPNetValue { *p = val - return (*ipNetValue)(p) + return (*IPNetValue)(p) } func ipNetConv(sval string) (interface{}, error) { @@ -55,7 +57,7 @@ func (f *FlagSet) IPNetVar(p *net.IPNet, name string, value net.IPNet, usage str f.VarP(newIPNetValue(value, p), name, "", usage) } -// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash. +// Like IPNetVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) { f.VarP(newIPNetValue(value, p), name, shorthand, usage) } @@ -66,7 +68,7 @@ func IPNetVar(p *net.IPNet, name string, value net.IPNet, usage string) { CommandLine.VarP(newIPNetValue(value, p), name, "", usage) } -// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash. +// Like IPNetVar, but accepts a shorthand letter that can be used after a single dash. func IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) { CommandLine.VarP(newIPNetValue(value, p), name, shorthand, usage) } @@ -79,7 +81,7 @@ func (f *FlagSet) IPNet(name string, value net.IPNet, usage string) *net.IPNet { return p } -// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash. +// Like IPNet, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet { p := new(net.IPNet) f.IPNetVarP(p, name, shorthand, value, usage) @@ -92,7 +94,7 @@ func IPNet(name string, value net.IPNet, usage string) *net.IPNet { return CommandLine.IPNetP(name, "", value, usage) } -// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash. +// Like IPNet, but accepts a shorthand letter that can be used after a single dash. func IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet { return CommandLine.IPNetP(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/printusage_test.go b/vendor/github.com/spf13/pflag/printusage_test.go deleted file mode 100644 index df982aab..00000000 --- a/vendor/github.com/spf13/pflag/printusage_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package pflag - -import ( - "bytes" - "io" - "testing" -) - -const expectedOutput = ` --long-form Some description - --long-form2 Some description - with multiline - -s, --long-name Some description - -t, --long-name2 Some description with - multiline -` - -func setUpPFlagSet(buf io.Writer) *FlagSet { - f := NewFlagSet("test", ExitOnError) - f.Bool("long-form", false, "Some description") - f.Bool("long-form2", false, "Some description\n with multiline") - f.BoolP("long-name", "s", false, "Some description") - f.BoolP("long-name2", "t", false, "Some description with\n multiline") - f.SetOutput(buf) - return f -} - -func TestPrintUsage(t *testing.T) { - buf := bytes.Buffer{} - f := setUpPFlagSet(&buf) - f.PrintDefaults() - res := buf.String() - if res != expectedOutput { - t.Errorf("Expected \n%s \nActual \n%s", expectedOutput, res) - } -} - -func setUpPFlagSet2(buf io.Writer) *FlagSet { - f := NewFlagSet("test", ExitOnError) - f.Bool("long-form", false, "Some description") - f.Bool("long-form2", false, "Some description\n with multiline") - f.BoolP("long-name", "s", false, "Some description") - f.BoolP("long-name2", "t", false, "Some description with\n multiline") - f.StringP("some-very-long-arg", "l", "test", "Some very long description having break the limit") - f.StringP("other-very-long-arg", "o", "long-default-value", "Some very long description having break the limit") - f.String("some-very-long-arg2", "very long default value", "Some very long description\nwith line break\nmultiple") - f.SetOutput(buf) - return f -} - -const expectedOutput2 = ` --long-form Some description - --long-form2 Some description - with multiline - -s, --long-name Some description - -t, --long-name2 Some description with - multiline - -o, --other-very-long-arg string Some very long description having - break the limit (default - "long-default-value") - -l, --some-very-long-arg string Some very long description having - break the limit (default "test") - --some-very-long-arg2 string Some very long description - with line break - multiple (default "very long default - value") -` - -func TestPrintUsage_2(t *testing.T) { - buf := bytes.Buffer{} - f := setUpPFlagSet2(&buf) - res := f.FlagUsagesWrapped(80) - if res != expectedOutput2 { - t.Errorf("Expected \n%q \nActual \n%q", expectedOutput2, res) - } -} diff --git a/vendor/github.com/spf13/pflag/string.go b/vendor/github.com/spf13/pflag/string.go index 04e0a26f..f89ea8b5 100644 --- a/vendor/github.com/spf13/pflag/string.go +++ b/vendor/github.com/spf13/pflag/string.go @@ -1,5 +1,7 @@ package pflag +import "fmt" + // -- string Value type stringValue string @@ -16,7 +18,7 @@ func (s *stringValue) Type() string { return "string" } -func (s *stringValue) String() string { return string(*s) } +func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) } func stringConv(sval string) (interface{}, error) { return sval, nil @@ -37,7 +39,7 @@ func (f *FlagSet) StringVar(p *string, name string, value string, usage string) f.VarP(newStringValue(value, p), name, "", usage) } -// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash. +// Like StringVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) StringVarP(p *string, name, shorthand string, value string, usage string) { f.VarP(newStringValue(value, p), name, shorthand, usage) } @@ -48,7 +50,7 @@ func StringVar(p *string, name string, value string, usage string) { CommandLine.VarP(newStringValue(value, p), name, "", usage) } -// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash. +// Like StringVar, but accepts a shorthand letter that can be used after a single dash. func StringVarP(p *string, name, shorthand string, value string, usage string) { CommandLine.VarP(newStringValue(value, p), name, shorthand, usage) } @@ -61,7 +63,7 @@ func (f *FlagSet) String(name string, value string, usage string) *string { return p } -// StringP is like String, but accepts a shorthand letter that can be used after a single dash. +// Like String, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) StringP(name, shorthand string, value string, usage string) *string { p := new(string) f.StringVarP(p, name, shorthand, value, usage) @@ -74,7 +76,7 @@ func String(name string, value string, usage string) *string { return CommandLine.StringP(name, "", value, usage) } -// StringP is like String, but accepts a shorthand letter that can be used after a single dash. +// Like String, but accepts a shorthand letter that can be used after a single dash. func StringP(name, shorthand string, value string, usage string) *string { return CommandLine.StringP(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/string_array.go b/vendor/github.com/spf13/pflag/string_array.go deleted file mode 100644 index fa7bc601..00000000 --- a/vendor/github.com/spf13/pflag/string_array.go +++ /dev/null @@ -1,103 +0,0 @@ -package pflag - -// -- stringArray Value -type stringArrayValue struct { - value *[]string - changed bool -} - -func newStringArrayValue(val []string, p *[]string) *stringArrayValue { - ssv := new(stringArrayValue) - ssv.value = p - *ssv.value = val - return ssv -} - -func (s *stringArrayValue) Set(val string) error { - if !s.changed { - *s.value = []string{val} - s.changed = true - } else { - *s.value = append(*s.value, val) - } - return nil -} - -func (s *stringArrayValue) Type() string { - return "stringArray" -} - -func (s *stringArrayValue) String() string { - str, _ := writeAsCSV(*s.value) - return "[" + str + "]" -} - -func stringArrayConv(sval string) (interface{}, error) { - sval = sval[1 : len(sval)-1] - // An empty string would cause a array with one (empty) string - if len(sval) == 0 { - return []string{}, nil - } - return readAsCSV(sval) -} - -// GetStringArray return the []string value of a flag with the given name -func (f *FlagSet) GetStringArray(name string) ([]string, error) { - val, err := f.getFlagType(name, "stringArray", stringArrayConv) - if err != nil { - return []string{}, err - } - return val.([]string), nil -} - -// StringArrayVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a []string variable in which to store the values of the multiple flags. -// The value of each argument will not try to be separated by comma. Use a StringSlice for that. -func (f *FlagSet) StringArrayVar(p *[]string, name string, value []string, usage string) { - f.VarP(newStringArrayValue(value, p), name, "", usage) -} - -// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) { - f.VarP(newStringArrayValue(value, p), name, shorthand, usage) -} - -// StringArrayVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a []string variable in which to store the value of the flag. -// The value of each argument will not try to be separated by comma. Use a StringSlice for that. -func StringArrayVar(p *[]string, name string, value []string, usage string) { - CommandLine.VarP(newStringArrayValue(value, p), name, "", usage) -} - -// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash. -func StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) { - CommandLine.VarP(newStringArrayValue(value, p), name, shorthand, usage) -} - -// StringArray defines a string flag with specified name, default value, and usage string. -// The return value is the address of a []string variable that stores the value of the flag. -// The value of each argument will not try to be separated by comma. Use a StringSlice for that. -func (f *FlagSet) StringArray(name string, value []string, usage string) *[]string { - p := []string{} - f.StringArrayVarP(&p, name, "", value, usage) - return &p -} - -// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringArrayP(name, shorthand string, value []string, usage string) *[]string { - p := []string{} - f.StringArrayVarP(&p, name, shorthand, value, usage) - return &p -} - -// StringArray defines a string flag with specified name, default value, and usage string. -// The return value is the address of a []string variable that stores the value of the flag. -// The value of each argument will not try to be separated by comma. Use a StringSlice for that. -func StringArray(name string, value []string, usage string) *[]string { - return CommandLine.StringArrayP(name, "", value, usage) -} - -// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash. -func StringArrayP(name, shorthand string, value []string, usage string) *[]string { - return CommandLine.StringArrayP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/string_array_test.go b/vendor/github.com/spf13/pflag/string_array_test.go deleted file mode 100644 index 1ceac8c6..00000000 --- a/vendor/github.com/spf13/pflag/string_array_test.go +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag - -import ( - "fmt" - "testing" -) - -func setUpSAFlagSet(sap *[]string) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.StringArrayVar(sap, "sa", []string{}, "Command separated list!") - return f -} - -func setUpSAFlagSetWithDefault(sap *[]string) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.StringArrayVar(sap, "sa", []string{"default", "values"}, "Command separated list!") - return f -} - -func TestEmptySA(t *testing.T) { - var sa []string - f := setUpSAFlagSet(&sa) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getSA, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("got an error from GetStringArray():", err) - } - if len(getSA) != 0 { - t.Fatalf("got sa %v with len=%d but expected length=0", getSA, len(getSA)) - } -} - -func TestEmptySAValue(t *testing.T) { - var sa []string - f := setUpSAFlagSet(&sa) - err := f.Parse([]string{"--sa="}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getSA, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("got an error from GetStringArray():", err) - } - if len(getSA) != 0 { - t.Fatalf("got sa %v with len=%d but expected length=0", getSA, len(getSA)) - } -} - -func TestSADefault(t *testing.T) { - var sa []string - f := setUpSAFlagSetWithDefault(&sa) - - vals := []string{"default", "values"} - - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range sa { - if vals[i] != v { - t.Fatalf("expected sa[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getSA, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("got an error from GetStringArray():", err) - } - for i, v := range getSA { - if vals[i] != v { - t.Fatalf("expected sa[%d] to be %s from GetStringArray but got: %s", i, vals[i], v) - } - } -} - -func TestSAWithDefault(t *testing.T) { - var sa []string - f := setUpSAFlagSetWithDefault(&sa) - - val := "one" - arg := fmt.Sprintf("--sa=%s", val) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(sa) != 1 { - t.Fatalf("expected number of values to be %d but %d", 1, len(sa)) - } - - if sa[0] != val { - t.Fatalf("expected value to be %s but got: %s", sa[0], val) - } - - getSA, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("got an error from GetStringArray():", err) - } - - if len(getSA) != 1 { - t.Fatalf("expected number of values to be %d but %d", 1, len(getSA)) - } - - if getSA[0] != val { - t.Fatalf("expected value to be %s but got: %s", getSA[0], val) - } -} - -func TestSACalledTwice(t *testing.T) { - var sa []string - f := setUpSAFlagSet(&sa) - - in := []string{"one", "two"} - expected := []string{"one", "two"} - argfmt := "--sa=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(sa) { - t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa)) - } - for i, v := range sa { - if expected[i] != v { - t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v) - } - } - - values, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(values) { - t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(sa)) - } - for i, v := range values { - if expected[i] != v { - t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v) - } - } -} - -func TestSAWithSpecialChar(t *testing.T) { - var sa []string - f := setUpSAFlagSet(&sa) - - in := []string{"one,two", `"three"`, `"four,five",six`, "seven eight"} - expected := []string{"one,two", `"three"`, `"four,five",six`, "seven eight"} - argfmt := "--sa=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - arg3 := fmt.Sprintf(argfmt, in[2]) - arg4 := fmt.Sprintf(argfmt, in[3]) - err := f.Parse([]string{arg1, arg2, arg3, arg4}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(sa) { - t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa)) - } - for i, v := range sa { - if expected[i] != v { - t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v) - } - } - - values, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(values) { - t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values)) - } - for i, v := range values { - if expected[i] != v { - t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v) - } - } -} - -func TestSAWithSquareBrackets(t *testing.T) { - var sa []string - f := setUpSAFlagSet(&sa) - - in := []string{"][]-[", "[a-z]", "[a-z]+"} - expected := []string{"][]-[", "[a-z]", "[a-z]+"} - argfmt := "--sa=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - arg3 := fmt.Sprintf(argfmt, in[2]) - err := f.Parse([]string{arg1, arg2, arg3}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(sa) { - t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa)) - } - for i, v := range sa { - if expected[i] != v { - t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v) - } - } - - values, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(values) { - t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values)) - } - for i, v := range values { - if expected[i] != v { - t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v) - } - } -} diff --git a/vendor/github.com/spf13/pflag/string_slice.go b/vendor/github.com/spf13/pflag/string_slice.go index 0cd3ccc0..848bea89 100644 --- a/vendor/github.com/spf13/pflag/string_slice.go +++ b/vendor/github.com/spf13/pflag/string_slice.go @@ -1,11 +1,12 @@ package pflag import ( - "bytes" - "encoding/csv" + "fmt" "strings" ) +var _ = fmt.Fprint + // -- stringSlice Value type stringSliceValue struct { value *[]string @@ -19,31 +20,8 @@ func newStringSliceValue(val []string, p *[]string) *stringSliceValue { return ssv } -func readAsCSV(val string) ([]string, error) { - if val == "" { - return []string{}, nil - } - stringReader := strings.NewReader(val) - csvReader := csv.NewReader(stringReader) - return csvReader.Read() -} - -func writeAsCSV(vals []string) (string, error) { - b := &bytes.Buffer{} - w := csv.NewWriter(b) - err := w.Write(vals) - if err != nil { - return "", err - } - w.Flush() - return strings.TrimSuffix(b.String(), "\n"), nil -} - func (s *stringSliceValue) Set(val string) error { - v, err := readAsCSV(val) - if err != nil { - return err - } + v := strings.Split(val, ",") if !s.changed { *s.value = v } else { @@ -57,18 +35,16 @@ func (s *stringSliceValue) Type() string { return "stringSlice" } -func (s *stringSliceValue) String() string { - str, _ := writeAsCSV(*s.value) - return "[" + str + "]" -} +func (s *stringSliceValue) String() string { return "[" + strings.Join(*s.value, ",") + "]" } func stringSliceConv(sval string) (interface{}, error) { - sval = sval[1 : len(sval)-1] + sval = strings.Trim(sval, "[]") // An empty string would cause a slice with one (empty) string if len(sval) == 0 { return []string{}, nil } - return readAsCSV(sval) + v := strings.Split(sval, ",") + return v, nil } // GetStringSlice return the []string value of a flag with the given name @@ -82,68 +58,48 @@ func (f *FlagSet) GetStringSlice(name string) ([]string, error) { // StringSliceVar defines a string flag with specified name, default value, and usage string. // The argument p points to a []string variable in which to store the value of the flag. -// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. -// For example: -// --ss="v1,v2" -ss="v3" -// will result in -// []string{"v1", "v2", "v3"} func (f *FlagSet) StringSliceVar(p *[]string, name string, value []string, usage string) { f.VarP(newStringSliceValue(value, p), name, "", usage) } -// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash. +// Like StringSliceVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) { f.VarP(newStringSliceValue(value, p), name, shorthand, usage) } // StringSliceVar defines a string flag with specified name, default value, and usage string. // The argument p points to a []string variable in which to store the value of the flag. -// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. -// For example: -// --ss="v1,v2" -ss="v3" -// will result in -// []string{"v1", "v2", "v3"} func StringSliceVar(p *[]string, name string, value []string, usage string) { CommandLine.VarP(newStringSliceValue(value, p), name, "", usage) } -// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash. +// Like StringSliceVar, but accepts a shorthand letter that can be used after a single dash. func StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) { CommandLine.VarP(newStringSliceValue(value, p), name, shorthand, usage) } // StringSlice defines a string flag with specified name, default value, and usage string. // The return value is the address of a []string variable that stores the value of the flag. -// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. -// For example: -// --ss="v1,v2" -ss="v3" -// will result in -// []string{"v1", "v2", "v3"} func (f *FlagSet) StringSlice(name string, value []string, usage string) *[]string { - p := []string{} + p := make([]string, 0) f.StringSliceVarP(&p, name, "", value, usage) return &p } -// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash. +// Like StringSlice, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) StringSliceP(name, shorthand string, value []string, usage string) *[]string { - p := []string{} + p := make([]string, 0) f.StringSliceVarP(&p, name, shorthand, value, usage) return &p } // StringSlice defines a string flag with specified name, default value, and usage string. // The return value is the address of a []string variable that stores the value of the flag. -// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. -// For example: -// --ss="v1,v2" -ss="v3" -// will result in -// []string{"v1", "v2", "v3"} func StringSlice(name string, value []string, usage string) *[]string { return CommandLine.StringSliceP(name, "", value, usage) } -// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash. +// Like StringSlice, but accepts a shorthand letter that can be used after a single dash. func StringSliceP(name, shorthand string, value []string, usage string) *[]string { return CommandLine.StringSliceP(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/string_slice_test.go b/vendor/github.com/spf13/pflag/string_slice_test.go index c41f3bd6..97602de5 100644 --- a/vendor/github.com/spf13/pflag/string_slice_test.go +++ b/vendor/github.com/spf13/pflag/string_slice_test.go @@ -39,23 +39,6 @@ func TestEmptySS(t *testing.T) { } } -func TestEmptySSValue(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - err := f.Parse([]string{"--ss="}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - if len(getSS) != 0 { - t.Fatalf("got ss %v with len=%d but expected length=0", getSS, len(getSS)) - } -} - func TestSS(t *testing.T) { var ss []string f := setUpSSFlagSet(&ss) @@ -150,104 +133,9 @@ func TestSSCalledTwice(t *testing.T) { if err != nil { t.Fatal("expected no error; got", err) } - - if len(expected) != len(ss) { - t.Fatalf("expected number of ss to be %d but got: %d", len(expected), len(ss)) - } for i, v := range ss { if expected[i] != v { t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v) } } - - values, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(values) { - t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(ss)) - } - for i, v := range values { - if expected[i] != v { - t.Fatalf("expected got ss[%d] to be %s but got: %s", i, expected[i], v) - } - } -} - -func TestSSWithComma(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - - in := []string{`"one,two"`, `"three"`, `"four,five",six`} - expected := []string{"one,two", "three", "four,five", "six"} - argfmt := "--ss=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - arg3 := fmt.Sprintf(argfmt, in[2]) - err := f.Parse([]string{arg1, arg2, arg3}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(ss) { - t.Fatalf("expected number of ss to be %d but got: %d", len(expected), len(ss)) - } - for i, v := range ss { - if expected[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v) - } - } - - values, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(values) { - t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values)) - } - for i, v := range values { - if expected[i] != v { - t.Fatalf("expected got ss[%d] to be %s but got: %s", i, expected[i], v) - } - } -} - -func TestSSWithSquareBrackets(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - - in := []string{`"[a-z]"`, `"[a-z]+"`} - expected := []string{"[a-z]", "[a-z]+"} - argfmt := "--ss=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(ss) { - t.Fatalf("expected number of ss to be %d but got: %d", len(expected), len(ss)) - } - for i, v := range ss { - if expected[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v) - } - } - - values, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(values) { - t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values)) - } - for i, v := range values { - if expected[i] != v { - t.Fatalf("expected got ss[%d] to be %s but got: %s", i, expected[i], v) - } - } } diff --git a/vendor/github.com/spf13/pflag/uint.go b/vendor/github.com/spf13/pflag/uint.go index dcbc2b75..d6f8e5be 100644 --- a/vendor/github.com/spf13/pflag/uint.go +++ b/vendor/github.com/spf13/pflag/uint.go @@ -1,6 +1,9 @@ package pflag -import "strconv" +import ( + "fmt" + "strconv" +) // -- uint Value type uintValue uint @@ -20,7 +23,7 @@ func (i *uintValue) Type() string { return "uint" } -func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i), 10) } +func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) } func uintConv(sval string) (interface{}, error) { v, err := strconv.ParseUint(sval, 0, 0) @@ -45,7 +48,7 @@ func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) { f.VarP(newUintValue(value, p), name, "", usage) } -// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash. +// Like UintVar, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) UintVarP(p *uint, name, shorthand string, value uint, usage string) { f.VarP(newUintValue(value, p), name, shorthand, usage) } @@ -56,7 +59,7 @@ func UintVar(p *uint, name string, value uint, usage string) { CommandLine.VarP(newUintValue(value, p), name, "", usage) } -// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash. +// Like UintVar, but accepts a shorthand letter that can be used after a single dash. func UintVarP(p *uint, name, shorthand string, value uint, usage string) { CommandLine.VarP(newUintValue(value, p), name, shorthand, usage) } @@ -69,7 +72,7 @@ func (f *FlagSet) Uint(name string, value uint, usage string) *uint { return p } -// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash. +// Like Uint, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) UintP(name, shorthand string, value uint, usage string) *uint { p := new(uint) f.UintVarP(p, name, shorthand, value, usage) @@ -82,7 +85,7 @@ func Uint(name string, value uint, usage string) *uint { return CommandLine.UintP(name, "", value, usage) } -// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash. +// Like Uint, but accepts a shorthand letter that can be used after a single dash. func UintP(name, shorthand string, value uint, usage string) *uint { return CommandLine.UintP(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/uint16.go b/vendor/github.com/spf13/pflag/uint16.go index 7e9914ed..1cdc3dfb 100644 --- a/vendor/github.com/spf13/pflag/uint16.go +++ b/vendor/github.com/spf13/pflag/uint16.go @@ -1,6 +1,9 @@ package pflag -import "strconv" +import ( + "fmt" + "strconv" +) // -- uint16 value type uint16Value uint16 @@ -9,7 +12,7 @@ func newUint16Value(val uint16, p *uint16) *uint16Value { *p = val return (*uint16Value)(p) } - +func (i *uint16Value) String() string { return fmt.Sprintf("%d", *i) } func (i *uint16Value) Set(s string) error { v, err := strconv.ParseUint(s, 0, 16) *i = uint16Value(v) @@ -20,8 +23,6 @@ func (i *uint16Value) Type() string { return "uint16" } -func (i *uint16Value) String() string { return strconv.FormatUint(uint64(*i), 10) } - func uint16Conv(sval string) (interface{}, error) { v, err := strconv.ParseUint(sval, 0, 16) if err != nil { @@ -45,7 +46,7 @@ func (f *FlagSet) Uint16Var(p *uint16, name string, value uint16, usage string) f.VarP(newUint16Value(value, p), name, "", usage) } -// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash. +// Like Uint16Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) { f.VarP(newUint16Value(value, p), name, shorthand, usage) } @@ -56,7 +57,7 @@ func Uint16Var(p *uint16, name string, value uint16, usage string) { CommandLine.VarP(newUint16Value(value, p), name, "", usage) } -// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash. +// Like Uint16Var, but accepts a shorthand letter that can be used after a single dash. func Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) { CommandLine.VarP(newUint16Value(value, p), name, shorthand, usage) } @@ -69,7 +70,7 @@ func (f *FlagSet) Uint16(name string, value uint16, usage string) *uint16 { return p } -// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash. +// Like Uint16, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Uint16P(name, shorthand string, value uint16, usage string) *uint16 { p := new(uint16) f.Uint16VarP(p, name, shorthand, value, usage) @@ -82,7 +83,7 @@ func Uint16(name string, value uint16, usage string) *uint16 { return CommandLine.Uint16P(name, "", value, usage) } -// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash. +// Like Uint16, but accepts a shorthand letter that can be used after a single dash. func Uint16P(name, shorthand string, value uint16, usage string) *uint16 { return CommandLine.Uint16P(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/uint32.go b/vendor/github.com/spf13/pflag/uint32.go index d8024539..1326e4ab 100644 --- a/vendor/github.com/spf13/pflag/uint32.go +++ b/vendor/github.com/spf13/pflag/uint32.go @@ -1,15 +1,18 @@ package pflag -import "strconv" +import ( + "fmt" + "strconv" +) -// -- uint32 value +// -- uint16 value type uint32Value uint32 func newUint32Value(val uint32, p *uint32) *uint32Value { *p = val return (*uint32Value)(p) } - +func (i *uint32Value) String() string { return fmt.Sprintf("%d", *i) } func (i *uint32Value) Set(s string) error { v, err := strconv.ParseUint(s, 0, 32) *i = uint32Value(v) @@ -20,8 +23,6 @@ func (i *uint32Value) Type() string { return "uint32" } -func (i *uint32Value) String() string { return strconv.FormatUint(uint64(*i), 10) } - func uint32Conv(sval string) (interface{}, error) { v, err := strconv.ParseUint(sval, 0, 32) if err != nil { @@ -45,7 +46,7 @@ func (f *FlagSet) Uint32Var(p *uint32, name string, value uint32, usage string) f.VarP(newUint32Value(value, p), name, "", usage) } -// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash. +// Like Uint32Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) { f.VarP(newUint32Value(value, p), name, shorthand, usage) } @@ -56,7 +57,7 @@ func Uint32Var(p *uint32, name string, value uint32, usage string) { CommandLine.VarP(newUint32Value(value, p), name, "", usage) } -// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash. +// Like Uint32Var, but accepts a shorthand letter that can be used after a single dash. func Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) { CommandLine.VarP(newUint32Value(value, p), name, shorthand, usage) } @@ -69,7 +70,7 @@ func (f *FlagSet) Uint32(name string, value uint32, usage string) *uint32 { return p } -// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash. +// Like Uint32, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Uint32P(name, shorthand string, value uint32, usage string) *uint32 { p := new(uint32) f.Uint32VarP(p, name, shorthand, value, usage) @@ -82,7 +83,7 @@ func Uint32(name string, value uint32, usage string) *uint32 { return CommandLine.Uint32P(name, "", value, usage) } -// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash. +// Like Uint32, but accepts a shorthand letter that can be used after a single dash. func Uint32P(name, shorthand string, value uint32, usage string) *uint32 { return CommandLine.Uint32P(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/uint64.go b/vendor/github.com/spf13/pflag/uint64.go index f62240f2..6788bbf8 100644 --- a/vendor/github.com/spf13/pflag/uint64.go +++ b/vendor/github.com/spf13/pflag/uint64.go @@ -1,6 +1,9 @@ package pflag -import "strconv" +import ( + "fmt" + "strconv" +) // -- uint64 Value type uint64Value uint64 @@ -20,7 +23,7 @@ func (i *uint64Value) Type() string { return "uint64" } -func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i), 10) } +func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) } func uint64Conv(sval string) (interface{}, error) { v, err := strconv.ParseUint(sval, 0, 64) @@ -45,7 +48,7 @@ func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) f.VarP(newUint64Value(value, p), name, "", usage) } -// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash. +// Like Uint64Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) { f.VarP(newUint64Value(value, p), name, shorthand, usage) } @@ -56,7 +59,7 @@ func Uint64Var(p *uint64, name string, value uint64, usage string) { CommandLine.VarP(newUint64Value(value, p), name, "", usage) } -// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash. +// Like Uint64Var, but accepts a shorthand letter that can be used after a single dash. func Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) { CommandLine.VarP(newUint64Value(value, p), name, shorthand, usage) } @@ -69,7 +72,7 @@ func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 { return p } -// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash. +// Like Uint64, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Uint64P(name, shorthand string, value uint64, usage string) *uint64 { p := new(uint64) f.Uint64VarP(p, name, shorthand, value, usage) @@ -82,7 +85,7 @@ func Uint64(name string, value uint64, usage string) *uint64 { return CommandLine.Uint64P(name, "", value, usage) } -// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash. +// Like Uint64, but accepts a shorthand letter that can be used after a single dash. func Uint64P(name, shorthand string, value uint64, usage string) *uint64 { return CommandLine.Uint64P(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/uint8.go b/vendor/github.com/spf13/pflag/uint8.go index bb0e83c1..560c569b 100644 --- a/vendor/github.com/spf13/pflag/uint8.go +++ b/vendor/github.com/spf13/pflag/uint8.go @@ -1,6 +1,9 @@ package pflag -import "strconv" +import ( + "fmt" + "strconv" +) // -- uint8 Value type uint8Value uint8 @@ -20,7 +23,7 @@ func (i *uint8Value) Type() string { return "uint8" } -func (i *uint8Value) String() string { return strconv.FormatUint(uint64(*i), 10) } +func (i *uint8Value) String() string { return fmt.Sprintf("%v", *i) } func uint8Conv(sval string) (interface{}, error) { v, err := strconv.ParseUint(sval, 0, 8) @@ -45,7 +48,7 @@ func (f *FlagSet) Uint8Var(p *uint8, name string, value uint8, usage string) { f.VarP(newUint8Value(value, p), name, "", usage) } -// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash. +// Like Uint8Var, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) { f.VarP(newUint8Value(value, p), name, shorthand, usage) } @@ -56,7 +59,7 @@ func Uint8Var(p *uint8, name string, value uint8, usage string) { CommandLine.VarP(newUint8Value(value, p), name, "", usage) } -// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash. +// Like Uint8Var, but accepts a shorthand letter that can be used after a single dash. func Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) { CommandLine.VarP(newUint8Value(value, p), name, shorthand, usage) } @@ -69,7 +72,7 @@ func (f *FlagSet) Uint8(name string, value uint8, usage string) *uint8 { return p } -// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash. +// Like Uint8, but accepts a shorthand letter that can be used after a single dash. func (f *FlagSet) Uint8P(name, shorthand string, value uint8, usage string) *uint8 { p := new(uint8) f.Uint8VarP(p, name, shorthand, value, usage) @@ -82,7 +85,7 @@ func Uint8(name string, value uint8, usage string) *uint8 { return CommandLine.Uint8P(name, "", value, usage) } -// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash. +// Like Uint8, but accepts a shorthand letter that can be used after a single dash. func Uint8P(name, shorthand string, value uint8, usage string) *uint8 { return CommandLine.Uint8P(name, shorthand, value, usage) } diff --git a/vendor/github.com/spf13/pflag/uint_slice.go b/vendor/github.com/spf13/pflag/uint_slice.go deleted file mode 100644 index edd94c60..00000000 --- a/vendor/github.com/spf13/pflag/uint_slice.go +++ /dev/null @@ -1,126 +0,0 @@ -package pflag - -import ( - "fmt" - "strconv" - "strings" -) - -// -- uintSlice Value -type uintSliceValue struct { - value *[]uint - changed bool -} - -func newUintSliceValue(val []uint, p *[]uint) *uintSliceValue { - uisv := new(uintSliceValue) - uisv.value = p - *uisv.value = val - return uisv -} - -func (s *uintSliceValue) Set(val string) error { - ss := strings.Split(val, ",") - out := make([]uint, len(ss)) - for i, d := range ss { - u, err := strconv.ParseUint(d, 10, 0) - if err != nil { - return err - } - out[i] = uint(u) - } - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - s.changed = true - return nil -} - -func (s *uintSliceValue) Type() string { - return "uintSlice" -} - -func (s *uintSliceValue) String() string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = fmt.Sprintf("%d", d) - } - return "[" + strings.Join(out, ",") + "]" -} - -func uintSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []uint{}, nil - } - ss := strings.Split(val, ",") - out := make([]uint, len(ss)) - for i, d := range ss { - u, err := strconv.ParseUint(d, 10, 0) - if err != nil { - return nil, err - } - out[i] = uint(u) - } - return out, nil -} - -// GetUintSlice returns the []uint value of a flag with the given name. -func (f *FlagSet) GetUintSlice(name string) ([]uint, error) { - val, err := f.getFlagType(name, "uintSlice", uintSliceConv) - if err != nil { - return []uint{}, err - } - return val.([]uint), nil -} - -// UintSliceVar defines a uintSlice flag with specified name, default value, and usage string. -// The argument p points to a []uint variable in which to store the value of the flag. -func (f *FlagSet) UintSliceVar(p *[]uint, name string, value []uint, usage string) { - f.VarP(newUintSliceValue(value, p), name, "", usage) -} - -// UintSliceVarP is like UintSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) { - f.VarP(newUintSliceValue(value, p), name, shorthand, usage) -} - -// UintSliceVar defines a uint[] flag with specified name, default value, and usage string. -// The argument p points to a uint[] variable in which to store the value of the flag. -func UintSliceVar(p *[]uint, name string, value []uint, usage string) { - CommandLine.VarP(newUintSliceValue(value, p), name, "", usage) -} - -// UintSliceVarP is like the UintSliceVar, but accepts a shorthand letter that can be used after a single dash. -func UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) { - CommandLine.VarP(newUintSliceValue(value, p), name, shorthand, usage) -} - -// UintSlice defines a []uint flag with specified name, default value, and usage string. -// The return value is the address of a []uint variable that stores the value of the flag. -func (f *FlagSet) UintSlice(name string, value []uint, usage string) *[]uint { - p := []uint{} - f.UintSliceVarP(&p, name, "", value, usage) - return &p -} - -// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) UintSliceP(name, shorthand string, value []uint, usage string) *[]uint { - p := []uint{} - f.UintSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// UintSlice defines a []uint flag with specified name, default value, and usage string. -// The return value is the address of a []uint variable that stores the value of the flag. -func UintSlice(name string, value []uint, usage string) *[]uint { - return CommandLine.UintSliceP(name, "", value, usage) -} - -// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash. -func UintSliceP(name, shorthand string, value []uint, usage string) *[]uint { - return CommandLine.UintSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint_slice_test.go b/vendor/github.com/spf13/pflag/uint_slice_test.go deleted file mode 100644 index db1a19dc..00000000 --- a/vendor/github.com/spf13/pflag/uint_slice_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package pflag - -import ( - "fmt" - "strconv" - "strings" - "testing" -) - -func setUpUISFlagSet(uisp *[]uint) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.UintSliceVar(uisp, "uis", []uint{}, "Command separated list!") - return f -} - -func setUpUISFlagSetWithDefault(uisp *[]uint) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.UintSliceVar(uisp, "uis", []uint{0, 1}, "Command separated list!") - return f -} - -func TestEmptyUIS(t *testing.T) { - var uis []uint - f := setUpUISFlagSet(&uis) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getUIS, err := f.GetUintSlice("uis") - if err != nil { - t.Fatal("got an error from GetUintSlice():", err) - } - if len(getUIS) != 0 { - t.Fatalf("got is %v with len=%d but expected length=0", getUIS, len(getUIS)) - } -} - -func TestUIS(t *testing.T) { - var uis []uint - f := setUpUISFlagSet(&uis) - - vals := []string{"1", "2", "4", "3"} - arg := fmt.Sprintf("--uis=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range uis { - u, err := strconv.ParseUint(vals[i], 10, 0) - if err != nil { - t.Fatalf("got error: %v", err) - } - if uint(u) != v { - t.Fatalf("expected uis[%d] to be %s but got %d", i, vals[i], v) - } - } - getUIS, err := f.GetUintSlice("uis") - if err != nil { - t.Fatalf("got error: %v", err) - } - for i, v := range getUIS { - u, err := strconv.ParseUint(vals[i], 10, 0) - if err != nil { - t.Fatalf("got error: %v", err) - } - if uint(u) != v { - t.Fatalf("expected uis[%d] to be %s but got: %d from GetUintSlice", i, vals[i], v) - } - } -} - -func TestUISDefault(t *testing.T) { - var uis []uint - f := setUpUISFlagSetWithDefault(&uis) - - vals := []string{"0", "1"} - - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range uis { - u, err := strconv.ParseUint(vals[i], 10, 0) - if err != nil { - t.Fatalf("got error: %v", err) - } - if uint(u) != v { - t.Fatalf("expect uis[%d] to be %d but got: %d", i, u, v) - } - } - - getUIS, err := f.GetUintSlice("uis") - if err != nil { - t.Fatal("got an error from GetUintSlice():", err) - } - for i, v := range getUIS { - u, err := strconv.ParseUint(vals[i], 10, 0) - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - if uint(u) != v { - t.Fatalf("expected uis[%d] to be %d from GetUintSlice but got: %d", i, u, v) - } - } -} - -func TestUISWithDefault(t *testing.T) { - var uis []uint - f := setUpUISFlagSetWithDefault(&uis) - - vals := []string{"1", "2"} - arg := fmt.Sprintf("--uis=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range uis { - u, err := strconv.ParseUint(vals[i], 10, 0) - if err != nil { - t.Fatalf("got error: %v", err) - } - if uint(u) != v { - t.Fatalf("expected uis[%d] to be %d from GetUintSlice but got: %d", i, u, v) - } - } - - getUIS, err := f.GetUintSlice("uis") - if err != nil { - t.Fatal("got an error from GetUintSlice():", err) - } - for i, v := range getUIS { - u, err := strconv.ParseUint(vals[i], 10, 0) - if err != nil { - t.Fatalf("got error: %v", err) - } - if uint(u) != v { - t.Fatalf("expected uis[%d] to be %d from GetUintSlice but got: %d", i, u, v) - } - } -} - -func TestUISCalledTwice(t *testing.T) { - var uis []uint - f := setUpUISFlagSet(&uis) - - in := []string{"1,2", "3"} - expected := []int{1, 2, 3} - argfmt := "--uis=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range uis { - if uint(expected[i]) != v { - t.Fatalf("expected uis[%d] to be %d but got: %d", i, expected[i], v) - } - } -} diff --git a/vendor/github.com/spf13/pflag/verify/all.sh b/vendor/github.com/spf13/pflag/verify/all.sh deleted file mode 100755 index 739f89c0..00000000 --- a/vendor/github.com/spf13/pflag/verify/all.sh +++ /dev/null @@ -1,69 +0,0 @@ -#!/bin/bash - -set -o errexit -set -o nounset -set -o pipefail - -ROOT=$(dirname "${BASH_SOURCE}")/.. - -# Some useful colors. -if [[ -z "${color_start-}" ]]; then - declare -r color_start="\033[" - declare -r color_red="${color_start}0;31m" - declare -r color_yellow="${color_start}0;33m" - declare -r color_green="${color_start}0;32m" - declare -r color_norm="${color_start}0m" -fi - -SILENT=true - -function is-excluded { - for e in $EXCLUDE; do - if [[ $1 -ef ${BASH_SOURCE} ]]; then - return - fi - if [[ $1 -ef "$ROOT/hack/$e" ]]; then - return - fi - done - return 1 -} - -while getopts ":v" opt; do - case $opt in - v) - SILENT=false - ;; - \?) - echo "Invalid flag: -$OPTARG" >&2 - exit 1 - ;; - esac -done - -if $SILENT ; then - echo "Running in the silent mode, run with -v if you want to see script logs." -fi - -EXCLUDE="all.sh" - -ret=0 -for t in `ls $ROOT/verify/*.sh` -do - if is-excluded $t ; then - echo "Skipping $t" - continue - fi - if $SILENT ; then - echo -e "Verifying $t" - if bash "$t" &> /dev/null; then - echo -e "${color_green}SUCCESS${color_norm}" - else - echo -e "${color_red}FAILED${color_norm}" - ret=1 - fi - else - bash "$t" || ret=1 - fi -done -exit $ret diff --git a/vendor/github.com/spf13/pflag/verify/gofmt.sh b/vendor/github.com/spf13/pflag/verify/gofmt.sh deleted file mode 100755 index f66acf80..00000000 --- a/vendor/github.com/spf13/pflag/verify/gofmt.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/bash - -set -o errexit -set -o nounset -set -o pipefail - -ROOT=$(dirname "${BASH_SOURCE}")/.. - -pushd "${ROOT}" > /dev/null - -GOFMT=${GOFMT:-"gofmt"} -bad_files=$(find . -name '*.go' | xargs $GOFMT -s -l) -if [[ -n "${bad_files}" ]]; then - echo "!!! '$GOFMT' needs to be run on the following files: " - echo "${bad_files}" - exit 1 -fi - -# ex: ts=2 sw=2 et filetype=sh diff --git a/vendor/github.com/spf13/pflag/verify/golint.sh b/vendor/github.com/spf13/pflag/verify/golint.sh deleted file mode 100755 index 685c1778..00000000 --- a/vendor/github.com/spf13/pflag/verify/golint.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/bash - -ROOT=$(dirname "${BASH_SOURCE}")/.. -GOLINT=${GOLINT:-"golint"} - -pushd "${ROOT}" > /dev/null - bad_files=$($GOLINT -min_confidence=0.9 ./...) - if [[ -n "${bad_files}" ]]; then - echo "!!! '$GOLINT' problems: " - echo "${bad_files}" - exit 1 - fi -popd > /dev/null - -# ex: ts=2 sw=2 et filetype=sh From 1c665a3534b482f9c90d9ed66ad9d04552bf3aae Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 21 May 2018 18:19:33 -0700 Subject: [PATCH 46/94] commands/run.go: make --version synonymous with version() --- commands/run.go | 8 +++++++- test/test-version.sh | 23 +++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100755 test/test-version.sh diff --git a/commands/run.go b/commands/run.go index de7409a0..823e76b2 100644 --- a/commands/run.go +++ b/commands/run.go @@ -16,6 +16,8 @@ import ( var ( commandFuncs []func() *cobra.Command commandMu sync.Mutex + + rootVersion bool ) // NewCommand creates a new 'git-lfs' sub command, given a command name and @@ -62,6 +64,8 @@ func Run() int { root.SetHelpFunc(helpCommand) root.SetUsageFunc(usageCommand) + root.Flags().BoolVarP(&rootVersion, "version", "v", false, "") + cfg = config.New() for _, f := range commandFuncs { @@ -81,7 +85,9 @@ func Run() int { func gitlfsCommand(cmd *cobra.Command, args []string) { versionCommand(cmd, args) - cmd.Usage() + if !rootVersion { + cmd.Usage() + } } func helpCommand(cmd *cobra.Command, args []string) { diff --git a/test/test-version.sh b/test/test-version.sh new file mode 100755 index 00000000..31dfdb7f --- /dev/null +++ b/test/test-version.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +. "test/testlib.sh" + +begin_test "git lfs --version is a synonym of git lfs version" +( + set -e + + reponame="git-lfs-version-synonymous" + mkdir "$reponame" + cd "$reponame" + + git lfs version 2>&1 >version.log + git lfs --version 2>&1 >flag.log + + if [ "$(cat version.log)" != "$(cat flag.log)" ]; then + echo >&2 "fatal: expected 'git lfs version' and 'git lfs --version' to" + echo >&2 "produce identical output ..." + + diff -u {version,flag}.log + fi +) +end_test From 9820f20d912074f7eede050255be2e123f2a3e66 Mon Sep 17 00:00:00 2001 From: Preben Ingvaldsen Date: Tue, 22 May 2018 11:12:40 -0700 Subject: [PATCH 47/94] commands: teach --no-rewrite flag to 'migrate-import' --- commands/command_migrate.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/commands/command_migrate.go b/commands/command_migrate.go index 391524cd..4a692a9d 100644 --- a/commands/command_migrate.go +++ b/commands/command_migrate.go @@ -36,6 +36,10 @@ var ( // objectMapFile is the path to the map of old sha1 to new sha1 // commits objectMapFilePath string + + // migrateNoRewrite is the flag indicating whether or not the + // command should rewrite git history + migrateNoRewrite bool ) // migrate takes the given command and arguments, *odb.ObjectDatabase, as well @@ -287,6 +291,7 @@ func init() { importCmd := NewCommand("import", migrateImportCommand) importCmd.Flags().BoolVar(&migrateVerbose, "verbose", false, "Verbose logging") importCmd.Flags().StringVar(&objectMapFilePath, "object-map", "", "Object map file") + importCmd.Flags().BoolVar(&migrateNoRewrite, "no-rewrite", false, "Add new history without rewriting previous") RegisterCommand("migrate", nil, func(cmd *cobra.Command) { cmd.PersistentFlags().StringVarP(&includeArg, "include", "I", "", "Include a list of paths") From bbcea3df62a4f74be6b6f6cda95c30d832a74bcc Mon Sep 17 00:00:00 2001 From: Preben Ingvaldsen Date: Wed, 23 May 2018 09:36:36 -0700 Subject: [PATCH 48/94] commands: create new commit with --no-rewrite Allow `migrate import` command to create a new commit without modifying git history when using the --no-rewrite flag --- commands/command_migrate.go | 4 ++ commands/command_migrate_import.go | 97 +++++++++++++++++++++++++++--- 2 files changed, 91 insertions(+), 10 deletions(-) diff --git a/commands/command_migrate.go b/commands/command_migrate.go index 4a692a9d..fe35c2f8 100644 --- a/commands/command_migrate.go +++ b/commands/command_migrate.go @@ -40,6 +40,9 @@ var ( // migrateNoRewrite is the flag indicating whether or not the // command should rewrite git history migrateNoRewrite bool + // migrateCommitMessage is the message to use with the commit generated + // by the migrate command + migrateCommitMessage string ) // migrate takes the given command and arguments, *odb.ObjectDatabase, as well @@ -292,6 +295,7 @@ func init() { importCmd.Flags().BoolVar(&migrateVerbose, "verbose", false, "Verbose logging") importCmd.Flags().StringVar(&objectMapFilePath, "object-map", "", "Object map file") importCmd.Flags().BoolVar(&migrateNoRewrite, "no-rewrite", false, "Add new history without rewriting previous") + importCmd.Flags().StringVarP(&migrateCommitMessage, "message", "m", "", "With --no-rewrite, an optional commit message") RegisterCommand("migrate", nil, func(cmd *cobra.Command) { cmd.PersistentFlags().StringVarP(&includeArg, "include", "I", "", "Include a list of paths") diff --git a/commands/command_migrate_import.go b/commands/command_migrate_import.go index 3c75c972..bfd905fe 100644 --- a/commands/command_migrate_import.go +++ b/commands/command_migrate_import.go @@ -9,6 +9,7 @@ import ( "path/filepath" "strings" + "github.com/git-lfs/git-lfs/errors" "github.com/git-lfs/git-lfs/filepathfilter" "github.com/git-lfs/git-lfs/git" "github.com/git-lfs/git-lfs/git/githistory" @@ -29,6 +30,59 @@ func migrateImportCommand(cmd *cobra.Command, args []string) { } defer db.Close() + if migrateNoRewrite { + ref, err := git.CurrentRef() + if err != nil { + ExitWithError(errors.Wrap(err, "fatal: unable to find current reference")) + } + + sha, _ := hex.DecodeString(ref.Sha) + commit, err := db.Commit(sha) + if err != nil { + ExitWithError(errors.Wrap(err, "fatal: unable to load commit")) + } + + root := commit.TreeID + + include, _ := getIncludeExcludeArgs(cmd) + paths, _ := determineIncludeExcludePaths(cfg, include, nil) + if len(paths) == 0 { + ExitWithError(errors.New("fatal: no matching paths found")) + } + + for _, path := range paths { + root, err = rewriteTree(db, root, path) + if err != nil { + ExitWithError(errors.Wrapf(err, "fatal: could not rewrite %q", path)) + } + } + + name, email := cfg.CurrentCommitter() + author := fmt.Sprintf("%s <%s>", name, email) + + oid, err := db.WriteCommit(&odb.Commit{ + Author: author, + Committer: author, + ParentIDs: [][]byte{sha}, + Message: generateMigrateCommitMessage(cmd, include), + TreeID: root, + }) + + if err != nil { + ExitWithError(errors.Wrap(err, "fatal: unable to write commit")) + } + + if err := git.UpdateRef(ref, oid, "git lfs migrate import --no-rewrite"); err != nil { + ExitWithError(errors.Wrap(err, "fatal: unable to update ref")) + } + + if err := checkoutNonBare(l); err != nil { + ExitWithError(errors.Wrap(err, "fatal: could not checkout")) + } + + return + } + rewriter := getHistoryRewriter(cmd, db, l) tracked := trackedFromFilter(rewriter.Filter()) @@ -104,19 +158,38 @@ func migrateImportCommand(cmd *cobra.Command, args []string) { UpdateRefs: true, }) - // Only perform `git-checkout(1) -f` if the repository is - // non-bare. - if bare, _ := git.IsBare(); !bare { - t := l.Waiter("migrate: checkout") - err := git.Checkout("", nil, true) - t.Complete() - - if err != nil { - ExitWithError(err) - } + if err := checkoutNonBare(l); err != nil { + ExitWithError(errors.Wrap(err, "fatal: could not checkout")) } } +// generateMigrateCommitMessage generates a commit message used with +// --no-rewrite, using --message (if given) or generating one if it isn't. +func generateMigrateCommitMessage(cmd *cobra.Command, patterns *string) string { + if cmd.Flag("message").Changed { + return migrateCommitMessage + } + if patterns != nil { + return fmt.Sprintf("%s: convert to Git LFS", *patterns) + } + panic("unexpected") +} + +// checkoutNonBare forces a checkout of the current reference, so long as the +// repository is non-bare. +// +// It returns nil on success, and a non-nil error on failure. +func checkoutNonBare(l *tasklog.Logger) error { + if bare, _ := git.IsBare(); bare { + return nil + } + + t := l.Waiter("migrate: checkout") + defer t.Complete() + + return git.Checkout("", nil, true) +} + // trackedFromFilter returns an ordered set of strings where each entry is a // line in the .gitattributes file. It adds/removes the fiter/diff/merge=lfs // attributes based on patterns included/excldued in the given filter. @@ -202,3 +275,7 @@ func trackedToBlob(db *odb.ObjectDatabase, patterns *tools.OrderedSet) ([]byte, Size: int64(attrs.Len()), }) } + +func rewriteTree(db *odb.ObjectDatabase, root []byte, path string) ([]byte, error) { + return root, nil +} From 9632eb9bd8c6a4169d075f63e21fcf92427110d1 Mon Sep 17 00:00:00 2001 From: Preben Ingvaldsen Date: Thu, 24 May 2018 10:46:59 -0700 Subject: [PATCH 49/94] commands: rewrite tree with --no-rewrite Allow the `migrate import` command to convert blobs to git-lfs pointers by rewriting the tree in a new commit without touching git history --- commands/command_migrate_import.go | 134 +++++++++++++++++++++++++++-- 1 file changed, 129 insertions(+), 5 deletions(-) diff --git a/commands/command_migrate_import.go b/commands/command_migrate_import.go index bfd905fe..dc48e66b 100644 --- a/commands/command_migrate_import.go +++ b/commands/command_migrate_import.go @@ -50,10 +50,18 @@ func migrateImportCommand(cmd *cobra.Command, args []string) { ExitWithError(errors.New("fatal: no matching paths found")) } - for _, path := range paths { - root, err = rewriteTree(db, root, path) - if err != nil { - ExitWithError(errors.Wrapf(err, "fatal: could not rewrite %q", path)) + entries, err := listEntries(db, root, "") + if err != nil { + ExitWithError(errors.Wrap(err, "fatal: unable to list tree entries")) + } + + filter := filepathfilter.New(paths, nil) + for _, entry := range entries { + if filter.Allows(entry) { + root, err = rewriteTree(db, root, entry) + if err != nil { + ExitWithError(errors.Wrapf(err, "fatal: could not rewrite %q", entry)) + } } } @@ -276,6 +284,122 @@ func trackedToBlob(db *odb.ObjectDatabase, patterns *tools.OrderedSet) ([]byte, }) } +// rewriteTree replaces the blob at the provided path within the given tree with +// a git lfs pointer. It will recursively rewrite any subtrees along the path to the +// blob. func rewriteTree(db *odb.ObjectDatabase, root []byte, path string) ([]byte, error) { - return root, nil + tree, err := db.Tree(root) + if err != nil { + return nil, err + } + + splits := strings.SplitN(path, "/", 2) + + switch len(splits) { + case 1: + // The path points to an entry at the root of this tree, so it must be a blob. + // Try to replace this blob with a git lfs pointer. + index := findEntry(tree, splits[0]) + if index < 0 { + return nil, errors.Errorf("unable to find entry %s in tree", splits[0]) + } + + blobEntry := tree.Entries[index] + blob, err := db.Blob(blobEntry.Oid) + if err != nil { + return nil, err + } + + var buf bytes.Buffer + + if _, err := clean(lfs.NewGitFilter(cfg), &buf, blob.Contents, blobEntry.Name, blob.Size); err != nil { + return nil, err + } + + newBlob := odb.Blob{ + Contents: &buf, + Size: int64(buf.Len()), + } + + newOid, err := db.WriteBlob(&newBlob) + if err != nil { + return nil, err + } + + newEntry := odb.TreeEntry{ + Name: splits[0], + Filemode: blobEntry.Filemode, + Oid: newOid, + } + tree = tree.Merge(&newEntry) + return db.WriteTree(tree) + + case 2: + // The path points to an entry in a subtree contained at the root of the tree. + // Recursively rewrite the subtree. + head, tail := splits[0], splits[1] + + index := findEntry(tree, head) + if index < 0 { + return nil, errors.Errorf("unable to find entry %s in tree", head) + } + + subtreeEntry := tree.Entries[index] + if subtreeEntry.Type() != odb.TreeObjectType { + return nil, errors.Errorf("migrate: expected %s to be a tree, got %s", head, subtreeEntry.Type()) + } + + rewrittenSubtree, err := rewriteTree(db, subtreeEntry.Oid, tail) + if err != nil { + return nil, err + } + + tree = tree.Merge(&odb.TreeEntry{ + Filemode: subtreeEntry.Filemode, + Name: subtreeEntry.Name, + Oid: rewrittenSubtree, + }) + + return db.WriteTree(tree) + + default: + return nil, errors.Errorf("error parsing path %s", path) + } +} + +// findEntry searches a tree for the desired entry, and returns the +// index of that entry within the tree's Entries array +func findEntry(t *odb.Tree, name string) int { + for i, entry := range t.Entries { + if entry.Name == name { + return i + } + } + + return -1 +} + +// listEntries returns an array with the full paths to all blobs within the provided tree. +func listEntries(db *odb.ObjectDatabase, id []byte, parent string) ([]string, error) { + t, err := db.Tree(id) + if err != nil { + return nil, err + } + + names := make([]string, 0, len(t.Entries)) + + for _, e := range t.Entries { + switch e.Type() { + case odb.BlobObjectType: + names = append(names, fmt.Sprintf("%s%s", parent, e.Name)) + case odb.TreeObjectType: + sub, err := listEntries(db, e.Oid, fmt.Sprintf("%s%s/", parent, e.Name)) + if err != nil { + return nil, err + } + names = append(names, sub...) + } + } + + return names, nil } From 1a3a19cfd8304f3ff6f3e70acade3be53eced61f Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 25 May 2018 09:11:22 -0700 Subject: [PATCH 50/94] lfsapi: teach do() to track requests via when redirected --- lfsapi/auth.go | 6 +++--- lfsapi/client.go | 6 +++--- lfsapi/ntlm.go | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/lfsapi/auth.go b/lfsapi/auth.go index 837e217b..71aa69fb 100644 --- a/lfsapi/auth.go +++ b/lfsapi/auth.go @@ -31,7 +31,7 @@ func (c *Client) DoWithAuth(remote string, req *http.Request) (*http.Response, e return nil, err } - res, err := c.doWithCreds(req, credHelper, creds, credsURL, access) + res, err := c.doWithCreds(req, credHelper, creds, credsURL, access, nil) if err != nil { if errors.IsAuthError(err) { newAccess := getAuthAccess(res) @@ -57,11 +57,11 @@ func (c *Client) DoWithAuth(remote string, req *http.Request) (*http.Response, e return res, err } -func (c *Client) doWithCreds(req *http.Request, credHelper CredentialHelper, creds Creds, credsURL *url.URL, access Access) (*http.Response, error) { +func (c *Client) doWithCreds(req *http.Request, credHelper CredentialHelper, creds Creds, credsURL *url.URL, access Access, via []*http.Request) (*http.Response, error) { if access == NTLMAccess { return c.doWithNTLM(req, credHelper, creds, credsURL) } - return c.do(req) + return c.do(req, via) } // getCreds fills the authorization header for the given request if possible, diff --git a/lfsapi/client.go b/lfsapi/client.go index 222a9a5c..82dc0f4a 100644 --- a/lfsapi/client.go +++ b/lfsapi/client.go @@ -96,16 +96,16 @@ func joinURL(prefix, suffix string) string { func (c *Client) Do(req *http.Request) (*http.Response, error) { req.Header = c.extraHeadersFor(req) - return c.do(req) + return c.do(req, nil) } // do performs an *http.Request respecting redirects, and handles the response // as defined in c.handleResponse. Notably, it does not alter the headers for // the request argument in any way. -func (c *Client) do(req *http.Request) (*http.Response, error) { +func (c *Client) do(req *http.Request, via []*http.Request) (*http.Response, error) { req.Header.Set("User-Agent", UserAgent) - res, err := c.doWithRedirects(c.httpClient(req.Host), req, nil) + res, err := c.doWithRedirects(c.httpClient(req.Host), req, via) if err != nil { return res, err } diff --git a/lfsapi/ntlm.go b/lfsapi/ntlm.go index 10b1ae7c..e177bbe1 100644 --- a/lfsapi/ntlm.go +++ b/lfsapi/ntlm.go @@ -19,7 +19,7 @@ type ntmlCredentials struct { } func (c *Client) doWithNTLM(req *http.Request, credHelper CredentialHelper, creds Creds, credsURL *url.URL) (*http.Response, error) { - res, err := c.do(req) + res, err := c.do(req, nil) if err != nil && !errors.IsAuthError(err) { return res, err } @@ -86,7 +86,7 @@ func (c *Client) ntlmSendMessage(req *http.Request, message []byte) (*http.Respo msg := base64.StdEncoding.EncodeToString(message) req.Header.Set("Authorization", "NTLM "+msg) - return c.do(req) + return c.do(req, nil) } func parseChallengeResponse(res *http.Response) ([]byte, error) { From b1c2b4212206f4f91ef51d68efb3b55257879e38 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 25 May 2018 09:24:15 -0700 Subject: [PATCH 51/94] lfsapi: teach do() and friends 'remote' --- lfsapi/auth.go | 2 +- lfsapi/client.go | 10 +++++----- lfsapi/ntlm.go | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/lfsapi/auth.go b/lfsapi/auth.go index 71aa69fb..4356c2e2 100644 --- a/lfsapi/auth.go +++ b/lfsapi/auth.go @@ -61,7 +61,7 @@ func (c *Client) doWithCreds(req *http.Request, credHelper CredentialHelper, cre if access == NTLMAccess { return c.doWithNTLM(req, credHelper, creds, credsURL) } - return c.do(req, via) + return c.do(req, "", via) } // getCreds fills the authorization header for the given request if possible, diff --git a/lfsapi/client.go b/lfsapi/client.go index 82dc0f4a..488cddf6 100644 --- a/lfsapi/client.go +++ b/lfsapi/client.go @@ -96,16 +96,16 @@ func joinURL(prefix, suffix string) string { func (c *Client) Do(req *http.Request) (*http.Response, error) { req.Header = c.extraHeadersFor(req) - return c.do(req, nil) + return c.do(req, "", nil) } // do performs an *http.Request respecting redirects, and handles the response // as defined in c.handleResponse. Notably, it does not alter the headers for // the request argument in any way. -func (c *Client) do(req *http.Request, via []*http.Request) (*http.Response, error) { +func (c *Client) do(req *http.Request, remote string, via []*http.Request) (*http.Response, error) { req.Header.Set("User-Agent", UserAgent) - res, err := c.doWithRedirects(c.httpClient(req.Host), req, via) + res, err := c.doWithRedirects(c.httpClient(req.Host), req, remote, via) if err != nil { return res, err } @@ -161,7 +161,7 @@ func (c *Client) extraHeaders(u *url.URL) map[string][]string { return m } -func (c *Client) doWithRedirects(cli *http.Client, req *http.Request, via []*http.Request) (*http.Response, error) { +func (c *Client) doWithRedirects(cli *http.Client, req *http.Request, remote string, via []*http.Request) (*http.Response, error) { tracedReq, err := c.traceRequest(req) if err != nil { return nil, err @@ -231,7 +231,7 @@ func (c *Client) doWithRedirects(cli *http.Client, req *http.Request, via []*htt return res, err } - return c.doWithRedirects(cli, redirectedReq, via) + return c.doWithRedirects(cli, redirectedReq, remote, via) } func (c *Client) httpClient(host string) *http.Client { diff --git a/lfsapi/ntlm.go b/lfsapi/ntlm.go index e177bbe1..0170bb93 100644 --- a/lfsapi/ntlm.go +++ b/lfsapi/ntlm.go @@ -19,7 +19,7 @@ type ntmlCredentials struct { } func (c *Client) doWithNTLM(req *http.Request, credHelper CredentialHelper, creds Creds, credsURL *url.URL) (*http.Response, error) { - res, err := c.do(req, nil) + res, err := c.do(req, "", nil) if err != nil && !errors.IsAuthError(err) { return res, err } @@ -86,7 +86,7 @@ func (c *Client) ntlmSendMessage(req *http.Request, message []byte) (*http.Respo msg := base64.StdEncoding.EncodeToString(message) req.Header.Set("Authorization", "NTLM "+msg) - return c.do(req, nil) + return c.do(req, "", nil) } func parseChallengeResponse(res *http.Response) ([]byte, error) { From 5257e587e4f8b0f03b5a86cb0da9baae8522883f Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 25 May 2018 09:24:36 -0700 Subject: [PATCH 52/94] lfsapi: re-authenticated redirected requests when needed --- lfsapi/auth.go | 12 +++++++++++- lfsapi/client.go | 7 +++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/lfsapi/auth.go b/lfsapi/auth.go index 4356c2e2..1c351268 100644 --- a/lfsapi/auth.go +++ b/lfsapi/auth.go @@ -24,6 +24,10 @@ var ( // authentication from netrc or git's credential helpers if necessary, // supporting basic and ntlm authentication. func (c *Client) DoWithAuth(remote string, req *http.Request) (*http.Response, error) { + return c.doWithAuth(remote, req, nil) +} + +func (c *Client) doWithAuth(remote string, req *http.Request, via []*http.Request) (*http.Response, error) { req.Header = c.extraHeadersFor(req) apiEndpoint, access, credHelper, credsURL, creds, err := c.getCreds(remote, req) @@ -31,7 +35,7 @@ func (c *Client) DoWithAuth(remote string, req *http.Request) (*http.Response, e return nil, err } - res, err := c.doWithCreds(req, credHelper, creds, credsURL, access, nil) + res, err := c.doWithCreds(req, credHelper, creds, credsURL, access, via) if err != nil { if errors.IsAuthError(err) { newAccess := getAuthAccess(res) @@ -45,6 +49,12 @@ func (c *Client) DoWithAuth(remote string, req *http.Request) (*http.Response, e req.Header.Del("Authorization") credHelper.Reject(creds) } + + // This case represents a rejected request that + // should have been authenticated but wasn't. Do + // not count this against our redirection + // maximum, so do not recur through doWithAuth + // and instead call DoWithAuth. return c.DoWithAuth(remote, req) } } diff --git a/lfsapi/client.go b/lfsapi/client.go index 488cddf6..bea88a0b 100644 --- a/lfsapi/client.go +++ b/lfsapi/client.go @@ -231,6 +231,13 @@ func (c *Client) doWithRedirects(cli *http.Client, req *http.Request, remote str return res, err } + if len(req.Header.Get("Authorization")) > 0 { + // If the original request was authenticated (noted by the + // presence of the Authorization header), then recur through + // doWithAuth, retaining the requests via but only after + // authenticating the redirected request. + return c.doWithAuth(remote, redirectedReq, via) + } return c.doWithRedirects(cli, redirectedReq, remote, via) } From 058368ccd0fe11843fa20ea9314a4f6e45d16894 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 25 May 2018 11:55:39 -0700 Subject: [PATCH 53/94] *: use patched version of bgetnry/go-netrc --- config/netrc.go | 2 +- glide.lock | 12 +++---- glide.yaml | 4 +-- lfsapi/auth.go | 2 +- lfsapi/netrc.go | 2 +- lfsapi/netrc_test.go | 2 +- test/test-credentials.sh | 35 ++++++++++++++++++- .../{bgentry => git-lfs}/go-netrc/.hgignore | 0 .../{bgentry => git-lfs}/go-netrc/LICENSE | 0 .../{bgentry => git-lfs}/go-netrc/README.md | 0 .../netrc/examples/bad_default_order.netrc | 0 .../go-netrc/netrc/examples/good.netrc | 8 ++++- .../go-netrc/netrc/netrc.go | 9 +++-- .../go-netrc/netrc/netrc_test.go | 3 +- 14 files changed, 61 insertions(+), 18 deletions(-) rename vendor/github.com/{bgentry => git-lfs}/go-netrc/.hgignore (100%) rename vendor/github.com/{bgentry => git-lfs}/go-netrc/LICENSE (100%) rename vendor/github.com/{bgentry => git-lfs}/go-netrc/README.md (100%) rename vendor/github.com/{bgentry => git-lfs}/go-netrc/netrc/examples/bad_default_order.netrc (100%) rename vendor/github.com/{bgentry => git-lfs}/go-netrc/netrc/examples/good.netrc (66%) rename vendor/github.com/{bgentry => git-lfs}/go-netrc/netrc/netrc.go (98%) rename vendor/github.com/{bgentry => git-lfs}/go-netrc/netrc/netrc_test.go (99%) diff --git a/config/netrc.go b/config/netrc.go index 27156459..004755cd 100644 --- a/config/netrc.go +++ b/config/netrc.go @@ -4,7 +4,7 @@ import ( "os" "path/filepath" - "github.com/bgentry/go-netrc/netrc" + "github.com/git-lfs/go-netrc/netrc" ) type netrcfinder interface { diff --git a/glide.lock b/glide.lock index a4cb1f48..7ceb2f1a 100644 --- a/glide.lock +++ b/glide.lock @@ -1,18 +1,18 @@ -hash: bad2138ca7787101a7a23af2464319cc580f4285e90c07d11eb9f90ad3bb9604 -updated: 2018-02-27T14:39:39.133796-08:00 +hash: 3603b2885070c06a5a5b066ffb9f82335dc11e9698c5b9e5c0e782ad58e79af6 +updated: 2018-05-25T12:41:49.056975-07:00 imports: - name: github.com/alexbrainman/sspi version: 4729b3d4d8581b2db83864d1018926e4154f9406 subpackages: - ntlm -- name: github.com/bgentry/go-netrc - version: 9fd32a8b3d3d3f9d43c341bfe098430e07609480 - subpackages: - - netrc - name: github.com/davecgh/go-spew version: 5215b55f46b2b919f50a1df0eaa5886afe4e3b3d subpackages: - spew +- name: github.com/git-lfs/go-netrc + version: 5affb93432dc700b6b318e739f9c7f09650df90b + subpackages: + - netrc - name: github.com/git-lfs/wildmatch version: 8a0518641565a619e62a2738c7d4498fc345daf6 - name: github.com/inconshreveable/mousetrap diff --git a/glide.yaml b/glide.yaml index eee8a77a..24c6cfa8 100644 --- a/glide.yaml +++ b/glide.yaml @@ -1,7 +1,7 @@ package: github.com/git-lfs/git-lfs import: -- package: github.com/bgentry/go-netrc - version: 9fd32a8b3d3d3f9d43c341bfe098430e07609480 +- package: github.com/git-lfs/go-netrc + version: 5affb93432dc700b6b318e739f9c7f09650df90b subpackages: - netrc - package: github.com/kr/pty diff --git a/lfsapi/auth.go b/lfsapi/auth.go index 837e217b..0070a2f6 100644 --- a/lfsapi/auth.go +++ b/lfsapi/auth.go @@ -9,8 +9,8 @@ import ( "os" "strings" - "github.com/bgentry/go-netrc/netrc" "github.com/git-lfs/git-lfs/errors" + "github.com/git-lfs/go-netrc/netrc" "github.com/rubyist/tracerx" ) diff --git a/lfsapi/netrc.go b/lfsapi/netrc.go index f40f641a..3d2c6555 100644 --- a/lfsapi/netrc.go +++ b/lfsapi/netrc.go @@ -4,8 +4,8 @@ import ( "os" "path/filepath" - "github.com/bgentry/go-netrc/netrc" "github.com/git-lfs/git-lfs/config" + "github.com/git-lfs/go-netrc/netrc" ) type NetrcFinder interface { diff --git a/lfsapi/netrc_test.go b/lfsapi/netrc_test.go index f07e7f01..88f495dc 100644 --- a/lfsapi/netrc_test.go +++ b/lfsapi/netrc_test.go @@ -6,7 +6,7 @@ import ( "strings" "testing" - "github.com/bgentry/go-netrc/netrc" + "github.com/git-lfs/go-netrc/netrc" ) func TestNetrcWithHostAndPort(t *testing.T) { diff --git a/test/test-credentials.sh b/test/test-credentials.sh index 3efbe6b5..845d484b 100755 --- a/test/test-credentials.sh +++ b/test/test-credentials.sh @@ -259,6 +259,39 @@ begin_test "credentials from netrc" ) end_test +begin_test "credentials from netrc with unknown keyword" +( + set -e + + printf "machine localhost\nlogin netrcuser\nnot-a-key something\npassword netrcpass\n" >> "$NETRCFILE" + echo $HOME + echo "GITSERVER $GITSERVER" + cat $NETRCFILE + + # prevent prompts on Windows particularly + export SSH_ASKPASS= + + reponame="netrctest" + setup_remote_repo "$reponame" + + clone_repo "$reponame" repo2 + + # Need a remote named "localhost" or 127.0.0.1 in netrc will interfere with the other auth + git remote add "netrc" "$(echo $GITSERVER | sed s/127.0.0.1/localhost/)/netrctest" + git lfs env + + git lfs track "*.dat" + echo "push a" > a.dat + git add .gitattributes a.dat + git commit -m "add a.dat" + + GIT_TRACE=1 git lfs push netrc master 2>&1 | tee push.log + grep "Uploading LFS objects: 100% (1/1), 7 B" push.log + echo "any git credential calls:" + [ "0" -eq "$(cat push.log | grep "git credential" | wc -l)" ] +) +end_test + begin_test "credentials from netrc with bad password" ( set -e @@ -274,7 +307,7 @@ begin_test "credentials from netrc with bad password" reponame="netrctest" setup_remote_repo "$reponame" - clone_repo "$reponame" repo2 + clone_repo "$reponame" repo3 # Need a remote named "localhost" or 127.0.0.1 in netrc will interfere with the other auth git remote add "netrc" "$(echo $GITSERVER | sed s/127.0.0.1/localhost/)/netrctest" diff --git a/vendor/github.com/bgentry/go-netrc/.hgignore b/vendor/github.com/git-lfs/go-netrc/.hgignore similarity index 100% rename from vendor/github.com/bgentry/go-netrc/.hgignore rename to vendor/github.com/git-lfs/go-netrc/.hgignore diff --git a/vendor/github.com/bgentry/go-netrc/LICENSE b/vendor/github.com/git-lfs/go-netrc/LICENSE similarity index 100% rename from vendor/github.com/bgentry/go-netrc/LICENSE rename to vendor/github.com/git-lfs/go-netrc/LICENSE diff --git a/vendor/github.com/bgentry/go-netrc/README.md b/vendor/github.com/git-lfs/go-netrc/README.md similarity index 100% rename from vendor/github.com/bgentry/go-netrc/README.md rename to vendor/github.com/git-lfs/go-netrc/README.md diff --git a/vendor/github.com/bgentry/go-netrc/netrc/examples/bad_default_order.netrc b/vendor/github.com/git-lfs/go-netrc/netrc/examples/bad_default_order.netrc similarity index 100% rename from vendor/github.com/bgentry/go-netrc/netrc/examples/bad_default_order.netrc rename to vendor/github.com/git-lfs/go-netrc/netrc/examples/bad_default_order.netrc diff --git a/vendor/github.com/bgentry/go-netrc/netrc/examples/good.netrc b/vendor/github.com/git-lfs/go-netrc/netrc/examples/good.netrc similarity index 66% rename from vendor/github.com/bgentry/go-netrc/netrc/examples/good.netrc rename to vendor/github.com/git-lfs/go-netrc/netrc/examples/good.netrc index 41a8e5ba..c0994d68 100644 --- a/vendor/github.com/bgentry/go-netrc/netrc/examples/good.netrc +++ b/vendor/github.com/git-lfs/go-netrc/netrc/examples/good.netrc @@ -1,7 +1,7 @@ # I am a comment machine mail.google.com login joe@gmail.com - account justagmail #end of line comment with trailing space + account justagmail #end of line comment with trailing space password somethingSecret # I am another comment @@ -16,6 +16,12 @@ machine ray login demo password mypassword machine weirdlogin login uname password pass#pass +machine google.com + login alice@google.com + not-a-keyword + password secure + also-not-a-keyword + default login anonymous password joe@example.com diff --git a/vendor/github.com/bgentry/go-netrc/netrc/netrc.go b/vendor/github.com/git-lfs/go-netrc/netrc/netrc.go similarity index 98% rename from vendor/github.com/bgentry/go-netrc/netrc/netrc.go rename to vendor/github.com/git-lfs/go-netrc/netrc/netrc.go index ea49987c..4c9f8681 100644 --- a/vendor/github.com/bgentry/go-netrc/netrc/netrc.go +++ b/vendor/github.com/git-lfs/go-netrc/netrc/netrc.go @@ -24,6 +24,7 @@ const ( tkMacdef tkComment tkWhitespace + tkUnknown ) var keywords = map[string]tkType{ @@ -70,7 +71,7 @@ func (n *Netrc) MarshalText() (text []byte, err error) { // TODO(bgentry): not safe for concurrency for i := range n.tokens { switch n.tokens[i].kind { - case tkComment, tkDefault, tkWhitespace: // always append these types + case tkComment, tkDefault, tkWhitespace, tkUnknown: // always append these types text = append(text, n.tokens[i].rawkind...) default: if n.tokens[i].value != "" { // skip empty-value tokens @@ -391,9 +392,11 @@ func parse(r io.Reader, pos int) (*Netrc, error) { t, err = newToken(rawb) if err != nil { if currentMacro == nil { - return nil, &Error{pos, err.Error()} + t.kind = tkUnknown + nrc.tokens = append(nrc.tokens, t) + } else { + currentMacro.rawvalue = append(currentMacro.rawvalue, rawb...) } - currentMacro.rawvalue = append(currentMacro.rawvalue, rawb...) continue } diff --git a/vendor/github.com/bgentry/go-netrc/netrc/netrc_test.go b/vendor/github.com/git-lfs/go-netrc/netrc/netrc_test.go similarity index 99% rename from vendor/github.com/bgentry/go-netrc/netrc/netrc_test.go rename to vendor/github.com/git-lfs/go-netrc/netrc/netrc_test.go index 70ceacf6..d8437bf2 100644 --- a/vendor/github.com/bgentry/go-netrc/netrc/netrc_test.go +++ b/vendor/github.com/git-lfs/go-netrc/netrc/netrc_test.go @@ -18,6 +18,7 @@ var expectedMachines = []*Machine{ &Machine{Name: "mail.google.com", Login: "joe@gmail.com", Password: "somethingSecret", Account: "justagmail"}, &Machine{Name: "ray", Login: "demo", Password: "mypassword", Account: ""}, &Machine{Name: "weirdlogin", Login: "uname", Password: "pass#pass", Account: ""}, + &Machine{Name: "google.com", Login: "alice@google.com", Password: "secure"}, &Machine{Name: "", Login: "anonymous", Password: "joe@example.com", Account: ""}, } var expectedMacros = Macros{ @@ -146,7 +147,7 @@ func TestFindMachine(t *testing.T) { if err != nil { t.Fatal(err) } - if !eqMachine(m, expectedMachines[3]) { + if !eqMachine(m, expectedMachines[4]) { t.Errorf("bad machine; expected %v, got %v\n", expectedMachines[3], m) } if !m.IsDefault() { From 2fd8023b090ae3cb7ff8b252998e8fd06f14c439 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 25 May 2018 13:01:31 -0700 Subject: [PATCH 54/94] glide.yaml: update github.com/git-lfs/go-netrc --- glide.lock | 6 +++--- glide.yaml | 2 +- .../github.com/git-lfs/go-netrc/netrc/examples/good.netrc | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/glide.lock b/glide.lock index 7ceb2f1a..0d6e5477 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ -hash: 3603b2885070c06a5a5b066ffb9f82335dc11e9698c5b9e5c0e782ad58e79af6 -updated: 2018-05-25T12:41:49.056975-07:00 +hash: 5d2fbd8be4931b982d29c6ac8df833f139b28ffdb44ca062948a2386e2096a4d +updated: 2018-05-25T13:01:03.220513-07:00 imports: - name: github.com/alexbrainman/sspi version: 4729b3d4d8581b2db83864d1018926e4154f9406 @@ -10,7 +10,7 @@ imports: subpackages: - spew - name: github.com/git-lfs/go-netrc - version: 5affb93432dc700b6b318e739f9c7f09650df90b + version: e0e9ca483a183481412e6f5a700ff20a36177503 subpackages: - netrc - name: github.com/git-lfs/wildmatch diff --git a/glide.yaml b/glide.yaml index 24c6cfa8..5e7758d7 100644 --- a/glide.yaml +++ b/glide.yaml @@ -1,7 +1,7 @@ package: github.com/git-lfs/git-lfs import: - package: github.com/git-lfs/go-netrc - version: 5affb93432dc700b6b318e739f9c7f09650df90b + version: e0e9ca483a183481412e6f5a700ff20a36177503 subpackages: - netrc - package: github.com/kr/pty diff --git a/vendor/github.com/git-lfs/go-netrc/netrc/examples/good.netrc b/vendor/github.com/git-lfs/go-netrc/netrc/examples/good.netrc index c0994d68..10e37083 100644 --- a/vendor/github.com/git-lfs/go-netrc/netrc/examples/good.netrc +++ b/vendor/github.com/git-lfs/go-netrc/netrc/examples/good.netrc @@ -1,7 +1,7 @@ # I am a comment machine mail.google.com login joe@gmail.com - account justagmail #end of line comment with trailing space + account justagmail #end of line comment with trailing space password somethingSecret # I am another comment From 8f6c9e9cebde1cb047bbba8548646db4f24c777c Mon Sep 17 00:00:00 2001 From: Preben Ingvaldsen Date: Fri, 25 May 2018 14:06:54 -0700 Subject: [PATCH 55/94] commands: take files as args with --no-rewrite Change the `migrate import` command to take a list of files to be imported when the `--no-rewrite` flag is used. --- commands/command_migrate_import.go | 55 ++++++++---------------------- git/attribs.go | 17 +++++++++ 2 files changed, 32 insertions(+), 40 deletions(-) diff --git a/commands/command_migrate_import.go b/commands/command_migrate_import.go index dc48e66b..bca4597d 100644 --- a/commands/command_migrate_import.go +++ b/commands/command_migrate_import.go @@ -31,6 +31,10 @@ func migrateImportCommand(cmd *cobra.Command, args []string) { defer db.Close() if migrateNoRewrite { + if len(args) == 0 { + ExitWithError(errors.Errorf("fatal: the migrate import command requires a list of files to import when using the --no-rewrite flag")) + } + ref, err := git.CurrentRef() if err != nil { ExitWithError(errors.Wrap(err, "fatal: unable to find current reference")) @@ -44,35 +48,31 @@ func migrateImportCommand(cmd *cobra.Command, args []string) { root := commit.TreeID - include, _ := getIncludeExcludeArgs(cmd) - paths, _ := determineIncludeExcludePaths(cfg, include, nil) - if len(paths) == 0 { - ExitWithError(errors.New("fatal: no matching paths found")) + filter := git.GetAttributeFilter(cfg.LocalWorkingDir(), cfg.LocalGitDir()) + if len(filter.Include()) == 0 && len(filter.Exclude()) == 0 { + ExitWithError(errors.Errorf("fatal: no git lfs filters setup in .gitattributes")) } - entries, err := listEntries(db, root, "") - if err != nil { - ExitWithError(errors.Wrap(err, "fatal: unable to list tree entries")) - } - - filter := filepathfilter.New(paths, nil) - for _, entry := range entries { - if filter.Allows(entry) { - root, err = rewriteTree(db, root, entry) + for _, file := range args { + if filter.Allows(file) { + root, err = rewriteTree(db, root, file) if err != nil { - ExitWithError(errors.Wrapf(err, "fatal: could not rewrite %q", entry)) + ExitWithError(errors.Wrapf(err, "fatal: could not rewrite %q", file)) } + } else { + ExitWithError(errors.Errorf("fatal: file %s did not match any entries in .gitattributes", file)) } } name, email := cfg.CurrentCommitter() author := fmt.Sprintf("%s <%s>", name, email) + filelist := strings.Join(args, ",") oid, err := db.WriteCommit(&odb.Commit{ Author: author, Committer: author, ParentIDs: [][]byte{sha}, - Message: generateMigrateCommitMessage(cmd, include), + Message: generateMigrateCommitMessage(cmd, &filelist), TreeID: root, }) @@ -378,28 +378,3 @@ func findEntry(t *odb.Tree, name string) int { return -1 } - -// listEntries returns an array with the full paths to all blobs within the provided tree. -func listEntries(db *odb.ObjectDatabase, id []byte, parent string) ([]string, error) { - t, err := db.Tree(id) - if err != nil { - return nil, err - } - - names := make([]string, 0, len(t.Entries)) - - for _, e := range t.Entries { - switch e.Type() { - case odb.BlobObjectType: - names = append(names, fmt.Sprintf("%s%s", parent, e.Name)) - case odb.TreeObjectType: - sub, err := listEntries(db, e.Oid, fmt.Sprintf("%s%s/", parent, e.Name)) - if err != nil { - return nil, err - } - names = append(names, sub...) - } - } - - return names, nil -} diff --git a/git/attribs.go b/git/attribs.go index 067bf42d..f524e390 100644 --- a/git/attribs.go +++ b/git/attribs.go @@ -7,6 +7,7 @@ import ( "path/filepath" "strings" + "github.com/git-lfs/git-lfs/filepathfilter" "github.com/git-lfs/git-lfs/tools" "github.com/rubyist/tracerx" ) @@ -97,6 +98,22 @@ func GetAttributePaths(workingDir, gitDir string) []AttributePath { return paths } +// GetAttributeFilter returns a list of entries in .gitattributes which are +// configured with the filter=lfs attribute as a file path filter which +// file paths can be matched against +// workingDir is the root of the working copy +// gitDir is the root of the git repo +func GetAttributeFilter(workingDir, gitDir string) *filepathfilter.Filter { + paths := GetAttributePaths(workingDir, gitDir) + patterns := make([]filepathfilter.Pattern, len(paths)) + + for i, path := range paths { + patterns[i] = filepathfilter.NewPattern(path.Path) + } + + return filepathfilter.NewFromPatterns(patterns, nil) +} + // copies bufio.ScanLines(), counting LF vs CRLF in a file type lineEndingSplitter struct { LFCount int From 133da5293adee3951d7c2d3108c731460538a025 Mon Sep 17 00:00:00 2001 From: Preben Ingvaldsen Date: Fri, 25 May 2018 17:11:14 -0700 Subject: [PATCH 56/94] command: add integration tests for --no-rewrite Add a new test script, test-migrate-import-no-rewrite.sh, that runs a series of integration tests using the `migrate import` command and the `--no-rewrite` flag --- test/test-migrate-fixtures.sh | 67 ++++++++ test/test-migrate-import-no-rewrite.sh | 212 +++++++++++++++++++++++++ 2 files changed, 279 insertions(+) create mode 100755 test/test-migrate-import-no-rewrite.sh diff --git a/test/test-migrate-fixtures.sh b/test/test-migrate-fixtures.sh index 6d3408fa..e6f226f0 100755 --- a/test/test-migrate-fixtures.sh +++ b/test/test-migrate-fixtures.sh @@ -44,6 +44,46 @@ setup_local_branch_with_gitattrs() { git commit -m "add .gitattributes" } +# setup_local_branch_with_nested_gitattrs creates a repository as follows: +# +# A---B +# \ +# refs/heads/master +# +# - Commit 'A' has 120, in a.txt, and a corresponding entry in .gitattributes. There is also +# 140 in a.md, with no corresponding entry in .gitattributes. +# It also has 140 in subtree/a.md, and a corresponding entry in subtree/.gitattributes +setup_local_branch_with_nested_gitattrs() { + set -e + + reponame="migrate-single-remote-branch-with-nested-attrs" + + remove_and_create_local_repo "$reponame" + + mkdir subtree + + base64 < /dev/urandom | head -c 120 > a.txt + base64 < /dev/urandom | head -c 140 > a.md + base64 < /dev/urandom | head -c 140 > subtree/a.md + + git add a.txt a.md subtree/a.md + git commit -m "initial commit" + + git lfs track "*.txt" + + git add .gitattributes + git commit -m "add .gitattributes" + + cd subtree + + git lfs track "*.md" + + cd .. + + git add subtree/.gitattributes + git commit -m "add nested .gitattributes" +} + # setup_multiple_local_branches creates a repository as follows: # # B @@ -79,6 +119,21 @@ setup_multiple_local_branches() { git checkout master } +# setup_multiple_local_branches_with_gitattrs creates a repository in the same way +# as setup_multiple_local_branches, but also adds relevant lfs filters to the +# .gitattributes file in the master branch +setup_multiple_local_branches_with_gitattrs() { + set -e + + setup_multiple_local_branches + + git lfs track *.txt + git lfs track *.md + + git add .gitattributes + git commit -m "add .gitattributes" +} + # setup_local_branch_with_space creates a repository as follows: # # A @@ -134,6 +189,18 @@ setup_single_remote_branch() { git commit -m "add an additional 30, 50 bytes to a.{txt,md}" } +setup_single_remote_branch_with_gitattrs() { + set -e + + setup_single_remote_branch + + git lfs track *.txt + git lfs track *.md + + git add .gitattributes + git commit -m "add .gitattributes" +} + # setup_multiple_remote_branches creates a repository as follows: # # C diff --git a/test/test-migrate-import-no-rewrite.sh b/test/test-migrate-import-no-rewrite.sh new file mode 100755 index 00000000..d8c711f5 --- /dev/null +++ b/test/test-migrate-import-no-rewrite.sh @@ -0,0 +1,212 @@ +#!/usr/bin/env bash + +. "test/test-migrate-fixtures.sh" +. "test/testlib.sh" + +begin_test "migrate import --no-rewrite (default branch)" +( + set -e + + setup_local_branch_with_gitattrs + + txt_oid="$(calc_oid "$(git cat-file -p :a.txt)")" + prev_commit_oid="$(git rev-parse HEAD)" + + git lfs migrate import --no-rewrite *.txt + + # Ensure our desired files were imported into git-lfs + assert_pointer "refs/heads/master" "a.txt" "$txt_oid" "120" + assert_local_object "$txt_oid" "120" + + # Ensure the git history remained the same + new_commit_oid="$(git rev-parse HEAD~1)" + if [ "$prev_commit_oid" != "$new_commit_oid" ]; then + exit 1 + fi + + # Ensure a new commit was made + new_head_oid="$(git rev-parse HEAD)" + if [ "$prev_commit_oid" == "$new_oid" ]; then + exit 1 + fi + + # Ensure a new commit message was generated based on the list of imported files + commit_msg="$(git log -1 --pretty=format:%s)" + echo "$commit_msg" | grep -q "a.txt: convert to Git LFS" +) +end_test + +begin_test "migrate import --no-rewrite (bare repository)" +( + set -e + + setup_single_remote_branch_with_gitattrs + + prev_commit_oid="$(git rev-parse HEAD)" + txt_oid="$(calc_oid "$(git cat-file -p :a.txt)")" + md_oid="$(calc_oid "$(git cat-file -p :a.md)")" + + git lfs migrate import --no-rewrite a.txt a.md + + # Ensure our desired files were imported + assert_pointer "refs/heads/master" "a.txt" "$txt_oid" "30" + assert_pointer "refs/heads/master" "a.md" "$md_oid" "50" + + # Ensure the git history remained the same + new_commit_oid="$(git rev-parse HEAD~1)" + if [ "$prev_commit_oid" != "$new_commit_oid" ]; then + exit 1 + fi + + # Ensure a new commit was made + new_head_oid="$(git rev-parse HEAD)" + if [ "$prev_commit_oid" == "$new_oid" ]; then + exit 1 + fi +) +end_test + +begin_test "migrate import --no-rewrite (multiple branches)" +( + set -e + + setup_multiple_local_branches_with_gitattrs + + prev_commit_oid="$(git rev-parse HEAD)" + + md_oid="$(calc_oid "$(git cat-file -p :a.md)")" + txt_oid="$(calc_oid "$(git cat-file -p :a.txt)")" + md_feature_oid="$(calc_oid "$(git cat-file -p my-feature:a.md)")" + + git lfs migrate import --no-rewrite *.txt *.md + + # Ensure our desired files were imported + assert_pointer "refs/heads/master" "a.md" "$md_oid" "140" + assert_pointer "refs/heads/master" "a.txt" "$txt_oid" "120" + + assert_local_object "$md_oid" "140" + assert_local_object "$txt_oid" "120" + + # Ensure our other branch was unmodified + refute_local_object "$md_feature_oid" "30" + + # Ensure the git history remained the same + new_commit_oid="$(git rev-parse HEAD~1)" + if [ "$prev_commit_oid" != "$new_commit_oid" ]; then + exit 1 + fi + + # Ensure a new commit was made + new_head_oid="$(git rev-parse HEAD)" + if [ "$prev_commit_oid" == "$new_oid" ]; then + exit 1 + fi +) +end_test + +begin_test "migrate import --no-rewrite (no .gitattributes)" +( + set -e + + setup_multiple_local_branches + + # Ensure command fails if no .gitattributes files are present + [ !"$(git lfs migrate import --no-rewrite *.txt *.md)" ] +) +end_test + +begin_test "migrate import --no-rewrite (nested .gitattributes)" +( + set -e + + setup_local_branch_with_nested_gitattrs + + # Ensure a .md filter does not exist in the top-level .gitattributes + master_attrs="$(git cat-file -p "$master:.gitattributes")" + [ !"$(echo "$master_attrs" | grep -q ".md")" ] + + # Ensure a .md filter exists in the nested .gitattributes + nested_attrs="$(git cat-file -p "$master:subtree/.gitattributes")" + echo "$nested_attrs" | grep -q "*.md filter=lfs diff=lfs merge=lfs" + + md_oid="$(calc_oid "$(git cat-file -p :a.md)")" + nested_md_oid="$(calc_oid "$(git cat-file -p :subtree/a.md)")" + txt_oid="$(calc_oid "$(git cat-file -p :a.txt)")" + + git lfs migrate import --no-rewrite a.txt subtree/a.md + + # Ensure a.txt and subtree/a.md were imported, even though *.md only exists in the + # nested subtree/.gitattributes file + assert_pointer "refs/heads/master" "subtree/a.md" "$nested_md_oid" "140" + assert_pointer "refs/heads/master" "a.txt" "$txt_oid" "120" + + assert_local_object "$nested_md_oid" 140 + assert_local_object "$txt_oid" 120 + refute_local_object "$md_oid" 140 + + # Failure should occur when trying to import a.md as no entry exists in + # top-level .gitattributes file + [ !"$(git lfs migrate import --no-rewrite a.md)" ] +) +end_test + +begin_test "migrate import --no-rewrite (with commit message)" +( + set -e + + setup_local_branch_with_gitattrs + + prev_commit_oid="$(git rev-parse HEAD)" + expected_commit_msg="run git-lfs migrate import --no-rewrite" + + git lfs migrate import --message "$expected_commit_msg" --no-rewrite *.txt + + # Ensure the git history remained the same + new_commit_oid="$(git rev-parse HEAD~1)" + if [ "$prev_commit_oid" != "$new_commit_oid" ]; then + exit 1 + fi + + # Ensure a new commit was made + new_head_oid="$(git rev-parse HEAD)" + if [ "$prev_commit_oid" == "$new_oid" ]; then + exit 1 + fi + + # Ensure the provided commit message was used + commit_msg="$(git log -1 --pretty=format:%s)" + if [ "$commit_msg" != "$expected_commit_msg" ]; then + exit 1 + fi +) +end_test + +begin_test "migrate import --no-rewrite (with empty commit message)" +( + set -e + + setup_local_branch_with_gitattrs + + prev_commit_oid="$(git rev-parse HEAD)" + + git lfs migrate import -m "" --no-rewrite *.txt + + # Ensure the git history remained the same + new_commit_oid="$(git rev-parse HEAD~1)" + if [ "$prev_commit_oid" != "$new_commit_oid" ]; then + exit 1 + fi + + # Ensure a new commit was made + new_head_oid="$(git rev-parse HEAD)" + if [ "$prev_commit_oid" == "$new_oid" ]; then + exit 1 + fi + + # Ensure the provided commit message was used + commit_msg="$(git log -1 --pretty=format:%s)" + if [ "$commit_msg" != "" ]; then + exit 1 + fi +) +end_test \ No newline at end of file From 8715e893e3f240f41cfc057234ae7d8ac16d5b28 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 28 May 2018 18:14:09 -0700 Subject: [PATCH 57/94] lfsapi/client_test.go: test cross-host authenticated redirect --- lfsapi/client_test.go | 76 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/lfsapi/client_test.go b/lfsapi/client_test.go index e31a7e92..f5500f80 100644 --- a/lfsapi/client_test.go +++ b/lfsapi/client_test.go @@ -1,11 +1,13 @@ package lfsapi import ( + "encoding/base64" "encoding/json" "fmt" "net" "net/http" "net/http/httptest" + "strings" "sync/atomic" "testing" @@ -175,6 +177,80 @@ func TestClientRedirect(t *testing.T) { assert.EqualError(t, err, "lfsapi/client: refusing insecure redirect, https->http") } +func TestClientRedirectReauthenticate(t *testing.T) { + var srv1, srv2 *httptest.Server + var called1, called2 uint32 + var creds1, creds2 Creds + + srv1 = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddUint32(&called1, 1) + + if hdr := r.Header.Get("Authorization"); len(hdr) > 0 { + parts := strings.SplitN(hdr, " ", 2) + typ, b64 := parts[0], parts[1] + + auth, err := base64.URLEncoding.DecodeString(b64) + assert.Nil(t, err) + assert.Equal(t, "Basic", typ) + assert.Equal(t, "user1:pass1", string(auth)) + + http.Redirect(w, r, srv2.URL+r.URL.Path, http.StatusMovedPermanently) + return + } + w.WriteHeader(http.StatusUnauthorized) + })) + + srv2 = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddUint32(&called2, 1) + + parts := strings.SplitN(r.Header.Get("Authorization"), " ", 2) + typ, b64 := parts[0], parts[1] + + auth, err := base64.URLEncoding.DecodeString(b64) + assert.Nil(t, err) + assert.Equal(t, "Basic", typ) + assert.Equal(t, "user2:pass2", string(auth)) + })) + + // Change the URL of srv2 to make it appears as if it is a different + // host. + srv2.URL = strings.Replace(srv2.URL, "127.0.0.1", "0.0.0.0", 1) + + creds1 = Creds(map[string]string{ + "protocol": "http", + "host": strings.TrimPrefix(srv1.URL, "http://"), + + "username": "user1", + "password": "pass1", + }) + creds2 = Creds(map[string]string{ + "protocol": "http", + "host": strings.TrimPrefix(srv2.URL, "http://"), + + "username": "user2", + "password": "pass2", + }) + + defer srv1.Close() + defer srv2.Close() + + c, err := NewClient(NewContext(nil, nil, nil)) + creds := newCredentialCacher() + creds.Approve(creds1) + creds.Approve(creds2) + c.Credentials = creds + + req, err := http.NewRequest("GET", srv1.URL, nil) + require.Nil(t, err) + + _, err = c.DoWithAuth("", req) + assert.Nil(t, err) + + // called1 is 2 since LFS tries an unauthenticated request first + assert.EqualValues(t, 2, called1) + assert.EqualValues(t, 1, called2) +} + func TestNewClient(t *testing.T) { c, err := NewClient(NewContext(nil, nil, map[string]string{ "lfs.dialtimeout": "151", From dfcbd79889c68ebe44942e91803c68c87a09cb57 Mon Sep 17 00:00:00 2001 From: Preben Ingvaldsen Date: Tue, 29 May 2018 16:56:19 -0700 Subject: [PATCH 58/94] commands: add man page docs for `--no-rewrite` Add documentation about the `--no-rewrite` flag to the man page for the `migrate` command --- docs/man/git-lfs-migrate.1.ronn | 42 +++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/docs/man/git-lfs-migrate.1.ronn b/docs/man/git-lfs-migrate.1.ronn index 996f4742..cb049bbc 100644 --- a/docs/man/git-lfs-migrate.1.ronn +++ b/docs/man/git-lfs-migrate.1.ronn @@ -84,13 +84,39 @@ options and these additional ones: Write to 'path' a file with the mapping of each rewritten commits. The file format is CSV with this pattern: `OLD-SHA`,`NEW-SHA` -If `--include` or `--exclude` (`-I`, `-X`, respectively) are given, the +* `--no-rewrite` + Migrate large objects to Git LFS in a new commit without rewriting git history. + Please note that when this option is used, the `migrate import` command will expect + a different argument list, specialized options will become available, and the core + `migrate` options will be ignored. See [IMPORT (NO REWRITE)]. + +If `--no-rewrite` is not provided and `--include` or `--exclude` (`-I`, `-X`, respectively) are given, the .gitattributes will be modified to include any new filepath patterns as given by those flags. -If neither of those flags are given, the gitattributes will be incrementally +If `--no-rewrite` is not provided and neither of those flags are given, the gitattributes will be incrementally modified to include new filepath extensions as they are rewritten in history. +### IMPORT (NO REWRITE) + +The `import` mode has a special sub-mode enabled by the `--no-rewrite` flag. This sub-mode +will migrate large objects to pointers as in the base `import` mode, but will do so in a new commit +without rewriting Git history. When using this sub-mode, the base `migrate` options, +such as `--include-ref`, will be ignored, as will those for the base `import` mode. +The `migrate` command will also take a different argument list. + +The `--no-rewrite` sub-mode supports the following options and arguments: + +* `-m` `--message`= + Specifies a commit message for the newly created commit. + +* [file ...] + The list of files to import. These files must be tracked by patterns specified in the + gitattributes. + +If `--message` is given, the new commit will be created with the provided message. If no message is given, +a commit message will be generated based on the file arguments. + ## INCLUDE AND EXCLUDE You can configure Git LFS to only migrate tree entries whose pathspec matches @@ -189,6 +215,18 @@ $ git lfs migrate import --everything --include="*.zip" Note: This will require a force push to any existing Git remotes. +### Migrate without rewriting local history + +You can also migrate files without modifying the existing history of your respoitory: + +``` +# Without a specified commit message +$ git lfs migrate import --no-rewrite test.zip *.mp3 *.psd + +# With a specified commit message +$ git lfs migrate import --no-rewrite -m "Import .zip, .mp3, .psd files" test.zip *.mpd *.psd +``` + ## SEE ALSO Part of the git-lfs(1) suite. From 9774ddcdffcd4a59f18938521e078b0ffddd8898 Mon Sep 17 00:00:00 2001 From: Preben Ingvaldsen Date: Wed, 30 May 2018 09:54:45 -0700 Subject: [PATCH 59/94] commands: address --no-rewrite feedback * Update error message text to be more concise/descriptive * Fix casing/formatting issues * Inline variables to reduce scope * Cache and reuse GitFilter instead of creating one every time a clean is performed --- commands/command_migrate_import.go | 40 ++++++++++++++---------------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/commands/command_migrate_import.go b/commands/command_migrate_import.go index bca4597d..de0dfd2e 100644 --- a/commands/command_migrate_import.go +++ b/commands/command_migrate_import.go @@ -32,7 +32,7 @@ func migrateImportCommand(cmd *cobra.Command, args []string) { if migrateNoRewrite { if len(args) == 0 { - ExitWithError(errors.Errorf("fatal: the migrate import command requires a list of files to import when using the --no-rewrite flag")) + ExitWithError(errors.Errorf("fatal: expected one or more files with --no-rewrite")) } ref, err := git.CurrentRef() @@ -50,12 +50,14 @@ func migrateImportCommand(cmd *cobra.Command, args []string) { filter := git.GetAttributeFilter(cfg.LocalWorkingDir(), cfg.LocalGitDir()) if len(filter.Include()) == 0 && len(filter.Exclude()) == 0 { - ExitWithError(errors.Errorf("fatal: no git lfs filters setup in .gitattributes")) + ExitWithError(errors.Errorf("fatal: no git lfs filters found in .gitattributes")) } + gf := lfs.NewGitFilter(cfg) + for _, file := range args { if filter.Allows(file) { - root, err = rewriteTree(db, root, file) + root, err = rewriteTree(gf, db, root, file) if err != nil { ExitWithError(errors.Wrapf(err, "fatal: could not rewrite %q", file)) } @@ -67,12 +69,11 @@ func migrateImportCommand(cmd *cobra.Command, args []string) { name, email := cfg.CurrentCommitter() author := fmt.Sprintf("%s <%s>", name, email) - filelist := strings.Join(args, ",") oid, err := db.WriteCommit(&odb.Commit{ Author: author, Committer: author, ParentIDs: [][]byte{sha}, - Message: generateMigrateCommitMessage(cmd, &filelist), + Message: generateMigrateCommitMessage(cmd, strings.Join(args, ",")), TreeID: root, }) @@ -173,14 +174,11 @@ func migrateImportCommand(cmd *cobra.Command, args []string) { // generateMigrateCommitMessage generates a commit message used with // --no-rewrite, using --message (if given) or generating one if it isn't. -func generateMigrateCommitMessage(cmd *cobra.Command, patterns *string) string { +func generateMigrateCommitMessage(cmd *cobra.Command, patterns string) string { if cmd.Flag("message").Changed { return migrateCommitMessage } - if patterns != nil { - return fmt.Sprintf("%s: convert to Git LFS", *patterns) - } - panic("unexpected") + return fmt.Sprintf("%s: convert to Git LFS", patterns) } // checkoutNonBare forces a checkout of the current reference, so long as the @@ -287,7 +285,7 @@ func trackedToBlob(db *odb.ObjectDatabase, patterns *tools.OrderedSet) ([]byte, // rewriteTree replaces the blob at the provided path within the given tree with // a git lfs pointer. It will recursively rewrite any subtrees along the path to the // blob. -func rewriteTree(db *odb.ObjectDatabase, root []byte, path string) ([]byte, error) { +func rewriteTree(gf *lfs.GitFilter, db *odb.ObjectDatabase, root []byte, path string) ([]byte, error) { tree, err := db.Tree(root) if err != nil { return nil, err @@ -298,7 +296,7 @@ func rewriteTree(db *odb.ObjectDatabase, root []byte, path string) ([]byte, erro switch len(splits) { case 1: // The path points to an entry at the root of this tree, so it must be a blob. - // Try to replace this blob with a git lfs pointer. + // Try to replace this blob with a Git LFS pointer. index := findEntry(tree, splits[0]) if index < 0 { return nil, errors.Errorf("unable to find entry %s in tree", splits[0]) @@ -312,26 +310,24 @@ func rewriteTree(db *odb.ObjectDatabase, root []byte, path string) ([]byte, erro var buf bytes.Buffer - if _, err := clean(lfs.NewGitFilter(cfg), &buf, blob.Contents, blobEntry.Name, blob.Size); err != nil { + if _, err := clean(gf, &buf, blob.Contents, blobEntry.Name, blob.Size); err != nil { return nil, err } - newBlob := odb.Blob{ + newOid, err := db.WriteBlob(&odb.Blob{ Contents: &buf, Size: int64(buf.Len()), - } + }) - newOid, err := db.WriteBlob(&newBlob) if err != nil { return nil, err } - newEntry := odb.TreeEntry{ + tree = tree.Merge(&odb.TreeEntry{ Name: splits[0], Filemode: blobEntry.Filemode, Oid: newOid, - } - tree = tree.Merge(&newEntry) + }) return db.WriteTree(tree) case 2: @@ -349,7 +345,7 @@ func rewriteTree(db *odb.ObjectDatabase, root []byte, path string) ([]byte, erro return nil, errors.Errorf("migrate: expected %s to be a tree, got %s", head, subtreeEntry.Type()) } - rewrittenSubtree, err := rewriteTree(db, subtreeEntry.Oid, tail) + rewrittenSubtree, err := rewriteTree(gf, db, subtreeEntry.Oid, tail) if err != nil { return nil, err } @@ -367,8 +363,8 @@ func rewriteTree(db *odb.ObjectDatabase, root []byte, path string) ([]byte, erro } } -// findEntry searches a tree for the desired entry, and returns the -// index of that entry within the tree's Entries array +// findEntry searches a tree for the desired entry, and returns the index of that +// entry within the tree's Entries array func findEntry(t *odb.Tree, name string) int { for i, entry := range t.Entries { if entry.Name == name { From 62b1142156e0ae03b51627aa556729d2ec98d7d3 Mon Sep 17 00:00:00 2001 From: Preben Ingvaldsen Date: Wed, 30 May 2018 10:18:04 -0700 Subject: [PATCH 60/94] commands: pre-check files against lfs filters With the `--no-rewrite` flag to the `migrate import`, check all provided files match `.gitattributes` filters before any tree rewrite operations. --- commands/command_migrate_import.go | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/commands/command_migrate_import.go b/commands/command_migrate_import.go index de0dfd2e..efdaf92b 100644 --- a/commands/command_migrate_import.go +++ b/commands/command_migrate_import.go @@ -56,16 +56,18 @@ func migrateImportCommand(cmd *cobra.Command, args []string) { gf := lfs.NewGitFilter(cfg) for _, file := range args { - if filter.Allows(file) { - root, err = rewriteTree(gf, db, root, file) - if err != nil { - ExitWithError(errors.Wrapf(err, "fatal: could not rewrite %q", file)) - } - } else { + if !filter.Allows(file) { ExitWithError(errors.Errorf("fatal: file %s did not match any entries in .gitattributes", file)) } } + for _, file := range args { + root, err = rewriteTree(gf, db, root, file) + if err != nil { + ExitWithError(errors.Wrapf(err, "fatal: could not rewrite %q", file)) + } + } + name, email := cfg.CurrentCommitter() author := fmt.Sprintf("%s <%s>", name, email) From afffdd0d3f5e022c3fc00f0f28ae432824a64cb1 Mon Sep 17 00:00:00 2001 From: Preben Ingvaldsen Date: Wed, 30 May 2018 10:23:14 -0700 Subject: [PATCH 61/94] git: use append in GetAttributeFilter() Append elements to the array rather than assigning them to indices in GetAttributeFilter --- git/attribs.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/git/attribs.go b/git/attribs.go index f524e390..70764f1c 100644 --- a/git/attribs.go +++ b/git/attribs.go @@ -105,10 +105,10 @@ func GetAttributePaths(workingDir, gitDir string) []AttributePath { // gitDir is the root of the git repo func GetAttributeFilter(workingDir, gitDir string) *filepathfilter.Filter { paths := GetAttributePaths(workingDir, gitDir) - patterns := make([]filepathfilter.Pattern, len(paths)) + patterns := make([]filepathfilter.Pattern, 0, len(paths)) - for i, path := range paths { - patterns[i] = filepathfilter.NewPattern(path.Path) + for _, path := range paths { + patterns = append(patterns, filepathfilter.NewPattern(path.Path)) } return filepathfilter.NewFromPatterns(patterns, nil) From 5fec165fccbdafe9c6b64d41c7cea2302ccac6a4 Mon Sep 17 00:00:00 2001 From: Preben Ingvaldsen Date: Wed, 30 May 2018 10:55:02 -0700 Subject: [PATCH 62/94] commands: use consistent casing/terms in errors Update `--no-rewrite` error messages to correctly case Git LFS and use the term `filters` --- commands/command_migrate_import.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/commands/command_migrate_import.go b/commands/command_migrate_import.go index efdaf92b..2ffa6d79 100644 --- a/commands/command_migrate_import.go +++ b/commands/command_migrate_import.go @@ -50,14 +50,14 @@ func migrateImportCommand(cmd *cobra.Command, args []string) { filter := git.GetAttributeFilter(cfg.LocalWorkingDir(), cfg.LocalGitDir()) if len(filter.Include()) == 0 && len(filter.Exclude()) == 0 { - ExitWithError(errors.Errorf("fatal: no git lfs filters found in .gitattributes")) + ExitWithError(errors.Errorf("fatal: no Git LFS filters found in .gitattributes")) } gf := lfs.NewGitFilter(cfg) for _, file := range args { if !filter.Allows(file) { - ExitWithError(errors.Errorf("fatal: file %s did not match any entries in .gitattributes", file)) + ExitWithError(errors.Errorf("fatal: file %s did not match any Git LFS filters in .gitattributes", file)) } } From 188a4c668c5a06702d859e5eeb04697bef7b390a Mon Sep 17 00:00:00 2001 From: Preben Ingvaldsen Date: Wed, 30 May 2018 10:56:11 -0700 Subject: [PATCH 63/94] commands: test error messages are as expected In the `--no-rewrite` tests that cover error cases, test that the provided error message is as expected --- test/test-migrate-import-no-rewrite.sh | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/test/test-migrate-import-no-rewrite.sh b/test/test-migrate-import-no-rewrite.sh index d8c711f5..26480740 100755 --- a/test/test-migrate-import-no-rewrite.sh +++ b/test/test-migrate-import-no-rewrite.sh @@ -111,7 +111,12 @@ begin_test "migrate import --no-rewrite (no .gitattributes)" setup_multiple_local_branches # Ensure command fails if no .gitattributes files are present - [ !"$(git lfs migrate import --no-rewrite *.txt *.md)" ] + git lfs migrate import --no-rewrite *.txt *.md 2>&1 | tee migrate.log + if [ ${PIPESTATUS[0]} -eq 0 ]; then + echo >&2 "fatal: expected git lfs migrate import --no-rewrite to fail, didn't" + fi + + grep "no Git LFS filters found in .gitattributes" migrate.log ) end_test @@ -146,7 +151,12 @@ begin_test "migrate import --no-rewrite (nested .gitattributes)" # Failure should occur when trying to import a.md as no entry exists in # top-level .gitattributes file - [ !"$(git lfs migrate import --no-rewrite a.md)" ] + git lfs migrate import --no-rewrite a.md 2>&1 | tee migrate.log + if [ ${PIPESTATUS[0]} -eq 0 ]; then + echo >&2 "fatal: expected git lfs migrate import --no-rewrite to fail, didn't" + fi + + grep "a.md did not match any Git LFS filters in .gitattributes" migrate.log ) end_test From abbd514baa0bb5ead8716abbe0b69c9db6d70071 Mon Sep 17 00:00:00 2001 From: Preben Ingvaldsen Date: Thu, 31 May 2018 10:21:07 -0700 Subject: [PATCH 64/94] git: use '/' when parsing paths to lfs filters Ensure `/` is used as the path separator when parsing Git LFS filters in nested directories. --- git/attribs.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/git/attribs.go b/git/attribs.go index 70764f1c..1a8b6cab 100644 --- a/git/attribs.go +++ b/git/attribs.go @@ -73,7 +73,7 @@ func GetAttributePaths(workingDir, gitDir string) []AttributePath { fields := strings.Fields(line) pattern := fields[0] if len(reldir) > 0 { - pattern = filepath.Join(reldir, pattern) + pattern = filepath.ToSlash(filepath.Join(reldir, pattern)) } // Find lockable flag in any position after pattern to avoid // edge case of matching "lockable" to a file pattern From 77ebf9b1443128f7ad50252dddeeb9c213f851ab Mon Sep 17 00:00:00 2001 From: Preben Ingvaldsen Date: Thu, 31 May 2018 11:18:33 -0700 Subject: [PATCH 65/94] docs: update migrate docs based on feedback * Fix various formatting issues * Add note about `--no-rewrite` commits needing to be merged into other branches --- docs/man/git-lfs-migrate.1.ronn | 56 +++++++++++++++++++-------------- 1 file changed, 32 insertions(+), 24 deletions(-) diff --git a/docs/man/git-lfs-migrate.1.ronn b/docs/man/git-lfs-migrate.1.ronn index cb049bbc..9628156d 100644 --- a/docs/man/git-lfs-migrate.1.ronn +++ b/docs/man/git-lfs-migrate.1.ronn @@ -85,37 +85,43 @@ options and these additional ones: format is CSV with this pattern: `OLD-SHA`,`NEW-SHA` * `--no-rewrite` - Migrate large objects to Git LFS in a new commit without rewriting git history. - Please note that when this option is used, the `migrate import` command will expect - a different argument list, specialized options will become available, and the core - `migrate` options will be ignored. See [IMPORT (NO REWRITE)]. + Migrate large objects to Git LFS in a new commit without rewriting git + history. Please note that when this option is used, the `migrate import` + command will expect a different argument list, specialized options will + become available, and the core `migrate` options will be ignored. See + [IMPORT (NO REWRITE)]. -If `--no-rewrite` is not provided and `--include` or `--exclude` (`-I`, `-X`, respectively) are given, the -.gitattributes will be modified to include any new filepath patterns as given by -those flags. +If `--no-rewrite` is not provided and `--include` or `--exclude` (`-I`, `-X`, +respectively) are given, the .gitattributes will be modified to include any new +filepath patterns as given by those flags. -If `--no-rewrite` is not provided and neither of those flags are given, the gitattributes will be incrementally -modified to include new filepath extensions as they are rewritten in history. +If `--no-rewrite` is not provided and neither of those flags are given, the +gitattributes will be incrementally modified to include new filepath extensions +as they are rewritten in history. ### IMPORT (NO REWRITE) -The `import` mode has a special sub-mode enabled by the `--no-rewrite` flag. This sub-mode -will migrate large objects to pointers as in the base `import` mode, but will do so in a new commit -without rewriting Git history. When using this sub-mode, the base `migrate` options, -such as `--include-ref`, will be ignored, as will those for the base `import` mode. -The `migrate` command will also take a different argument list. +The `import` mode has a special sub-mode enabled by the `--no-rewrite` flag. +This sub-mode will migrate large objects to pointers as in the base `import` +mode, but will do so in a new commit without rewriting Git history. When using +this sub-mode, the base `migrate` options, such as `--include-ref`, will be +ignored, as will those for the base `import` mode. The `migrate` command will +also take a different argument list. As a result of these changes, +`--no-rewrite` will only operate on the current branch - any other interested +branches must have the generated commit merged in. The `--no-rewrite` sub-mode supports the following options and arguments: -* `-m` `--message`= +* `-m --message=` Specifies a commit message for the newly created commit. * [file ...] - The list of files to import. These files must be tracked by patterns specified in the - gitattributes. + The list of files to import. These files must be tracked by patterns + specified in the gitattributes. -If `--message` is given, the new commit will be created with the provided message. If no message is given, -a commit message will be generated based on the file arguments. +If `--message` is given, the new commit will be created with the provided +message. If no message is given, a commit message will be generated based on the +file arguments. ## INCLUDE AND EXCLUDE @@ -219,12 +225,14 @@ Note: This will require a force push to any existing Git remotes. You can also migrate files without modifying the existing history of your respoitory: +Without a specified commit message: ``` -# Without a specified commit message -$ git lfs migrate import --no-rewrite test.zip *.mp3 *.psd - -# With a specified commit message -$ git lfs migrate import --no-rewrite -m "Import .zip, .mp3, .psd files" test.zip *.mpd *.psd + git lfs migrate import --no-rewrite test.zip *.mp3 *.psd +``` +With a specified commit message: +``` + git lfs migrate import --no-rewrite -m "Import .zip, .mp3, .psd files" \ + test.zip *.mpd *.psd ``` ## SEE ALSO From 30cdf66a219fb7da682ad2535c7dc29c8d5b68f8 Mon Sep 17 00:00:00 2001 From: Preben Ingvaldsen Date: Thu, 31 May 2018 11:19:45 -0700 Subject: [PATCH 66/94] commands: fix issues based on feedback * Exit `migrate import --no-rewrite` if attributes filter has no elements in its Include() list * In `--no-rewrite` tests checking errors, fail out of test if the command doesn't fail --- commands/command_migrate_import.go | 2 +- test/test-migrate-import-no-rewrite.sh | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/commands/command_migrate_import.go b/commands/command_migrate_import.go index 2ffa6d79..e98fdc19 100644 --- a/commands/command_migrate_import.go +++ b/commands/command_migrate_import.go @@ -49,7 +49,7 @@ func migrateImportCommand(cmd *cobra.Command, args []string) { root := commit.TreeID filter := git.GetAttributeFilter(cfg.LocalWorkingDir(), cfg.LocalGitDir()) - if len(filter.Include()) == 0 && len(filter.Exclude()) == 0 { + if len(filter.Include()) == 0 { ExitWithError(errors.Errorf("fatal: no Git LFS filters found in .gitattributes")) } diff --git a/test/test-migrate-import-no-rewrite.sh b/test/test-migrate-import-no-rewrite.sh index 26480740..be0c7b23 100755 --- a/test/test-migrate-import-no-rewrite.sh +++ b/test/test-migrate-import-no-rewrite.sh @@ -114,6 +114,7 @@ begin_test "migrate import --no-rewrite (no .gitattributes)" git lfs migrate import --no-rewrite *.txt *.md 2>&1 | tee migrate.log if [ ${PIPESTATUS[0]} -eq 0 ]; then echo >&2 "fatal: expected git lfs migrate import --no-rewrite to fail, didn't" + exit 1 fi grep "no Git LFS filters found in .gitattributes" migrate.log @@ -154,6 +155,7 @@ begin_test "migrate import --no-rewrite (nested .gitattributes)" git lfs migrate import --no-rewrite a.md 2>&1 | tee migrate.log if [ ${PIPESTATUS[0]} -eq 0 ]; then echo >&2 "fatal: expected git lfs migrate import --no-rewrite to fail, didn't" + exit 1 fi grep "a.md did not match any Git LFS filters in .gitattributes" migrate.log @@ -219,4 +221,4 @@ begin_test "migrate import --no-rewrite (with empty commit message)" exit 1 fi ) -end_test \ No newline at end of file +end_test From 6e40c67a5cdd98693cc300ad100ee7bf57658ff4 Mon Sep 17 00:00:00 2001 From: Preben Ingvaldsen Date: Thu, 31 May 2018 11:26:58 -0700 Subject: [PATCH 67/94] test: shorten repo/folder names Shorten the repo/folder names in the nested .gitattributes test to prevent AppVeyor failure --- test/test-migrate-fixtures.sh | 12 ++++++------ test/test-migrate-import-no-rewrite.sh | 8 ++++---- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/test/test-migrate-fixtures.sh b/test/test-migrate-fixtures.sh index e6f226f0..c830a46b 100755 --- a/test/test-migrate-fixtures.sh +++ b/test/test-migrate-fixtures.sh @@ -56,17 +56,17 @@ setup_local_branch_with_gitattrs() { setup_local_branch_with_nested_gitattrs() { set -e - reponame="migrate-single-remote-branch-with-nested-attrs" + reponame="nested-attrs" remove_and_create_local_repo "$reponame" - mkdir subtree + mkdir b base64 < /dev/urandom | head -c 120 > a.txt base64 < /dev/urandom | head -c 140 > a.md - base64 < /dev/urandom | head -c 140 > subtree/a.md + base64 < /dev/urandom | head -c 140 > b/a.md - git add a.txt a.md subtree/a.md + git add a.txt a.md b/a.md git commit -m "initial commit" git lfs track "*.txt" @@ -74,13 +74,13 @@ setup_local_branch_with_nested_gitattrs() { git add .gitattributes git commit -m "add .gitattributes" - cd subtree + cd b git lfs track "*.md" cd .. - git add subtree/.gitattributes + git add b/.gitattributes git commit -m "add nested .gitattributes" } diff --git a/test/test-migrate-import-no-rewrite.sh b/test/test-migrate-import-no-rewrite.sh index be0c7b23..2bae29f8 100755 --- a/test/test-migrate-import-no-rewrite.sh +++ b/test/test-migrate-import-no-rewrite.sh @@ -132,18 +132,18 @@ begin_test "migrate import --no-rewrite (nested .gitattributes)" [ !"$(echo "$master_attrs" | grep -q ".md")" ] # Ensure a .md filter exists in the nested .gitattributes - nested_attrs="$(git cat-file -p "$master:subtree/.gitattributes")" + nested_attrs="$(git cat-file -p "$master:b/.gitattributes")" echo "$nested_attrs" | grep -q "*.md filter=lfs diff=lfs merge=lfs" md_oid="$(calc_oid "$(git cat-file -p :a.md)")" - nested_md_oid="$(calc_oid "$(git cat-file -p :subtree/a.md)")" + nested_md_oid="$(calc_oid "$(git cat-file -p :b/a.md)")" txt_oid="$(calc_oid "$(git cat-file -p :a.txt)")" - git lfs migrate import --no-rewrite a.txt subtree/a.md + git lfs migrate import --no-rewrite a.txt b/a.md # Ensure a.txt and subtree/a.md were imported, even though *.md only exists in the # nested subtree/.gitattributes file - assert_pointer "refs/heads/master" "subtree/a.md" "$nested_md_oid" "140" + assert_pointer "refs/heads/master" "b/a.md" "$nested_md_oid" "140" assert_pointer "refs/heads/master" "a.txt" "$txt_oid" "120" assert_local_object "$nested_md_oid" 140 From 7caa122bae0b11fd886f01a5b62c0648716c11d6 Mon Sep 17 00:00:00 2001 From: Preben Ingvaldsen Date: Thu, 31 May 2018 14:33:46 -0700 Subject: [PATCH 68/94] git: convert separators to `/` on pattern creation Convert path separators to `/` when creating a pattern from a path to a .gitattributes filter instead of on creating the path to the filter --- git/attribs.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/git/attribs.go b/git/attribs.go index 1a8b6cab..fb690bf8 100644 --- a/git/attribs.go +++ b/git/attribs.go @@ -73,7 +73,7 @@ func GetAttributePaths(workingDir, gitDir string) []AttributePath { fields := strings.Fields(line) pattern := fields[0] if len(reldir) > 0 { - pattern = filepath.ToSlash(filepath.Join(reldir, pattern)) + pattern = filepath.Join(reldir, pattern) } // Find lockable flag in any position after pattern to avoid // edge case of matching "lockable" to a file pattern @@ -108,7 +108,9 @@ func GetAttributeFilter(workingDir, gitDir string) *filepathfilter.Filter { patterns := make([]filepathfilter.Pattern, 0, len(paths)) for _, path := range paths { - patterns = append(patterns, filepathfilter.NewPattern(path.Path)) + // Convert all separators to `/` before creating a pattern to + // avoid characters being escaped in situations like `subtree\*.md` + patterns = append(patterns, filepathfilter.NewPattern(filepath.ToSlash(path.Path))) } return filepathfilter.NewFromPatterns(patterns, nil) From e35b429ec3a40ec0b65a0d2020c957c4043e82c6 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 8 Jun 2018 11:21:22 -0500 Subject: [PATCH 69/94] git/githistory: don't write to stdout --- git/githistory/rewriter_test.go | 5 ----- 1 file changed, 5 deletions(-) diff --git a/git/githistory/rewriter_test.go b/git/githistory/rewriter_test.go index 0d570baf..40438245 100644 --- a/git/githistory/rewriter_test.go +++ b/git/githistory/rewriter_test.go @@ -3,7 +3,6 @@ package githistory import ( "bytes" "encoding/hex" - "fmt" "io" "io/ioutil" "reflect" @@ -189,10 +188,6 @@ func TestRewriterVisitsUniqueEntriesWithIdenticalContents(t *testing.T) { tree := "bbbe0a7676523ae02234bfe874784ca2380c2d4b" - fmt.Println(hex.EncodeToString(tip)) - root, _ := db.Root() - fmt.Println(root) - AssertCommitTree(t, db, hex.EncodeToString(tip), tree) // After rewriting, the HEAD state of the repository should contain a From e7f4843e2645304966b1d43aabaae69589239f4d Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 8 Jun 2018 14:53:10 -0500 Subject: [PATCH 70/94] git/githistory: add debug() to aid in debugging --- git/githistory/rewriter_test.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/git/githistory/rewriter_test.go b/git/githistory/rewriter_test.go index 40438245..afd30f0d 100644 --- a/git/githistory/rewriter_test.go +++ b/git/githistory/rewriter_test.go @@ -369,3 +369,18 @@ func TestHistoryRewriterReturnsFilter(t *testing.T) { assert.Equal(t, expected, got, "git/githistory: expected Rewriter.Filter() to return same *filepathfilter.Filter instance") } + +// debug is meant to be called from a defer statement to aide in debugging a +// test failure among any in this file. +// +// Callers are expected to call it immediately after calling the Rewrite() +// function. +func debug(t *testing.T, db *odb.ObjectDatabase, tip []byte, err error) { + root, ok := db.Root() + + t.Log(strings.Repeat("*", 80)) + t.Logf("* root=%s, ok=%t\n", root, ok) + t.Logf("* tip=%x\n", tip) + t.Logf("* err=%s\n", err) + t.Log(strings.Repeat("*", 80)) +} From 1b48d251d39afe12175cabb60a90e4bfd87e8195 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 8 Jun 2018 14:53:42 -0500 Subject: [PATCH 71/94] git/odb: do not remove trailing newline --- git/githistory/rewriter_test.go | 28 ++++++++++++++-------------- git/odb/commit.go | 6 +++++- git/odb/object_db_test.go | 2 +- 3 files changed, 20 insertions(+), 16 deletions(-) diff --git a/git/githistory/rewriter_test.go b/git/githistory/rewriter_test.go index afd30f0d..45f342a7 100644 --- a/git/githistory/rewriter_test.go +++ b/git/githistory/rewriter_test.go @@ -60,8 +60,8 @@ func TestRewriterRewritesHistory(t *testing.T) { // // 100644 blob e440e5c842586965a7fb77deda2eca68612b1f53 hello.txt - AssertCommitParent(t, db, hex.EncodeToString(tip), "911994ab82ce256433c1fa739dbbbc7142156289") - AssertCommitTree(t, db, "911994ab82ce256433c1fa739dbbbc7142156289", tree2) + AssertCommitParent(t, db, hex.EncodeToString(tip), "4aaa3f49ffeabbb874250fe13ffeb8c683aba650") + AssertCommitTree(t, db, "4aaa3f49ffeabbb874250fe13ffeb8c683aba650", tree2) AssertBlobContents(t, db, tree2, "hello.txt", "3") @@ -70,8 +70,8 @@ func TestRewriterRewritesHistory(t *testing.T) { // // 100644 blob d8263ee9860594d2806b0dfd1bfd17528b0ba2a4 hello.txt - AssertCommitParent(t, db, "911994ab82ce256433c1fa739dbbbc7142156289", "38679ebeba3403103196eb6272b326f96c928ace") - AssertCommitTree(t, db, "38679ebeba3403103196eb6272b326f96c928ace", tree3) + AssertCommitParent(t, db, "4aaa3f49ffeabbb874250fe13ffeb8c683aba650", "24a341e1ff75addc22e336a8d87f82ba56b86fcf") + AssertCommitTree(t, db, "24a341e1ff75addc22e336a8d87f82ba56b86fcf", tree3) AssertBlobContents(t, db, tree3, "hello.txt", "2") } @@ -111,14 +111,14 @@ func TestRewriterRewritesOctopusMerges(t *testing.T) { // parent 1fe2b9577d5610e8d8fb2c3030534036fb648393 // parent ca447959bdcd20253d69b227bcc7c2e1d3126d5c - AssertCommitParent(t, db, hex.EncodeToString(tip), "89ab88fb7e11a439299aa2aa77a5d98f6629b750") - AssertCommitParent(t, db, hex.EncodeToString(tip), "adf1e9085f9dd263c1bec399b995ccfa5d994721") + AssertCommitParent(t, db, hex.EncodeToString(tip), "1fe2b9577d5610e8d8fb2c3030534036fb648393") + AssertCommitParent(t, db, hex.EncodeToString(tip), "ca447959bdcd20253d69b227bcc7c2e1d3126d5c") // And each of those parents should contain the root commit as their own // parent: - AssertCommitParent(t, db, "89ab88fb7e11a439299aa2aa77a5d98f6629b750", "52daca68bcf750bb86289fd95f92f5b3bd202328") - AssertCommitParent(t, db, "adf1e9085f9dd263c1bec399b995ccfa5d994721", "52daca68bcf750bb86289fd95f92f5b3bd202328") + AssertCommitParent(t, db, "1fe2b9577d5610e8d8fb2c3030534036fb648393", "9237567f379b3c83ddf53ad9a2ae3755afb62a09") + AssertCommitParent(t, db, "ca447959bdcd20253d69b227bcc7c2e1d3126d5c", "9237567f379b3c83ddf53ad9a2ae3755afb62a09") } func TestRewriterVisitsPackedObjects(t *testing.T) { @@ -273,8 +273,8 @@ func TestRewriterAllowsAdditionalTreeEntries(t *testing.T) { // 100644 blob d8263ee9860594d2806b0dfd1bfd17528b0ba2a4 hello.txt // 100644 blob 0f2287157f7cb0dd40498c7a92f74b6975fa2d57 extra.txt - AssertCommitParent(t, db, hex.EncodeToString(tip), "54ca0fdd5ee455d872ce4b4e379abe1c4cdc39b3") - AssertCommitTree(t, db, "54ca0fdd5ee455d872ce4b4e379abe1c4cdc39b3", tree2) + AssertCommitParent(t, db, hex.EncodeToString(tip), "45af5deb9a25bc4069b15c1f5bdccb0340978707") + AssertCommitTree(t, db, "45af5deb9a25bc4069b15c1f5bdccb0340978707", tree2) AssertBlobContents(t, db, tree2, "hello.txt", "2") AssertBlobContents(t, db, tree2, "extra.txt", "extra\n") @@ -285,8 +285,8 @@ func TestRewriterAllowsAdditionalTreeEntries(t *testing.T) { // 100644 blob 56a6051ca2b02b04ef92d5150c9ef600403cb1de hello.txt // 100644 blob 0f2287157f7cb0dd40498c7a92f74b6975fa2d57 extra.txt - AssertCommitParent(t, db, "54ca0fdd5ee455d872ce4b4e379abe1c4cdc39b3", "4c52196256c611d18ad718b9b68b3d54d0a6686d") - AssertCommitTree(t, db, "4c52196256c611d18ad718b9b68b3d54d0a6686d", tree3) + AssertCommitParent(t, db, "45af5deb9a25bc4069b15c1f5bdccb0340978707", "99f6bd7cd69b45494afed95b026f3e450de8304f") + AssertCommitTree(t, db, "99f6bd7cd69b45494afed95b026f3e450de8304f", tree3) AssertBlobContents(t, db, tree3, "hello.txt", "1") AssertBlobContents(t, db, tree3, "extra.txt", "extra\n") @@ -350,8 +350,8 @@ func TestHistoryRewriterUpdatesRefs(t *testing.T) { assert.Nil(t, err) c1 := hex.EncodeToString(tip) - c2 := "86f7ba8f02edaca4f980cdd584ea8899e18b840c" - c3 := "d73b8c1a294e2371b287d9b75dbed82328ad446e" + c2 := "66561fe3ae68651658e18e48053dcfe66a2e9da1" + c3 := "8268d8486c48024a871fa42fc487dbeabd6e3d86" AssertRef(t, db, "refs/heads/master", tip) diff --git a/git/odb/commit.go b/git/odb/commit.go index bd96aa0d..bfa22b86 100644 --- a/git/odb/commit.go +++ b/git/odb/commit.go @@ -185,7 +185,11 @@ func (c *Commit) Encode(to io.Writer) (n int, err error) { n = n + n3 } - n4, err := fmt.Fprintf(to, "\n%s", c.Message) + // c.Message is built from messageParts in the Decode() function. + // + // Since each entry in messageParts _does not_ contain its trailing LF, + // append an empty string to capture the final newline. + n4, err := fmt.Fprintf(to, "\n%s\n", c.Message) if err != nil { return n, err } diff --git a/git/odb/object_db_test.go b/git/odb/object_db_test.go index 46069a62..cf2edaa5 100644 --- a/git/odb/object_db_test.go +++ b/git/odb/object_db_test.go @@ -159,7 +159,7 @@ func TestWriteCommit(t *testing.T) { Message: "initial commit", }) - expected := "77a746376fdb591a44a4848b5ba308b2d3e2a90c" + expected := "fee8a35c2890cd6e0e28d24cc457fcecbd460962" assert.Nil(t, err) assert.Equal(t, expected, hex.EncodeToString(sha)) From e2ccbab03dcbef108398f8e3c668eaf434eb8bef Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 8 Jun 2018 15:15:48 -0500 Subject: [PATCH 72/94] commands/migrate: do not migrate empty commits --- commands/command_migrate_import.go | 12 ++++++++++++ test/test-migrate-import.sh | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/commands/command_migrate_import.go b/commands/command_migrate_import.go index 3c75c972..be3812ed 100644 --- a/commands/command_migrate_import.go +++ b/commands/command_migrate_import.go @@ -71,6 +71,18 @@ func migrateImportCommand(cmd *cobra.Command, args []string) { // include set is the wildcard filepath // extensions of files tracked. ours = exts + + if ours.Cardinality() == 0 { + // If it is still the case that we have + // no patterns to track, that means that + // we are in a tree that does not + // require .gitattributes changes. + // + // We can return early to avoid + // comparing and saving an identical + // tree. + return t, nil + } } theirs, err := trackedFromAttrs(db, t) diff --git a/test/test-migrate-import.sh b/test/test-migrate-import.sh index 8785f0f9..56dee2fd 100755 --- a/test/test-migrate-import.sh +++ b/test/test-migrate-import.sh @@ -673,3 +673,21 @@ begin_test "migrate import (handle symbolic link)" refute_local_object "$link_oid" "5" ) end_test + +begin_test "migrate import (commit --allow-empty)" +( + set -e + + reponame="migrate---allow-empty" + git init "$reponame" + cd "$reponame" + + git commit --allow-empty -m "initial commit" + + original_head="$(git rev-parse HEAD)" + git lfs migrate import --everything + migrated_head="$(git rev-parse HEAD)" + + assert_ref_unmoved "HEAD" "$original_head" "$migrated_head" +) +end_test From 12dc6dd88b6bd6ea87e4faf779e0b3f28163f411 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 8 Jun 2018 15:27:39 -0500 Subject: [PATCH 73/94] tq/meter: introduce tq.Direction.Verb --- tq/meter.go | 5 +---- tq/transfer.go | 12 ++++++++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/tq/meter.go b/tq/meter.go index a42a2cbb..36a6ae2d 100644 --- a/tq/meter.go +++ b/tq/meter.go @@ -5,7 +5,6 @@ import ( "math" "os" "path/filepath" - "strings" "sync" "sync/atomic" "time" @@ -231,12 +230,10 @@ func (m *Meter) skipUpdate() bool { func (m *Meter) str() string { // (Uploading|Downloading) LFS objects: 100% (10/10) 100 MiB | 10 MiB/s - - direction := strings.Title(m.Direction.String()) + "ing" percentage := 100 * float64(m.finishedFiles) / float64(m.estimatedFiles) return fmt.Sprintf("%s LFS objects: %3.f%% (%d/%d), %s | %s", - direction, + m.Direction.Verb(), percentage, m.finishedFiles, m.estimatedFiles, humanize.FormatBytes(clamp(m.currentBytes)), diff --git a/tq/transfer.go b/tq/transfer.go index b6a31ecc..77e05aab 100644 --- a/tq/transfer.go +++ b/tq/transfer.go @@ -18,6 +18,18 @@ const ( Download = Direction(iota) ) +// Verb returns a string containing the verb form of the receiving action. +func (d Direction) Verb() string { + switch d { + case Download: + return "Downloading" + case Upload: + return "Uploading" + default: + return "" + } +} + func (d Direction) String() string { switch d { case Download: From aa2ad1243df36192b0b9303c49456df748e6d02d Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 8 Jun 2018 15:29:15 -0500 Subject: [PATCH 74/94] tq/transfer.go: add Checkout direction --- tq/transfer.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tq/transfer.go b/tq/transfer.go index 77e05aab..60484e74 100644 --- a/tq/transfer.go +++ b/tq/transfer.go @@ -16,11 +16,14 @@ type Direction int const ( Upload = Direction(iota) Download = Direction(iota) + Checkout = Direction(iota) ) // Verb returns a string containing the verb form of the receiving action. func (d Direction) Verb() string { switch d { + case Checkout: + return "Checking out" case Download: return "Downloading" case Upload: @@ -32,6 +35,8 @@ func (d Direction) Verb() string { func (d Direction) String() string { switch d { + case Checkout: + return "checkout" case Download: return "download" case Upload: From 58815a6ac4a0ed221b31d370b88d7ce080f4e665 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 8 Jun 2018 15:29:24 -0500 Subject: [PATCH 75/94] commands/checkout: ensure that the checkout direction is printed as such --- commands/command_checkout.go | 1 + test/test-checkout.sh | 24 ++++++++++++++++-------- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/commands/command_checkout.go b/commands/command_checkout.go index d26b0026..e77dcf6c 100644 --- a/commands/command_checkout.go +++ b/commands/command_checkout.go @@ -29,6 +29,7 @@ func checkoutCommand(cmd *cobra.Command, args []string) { var pointers []*lfs.WrappedPointer logger := tasklog.NewLogger(os.Stdout) meter := tq.NewMeter() + meter.Direction = tq.Checkout meter.Logger = meter.LoggerFromEnv(cfg.Os) logger.Enqueue(meter) chgitscanner := lfs.NewGitScanner(func(p *lfs.WrappedPointer, err error) { diff --git a/test/test-checkout.sh b/test/test-checkout.sh index ef0ee6ae..b0acec7a 100755 --- a/test/test-checkout.sh +++ b/test/test-checkout.sh @@ -41,65 +41,73 @@ begin_test "checkout" rm -rf file1.dat file2.dat file3.dat folder1/nested.dat folder2/nested.dat echo "checkout should replace all" - git lfs checkout + git lfs checkout 2>&1 | tee checkout.log [ "$contents" = "$(cat file1.dat)" ] [ "$contents" = "$(cat file2.dat)" ] [ "$contents" = "$(cat file3.dat)" ] [ "$contents" = "$(cat folder1/nested.dat)" ] [ "$contents" = "$(cat folder2/nested.dat)" ] + grep "Checking out LFS objects: 100% (5/5), 95 B" checkout.log # Remove the working directory rm -rf file1.dat file2.dat file3.dat folder1/nested.dat folder2/nested.dat echo "checkout with filters" - git lfs checkout file2.dat + git lfs checkout file2.dat 2>&1 | tee checkout.log [ "$contents" = "$(cat file2.dat)" ] [ ! -f file1.dat ] [ ! -f file3.dat ] [ ! -f folder1/nested.dat ] [ ! -f folder2/nested.dat ] + grep "Checking out LFS objects: 100% (1/1), 19 B" checkout.log echo "quotes to avoid shell globbing" - git lfs checkout "file*.dat" + git lfs checkout "file*.dat" 2>&1 | tee checkout.log [ "$contents" = "$(cat file1.dat)" ] [ "$contents" = "$(cat file3.dat)" ] [ ! -f folder1/nested.dat ] [ ! -f folder2/nested.dat ] + grep "Checking out LFS objects: 100% (3/3), 57 B" checkout.log echo "test subdir context" pushd folder1 - git lfs checkout nested.dat + git lfs checkout nested.dat 2>&1 | tee checkout.log + grep "Checking out LFS objects: 100% (1/1), 19 B" checkout.log [ "$contents" = "$(cat nested.dat)" ] [ ! -f ../folder2/nested.dat ] # test '.' in current dir rm nested.dat - git lfs checkout . + git lfs checkout . 2>&1 | tee checkout.log [ "$contents" = "$(cat nested.dat)" ] + grep "Checking out LFS objects: 100% (1/1), 19 B" checkout.log popd echo "test folder param" - git lfs checkout folder2 + git lfs checkout folder2 2>&1 | tee checkout.log [ "$contents" = "$(cat folder2/nested.dat)" ] + grep "Checking out LFS objects: 100% (1/1), 19 B" checkout.log echo "test '.' in current dir" rm -rf file1.dat file2.dat file3.dat folder1/nested.dat folder2/nested.dat - git lfs checkout . + git lfs checkout . 2>&1 | tee checkout.log [ "$contents" = "$(cat file1.dat)" ] [ "$contents" = "$(cat file2.dat)" ] [ "$contents" = "$(cat file3.dat)" ] [ "$contents" = "$(cat folder1/nested.dat)" ] [ "$contents" = "$(cat folder2/nested.dat)" ] + grep "Checking out LFS objects: 100% (5/5), 95 B" checkout.log echo "test checkout with missing data doesn't fail" git push origin master rm -rf .git/lfs/objects rm file*.dat - git lfs checkout + git lfs checkout 2>&1 | tee checkout.log [ "$(pointer $contents_oid $contentsize)" = "$(cat file1.dat)" ] [ "$(pointer $contents_oid $contentsize)" = "$(cat file2.dat)" ] [ "$(pointer $contents_oid $contentsize)" = "$(cat file3.dat)" ] [ "$contents" = "$(cat folder1/nested.dat)" ] [ "$contents" = "$(cat folder2/nested.dat)" ] + grep "Checking out LFS objects: 100% (5/5), 95 B" checkout.log ) end_test From 766377cdafbefb0ef65b5d95605f398a117d8bee Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Fri, 8 Jun 2018 15:56:49 -0500 Subject: [PATCH 76/94] commands/checkout: mark 'git lfs checkout' as deprecated --- commands/command_checkout.go | 10 ++++++++++ docs/man/git-lfs-checkout.1.ronn | 2 ++ 2 files changed, 12 insertions(+) diff --git a/commands/command_checkout.go b/commands/command_checkout.go index d26b0026..32b368d1 100644 --- a/commands/command_checkout.go +++ b/commands/command_checkout.go @@ -3,6 +3,7 @@ package commands import ( "fmt" "os" + "strings" "github.com/git-lfs/git-lfs/filepathfilter" "github.com/git-lfs/git-lfs/git" @@ -14,6 +15,15 @@ import ( func checkoutCommand(cmd *cobra.Command, args []string) { requireInRepo() + + msg := []string{ + "WARNING: 'git lfs checkout' is deprecated and will be removed in v3.0.0.", + + "'git checkout' has been updated in upstream Git to have comparable speeds", + "to 'git lfs checkout'.", + } + fmt.Fprintln(os.Stderr, strings.Join(msg, "\n")) + ref, err := git.CurrentRef() if err != nil { Panic(err, "Could not checkout") diff --git a/docs/man/git-lfs-checkout.1.ronn b/docs/man/git-lfs-checkout.1.ronn index c7dd82f3..adab6a91 100644 --- a/docs/man/git-lfs-checkout.1.ronn +++ b/docs/man/git-lfs-checkout.1.ronn @@ -7,6 +7,8 @@ git-lfs-checkout(1) -- Update working copy with file content if available ## DESCRIPTION +This command is deprecated, and should be replaced with `git checkout`. + Try to ensure that the working copy contains file content for Git LFS objects for the current ref, if the object data is available. Does not download any content, see git-lfs-fetch(1) for that. From d2e4b9b40ddb582e7de9f0bbba9dadcb0097522c Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 11 Jun 2018 12:12:59 -0500 Subject: [PATCH 77/94] test/test-checkout.sh: remove extraneous grepping --- test/test-checkout.sh | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/test/test-checkout.sh b/test/test-checkout.sh index b0acec7a..1a5f2df5 100755 --- a/test/test-checkout.sh +++ b/test/test-checkout.sh @@ -53,25 +53,23 @@ begin_test "checkout" rm -rf file1.dat file2.dat file3.dat folder1/nested.dat folder2/nested.dat echo "checkout with filters" - git lfs checkout file2.dat 2>&1 | tee checkout.log + git lfs checkout file2.dat [ "$contents" = "$(cat file2.dat)" ] [ ! -f file1.dat ] [ ! -f file3.dat ] [ ! -f folder1/nested.dat ] [ ! -f folder2/nested.dat ] - grep "Checking out LFS objects: 100% (1/1), 19 B" checkout.log echo "quotes to avoid shell globbing" - git lfs checkout "file*.dat" 2>&1 | tee checkout.log + git lfs checkout "file*.dat" [ "$contents" = "$(cat file1.dat)" ] [ "$contents" = "$(cat file3.dat)" ] [ ! -f folder1/nested.dat ] [ ! -f folder2/nested.dat ] - grep "Checking out LFS objects: 100% (3/3), 57 B" checkout.log echo "test subdir context" pushd folder1 - git lfs checkout nested.dat 2>&1 | tee checkout.log + git lfs checkout nested.dat 2>&1 grep "Checking out LFS objects: 100% (1/1), 19 B" checkout.log [ "$contents" = "$(cat nested.dat)" ] [ ! -f ../folder2/nested.dat ] @@ -79,35 +77,31 @@ begin_test "checkout" rm nested.dat git lfs checkout . 2>&1 | tee checkout.log [ "$contents" = "$(cat nested.dat)" ] - grep "Checking out LFS objects: 100% (1/1), 19 B" checkout.log popd echo "test folder param" - git lfs checkout folder2 2>&1 | tee checkout.log + git lfs checkout folder2 [ "$contents" = "$(cat folder2/nested.dat)" ] - grep "Checking out LFS objects: 100% (1/1), 19 B" checkout.log echo "test '.' in current dir" rm -rf file1.dat file2.dat file3.dat folder1/nested.dat folder2/nested.dat - git lfs checkout . 2>&1 | tee checkout.log + git lfs checkout . [ "$contents" = "$(cat file1.dat)" ] [ "$contents" = "$(cat file2.dat)" ] [ "$contents" = "$(cat file3.dat)" ] [ "$contents" = "$(cat folder1/nested.dat)" ] [ "$contents" = "$(cat folder2/nested.dat)" ] - grep "Checking out LFS objects: 100% (5/5), 95 B" checkout.log echo "test checkout with missing data doesn't fail" git push origin master rm -rf .git/lfs/objects rm file*.dat - git lfs checkout 2>&1 | tee checkout.log + git lfs checkout [ "$(pointer $contents_oid $contentsize)" = "$(cat file1.dat)" ] [ "$(pointer $contents_oid $contentsize)" = "$(cat file2.dat)" ] [ "$(pointer $contents_oid $contentsize)" = "$(cat file3.dat)" ] [ "$contents" = "$(cat folder1/nested.dat)" ] [ "$contents" = "$(cat folder2/nested.dat)" ] - grep "Checking out LFS objects: 100% (5/5), 95 B" checkout.log ) end_test From 830f611f5722b790535bd896ec6abd50d7883589 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 11 Jun 2018 12:28:14 -0500 Subject: [PATCH 78/94] test/test-checkout.sh: remove logging grep site --- test/test-checkout.sh | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/test-checkout.sh b/test/test-checkout.sh index 1a5f2df5..cd2633c8 100755 --- a/test/test-checkout.sh +++ b/test/test-checkout.sh @@ -69,8 +69,7 @@ begin_test "checkout" echo "test subdir context" pushd folder1 - git lfs checkout nested.dat 2>&1 - grep "Checking out LFS objects: 100% (1/1), 19 B" checkout.log + git lfs checkout nested.dat [ "$contents" = "$(cat nested.dat)" ] [ ! -f ../folder2/nested.dat ] # test '.' in current dir From 47fa8523cda3582937077b63dd71d33db5390731 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 11 Jun 2018 15:27:11 -0500 Subject: [PATCH 79/94] docs/man/git-lfs.1.ronn: update casing and missing commands --- docs/man/git-lfs.1.ronn | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/man/git-lfs.1.ronn b/docs/man/git-lfs.1.ronn index dc5cc42e..f8c8c96d 100644 --- a/docs/man/git-lfs.1.ronn +++ b/docs/man/git-lfs.1.ronn @@ -33,7 +33,7 @@ commands and low level ("plumbing") commands. Display the Git LFS environment. * git-lfs-checkout(1): Populate working copy with real content from Git LFS files. -* git lfs clone: +* git-lfs-clone(1): Efficiently clone a Git LFS-enabled repository. * git-lfs-fetch(1): Download Git LFS files from a remote. @@ -46,15 +46,16 @@ commands and low level ("plumbing") commands. * git-lfs-locks(1): List currently "locked" files from the Git LFS server. * git-lfs-logs(1): - Show errors from the git-lfs command. + Show errors from the Git LFS command. * git-lfs-ls-files(1): Show information about Git LFS files in the index and working tree. * git-lfs-migrate(1): - Migrate history to or from git-lfs + Migrate history to or from Git LFS * git-lfs-prune(1): Delete old Git LFS files from local storage * git-lfs-pull(1): - Fetch LFS changes from the remote & checkout any required working tree files. + Fetch Git LFS changes from the remote & checkout any required working tree + files. * git-lfs-push(1): Push queued large files to the Git LFS endpoint. * git-lfs-status(1): @@ -69,7 +70,7 @@ commands and low level ("plumbing") commands. Remove Git LFS paths from Git Attributes. * git-lfs-update(1): Update Git hooks for the current Git repository. -* git lfs version: +* git-lfs-version(1): Report the version number. ### Low level commands (plumbing) @@ -80,5 +81,7 @@ commands and low level ("plumbing") commands. Build and compare pointers. * git-lfs-pre-push(1): Git pre-push hook implementation. +* git-lfs-filter-process(1): + Git process filter that converts between large files and pointers. * git-lfs-smudge(1): Git smudge filter that converts pointer in blobs to the actual content. From 5db937016a371a039458fc6e5694fee1644fc1fb Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Wed, 13 Jun 2018 12:24:15 -0500 Subject: [PATCH 80/94] lfsapi: prefer proxying from gitconfig before environment --- lfsapi/proxy.go | 17 ++++++++++------- lfsapi/proxy_test.go | 2 +- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/lfsapi/proxy.go b/lfsapi/proxy.go index d67f2dcd..c7410774 100644 --- a/lfsapi/proxy.go +++ b/lfsapi/proxy.go @@ -49,13 +49,6 @@ func proxyFromClient(c *Client) func(req *http.Request) (*url.URL, error) { } func getProxyServers(u *url.URL, urlCfg *config.URLConfig, osEnv config.Environment) (httpsProxy string, httpProxy string, noProxy string) { - if urlCfg != nil { - httpProxy, _ = urlCfg.Get("http", u.String(), "proxy") - if strings.HasPrefix(httpProxy, "https://") { - httpsProxy = httpProxy - } - } - if osEnv == nil { return } @@ -76,6 +69,16 @@ func getProxyServers(u *url.URL, urlCfg *config.URLConfig, osEnv config.Environm httpProxy, _ = osEnv.Get("http_proxy") } + if urlCfg != nil { + gitProxy, ok := urlCfg.Get("http", u.String(), "proxy") + if len(gitProxy) > 0 && ok { + if strings.HasPrefix(gitProxy, "https://") { + httpsProxy = gitProxy + } + httpProxy = gitProxy + } + } + noProxy, _ = osEnv.Get("NO_PROXY") if len(noProxy) == 0 { noProxy, _ = osEnv.Get("no_proxy") diff --git a/lfsapi/proxy_test.go b/lfsapi/proxy_test.go index ad98419b..e8e7e76a 100644 --- a/lfsapi/proxy_test.go +++ b/lfsapi/proxy_test.go @@ -20,7 +20,7 @@ func TestHttpsProxyFromGitConfig(t *testing.T) { require.Nil(t, err) proxyURL, err := proxyFromClient(c)(req) - assert.Equal(t, "proxy-from-git-config:8080", proxyURL.Host) + assert.Equal(t, "proxy-from-env:8080", proxyURL.Host) assert.Nil(t, err) } From 624b88b38aac1dbd946aaac48a4ee61099d64c73 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Wed, 13 Jun 2018 14:07:19 -0500 Subject: [PATCH 81/94] git/git.go: pass --multiple to git-fetch(1) when appropriate --- git/git.go | 8 +++++++- test/test-migrate-fixtures.sh | 25 +++++++++++++++++++++++++ test/test-migrate-import.sh | 16 ++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/git/git.go b/git/git.go index fd542571..51507ba6 100644 --- a/git/git.go +++ b/git/git.go @@ -975,7 +975,13 @@ func Fetch(remotes ...string) error { return nil } - _, err := gitNoLFSSimple(append([]string{"fetch"}, remotes...)...) + var args []string + if len(remotes) > 1 { + args = []string{"--multiple", "--"} + } + args = append(args, remotes...) + + _, err := gitNoLFSSimple(append([]string{"fetch"}, args...)...) return err } diff --git a/test/test-migrate-fixtures.sh b/test/test-migrate-fixtures.sh index c830a46b..5beee7d9 100755 --- a/test/test-migrate-fixtures.sh +++ b/test/test-migrate-fixtures.sh @@ -308,6 +308,31 @@ setup_single_local_branch_with_annotated_tags() { git tag "v1.0.0" -m "v1.0.0" } +setup_multiple_remotes() { + set -e + + reponame="migrate-multiple-remotes" + remove_and_create_remote_repo "$reponame" + + forkname="$(git remote -v \ + | head -n1 \ + | cut -d ' ' -f 1 \ + | sed -e 's/^.*\///g')-fork" + ( setup_remote_repo "$forkname" ) + + git remote add fork "$GITSERVER/$forkname" + + base64 < /dev/urandom | head -c 16 > a.txt + git add a.txt + git commit -m "initial commit" + git push origin master + + base64 < /dev/urandom | head -c 16 > a.txt + git add a.txt + git commit -m "another commit" + git push fork master +} + # setup_single_local_branch_deep_trees creates a repository as follows: # # A diff --git a/test/test-migrate-import.sh b/test/test-migrate-import.sh index 56dee2fd..22517d0b 100755 --- a/test/test-migrate-import.sh +++ b/test/test-migrate-import.sh @@ -691,3 +691,19 @@ begin_test "migrate import (commit --allow-empty)" assert_ref_unmoved "HEAD" "$original_head" "$migrated_head" ) end_test + +begin_test "migrate import (multiple remotes)" +( + set -e + + setup_multiple_remotes + + original_master="$(git rev-parse master)" + + git lfs migrate import + + migrated_master="$(git rev-parse master)" + + assert_ref_unmoved "master" "$original_master" "$migrated_master" +) +end_test From c6383b9ca36c29b6300828da48b532781c9d01f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Wed, 13 Jun 2018 17:25:17 -0400 Subject: [PATCH 82/94] add basic example in main manpage Every time I go back to git LFS after a long break, I wonder how it works and how to get started. The first manual page is currently a reference to a fairly large number of other manual pages and, as the core documentation of LFS, does not really help users in getting basic things done. In comparison, the LFS homepage has a good primer, so I have taken it as an example for a basic example that would work in the manual page to help users get out of the weeds quickly. --- docs/man/git-lfs.1.ronn | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/docs/man/git-lfs.1.ronn b/docs/man/git-lfs.1.ronn index dc5cc42e..bd23ca10 100644 --- a/docs/man/git-lfs.1.ronn +++ b/docs/man/git-lfs.1.ronn @@ -82,3 +82,28 @@ commands and low level ("plumbing") commands. Git pre-push hook implementation. * git-lfs-smudge(1): Git smudge filter that converts pointer in blobs to the actual content. + +## EXAMPLES + +To get started with Git LFS, the following commands can be used. + + 1. Setup Git LFS on your system. You only have to do this once per + repository per machine: + + git lfs install + + 2. Choose the type of files you want to track, for examples all `ISO` + images, with git-lfs-track(1): + + git lfs track "*.iso" + + 3. The above stores this information in gitattributes(5) files, so + that file need to be added to the repository: + + git add .gitattributes + + 3. Commit, push and work with the files normally: + + git add file.iso + git commit -m "Add disk image" + git push From 2e22042f90fa9f27894e8c0d79bd8e76f181da6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Wed, 13 Jun 2018 17:26:27 -0400 Subject: [PATCH 83/94] point to gitignore in track manpage We point to the online manual for gitignore, but it's not very useful when reading the manual pages with man or another offline manpage viewer. A more useful pointer is in the SEE ALSO section at the bottom. --- docs/man/git-lfs-track.1.ronn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/man/git-lfs-track.1.ronn b/docs/man/git-lfs-track.1.ronn index 234880e6..41810bca 100644 --- a/docs/man/git-lfs-track.1.ronn +++ b/docs/man/git-lfs-track.1.ronn @@ -59,6 +59,6 @@ to match paths. ## SEE ALSO -git-lfs-untrack(1), git-lfs-install(1), gitattributes(5). +git-lfs-untrack(1), git-lfs-install(1), gitattributes(5), gitignore(5). Part of the git-lfs(1) suite. From 45289c68264c8b8f7d5889045e03dd5d449926ab Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 18 Jun 2018 18:52:36 -0500 Subject: [PATCH 84/94] README.md: add link to installation wiki page --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8bc3c65b..07716375 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,9 @@ setup and preferences. In addition, [binary packages](https://github.com/git-lfs/git-lfs/releases) are available for Linux, macOS, Windows, and FreeBSD. This repository can also be -built-from-source using the latest version of [Go](https://golang.org). +built from source using the latest version of [Go](https://golang.org), and the +available instructions in our +[Wiki](https://github.com/git-lfs/git-lfs/wiki/Installation#source). ### Usage From 44b7e44094719eaf3bc7f7470dcf3d2edcf63e5b Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 18 Jun 2018 19:18:48 -0500 Subject: [PATCH 85/94] git/attribs.go: extract attrPaths from GetAttributePaths --- git/attribs.go | 92 +++++++++++++++++++++++++++----------------------- 1 file changed, 50 insertions(+), 42 deletions(-) diff --git a/git/attribs.go b/git/attribs.go index fb690bf8..8cf81b1c 100644 --- a/git/attribs.go +++ b/git/attribs.go @@ -43,58 +43,66 @@ func GetAttributePaths(workingDir, gitDir string) []AttributePath { paths := make([]AttributePath, 0) for _, path := range findAttributeFiles(workingDir, gitDir) { - attributes, err := os.Open(path) - if err != nil { + paths = append(paths, attrPaths(path, workingDir)...) + } + + return paths +} + +func attrPaths(path, workingDir string) []AttributePath { + attributes, err := os.Open(path) + if err != nil { + return nil + } + + var paths []AttributePath + + relfile, _ := filepath.Rel(workingDir, path) + reldir := filepath.Dir(relfile) + source := &AttributeSource{Path: relfile} + + le := &lineEndingSplitter{} + scanner := bufio.NewScanner(attributes) + scanner.Split(le.ScanLines) + + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + + if strings.HasPrefix(line, "#") { continue } - relfile, _ := filepath.Rel(workingDir, path) - reldir := filepath.Dir(relfile) - source := &AttributeSource{Path: relfile} + // Check for filter=lfs (signifying that LFS is tracking + // this file) or "lockable", which indicates that the + // file is lockable (and may or may not be tracked by + // Git LFS). + if strings.Contains(line, "filter=lfs") || + strings.HasSuffix(line, "lockable") { - le := &lineEndingSplitter{} - scanner := bufio.NewScanner(attributes) - scanner.Split(le.ScanLines) - - for scanner.Scan() { - line := strings.TrimSpace(scanner.Text()) - - if strings.HasPrefix(line, "#") { - continue + fields := strings.Fields(line) + pattern := fields[0] + if len(reldir) > 0 { + pattern = filepath.Join(reldir, pattern) } - - // Check for filter=lfs (signifying that LFS is tracking - // this file) or "lockable", which indicates that the - // file is lockable (and may or may not be tracked by - // Git LFS). - if strings.Contains(line, "filter=lfs") || - strings.HasSuffix(line, "lockable") { - - fields := strings.Fields(line) - pattern := fields[0] - if len(reldir) > 0 { - pattern = filepath.Join(reldir, pattern) + // Find lockable flag in any position after pattern to avoid + // edge case of matching "lockable" to a file pattern + lockable := false + for _, f := range fields[1:] { + if f == LockableAttrib { + lockable = true + break } - // Find lockable flag in any position after pattern to avoid - // edge case of matching "lockable" to a file pattern - lockable := false - for _, f := range fields[1:] { - if f == LockableAttrib { - lockable = true - break - } - } - paths = append(paths, AttributePath{ - Path: pattern, - Source: source, - Lockable: lockable, - }) } + paths = append(paths, AttributePath{ + Path: pattern, + Source: source, + Lockable: lockable, + }) } - - source.LineEnding = le.LineEnding() } + source.LineEnding = le.LineEnding() + return paths } From f99790b70bdf0ef9a89de6f63756e45a610b304e Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 18 Jun 2018 19:28:39 -0500 Subject: [PATCH 86/94] commands: extract getAllKnownPatterns() --- commands/command_track.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/commands/command_track.go b/commands/command_track.go index 5ba06925..a70bb28b 100644 --- a/commands/command_track.go +++ b/commands/command_track.go @@ -49,7 +49,7 @@ func trackCommand(cmd *cobra.Command, args []string) { return } - knownPatterns := git.GetAttributePaths(cfg.LocalWorkingDir(), cfg.LocalGitDir()) + knownPatterns := getAllKnownPatterns() lineEnd := getAttributeLineEnding(knownPatterns) if len(lineEnd) == 0 { lineEnd = gitLineEnding(cfg.Git) @@ -213,7 +213,7 @@ ArgsLoop: } func listPatterns() { - knownPatterns := git.GetAttributePaths(cfg.LocalWorkingDir(), cfg.LocalGitDir()) + knownPatterns := getAllKnownPatterns() if len(knownPatterns) < 1 { return } @@ -228,6 +228,12 @@ func listPatterns() { } } +func getAllKnownPatterns() []git.AttributePath { + knownPatterns := git.GetAttributePaths(cfg.LocalWorkingDir(), cfg.LocalGitDir()) + + return knownPatterns +} + func getAttributeLineEnding(attribs []git.AttributePath) string { for _, a := range attribs { if a.Source.Path == ".gitattributes" { From b0de5dc8831ca814d69a5f353497d97f4f96b854 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 18 Jun 2018 19:19:10 -0500 Subject: [PATCH 87/94] git/attribs.go: consider root attribute paths --- commands/command_track.go | 1 + git/attribs.go | 12 ++++++++++++ 2 files changed, 13 insertions(+) diff --git a/commands/command_track.go b/commands/command_track.go index a70bb28b..5077c9fb 100644 --- a/commands/command_track.go +++ b/commands/command_track.go @@ -230,6 +230,7 @@ func listPatterns() { func getAllKnownPatterns() []git.AttributePath { knownPatterns := git.GetAttributePaths(cfg.LocalWorkingDir(), cfg.LocalGitDir()) + knownPatterns = append(knownPatterns, git.GetRootAttributePaths(cfg.Git)...) return knownPatterns } diff --git a/git/attribs.go b/git/attribs.go index 8cf81b1c..0f80e829 100644 --- a/git/attribs.go +++ b/git/attribs.go @@ -35,6 +35,18 @@ func (s *AttributeSource) String() string { return s.Path } +// GetRootAttributePaths beahves as GetRootAttributePaths, and loads information +// only from the global gitattributes file. +func GetRootAttributePaths(cfg Env) []AttributePath { + af, ok := cfg.Get("core.attributesfile") + if !ok { + return nil + } + + // The working directory for the root gitattributes file is blank. + return attrPaths(af, "") +} + // GetAttributePaths returns a list of entries in .gitattributes which are // configured with the filter=lfs attribute // workingDir is the root of the working copy From 1f0214adee47d55ee34e27797c945b15a9b5e777 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 18 Jun 2018 19:19:25 -0500 Subject: [PATCH 88/94] git/attribs.go: consider system attribute paths --- commands/command_track.go | 1 + git/attribs.go | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/commands/command_track.go b/commands/command_track.go index 5077c9fb..94a43c08 100644 --- a/commands/command_track.go +++ b/commands/command_track.go @@ -231,6 +231,7 @@ func listPatterns() { func getAllKnownPatterns() []git.AttributePath { knownPatterns := git.GetAttributePaths(cfg.LocalWorkingDir(), cfg.LocalGitDir()) knownPatterns = append(knownPatterns, git.GetRootAttributePaths(cfg.Git)...) + knownPatterns = append(knownPatterns, git.GetSystemAttributePaths(cfg.Os)...) return knownPatterns } diff --git a/git/attribs.go b/git/attribs.go index 0f80e829..6a033b55 100644 --- a/git/attribs.go +++ b/git/attribs.go @@ -47,6 +47,24 @@ func GetRootAttributePaths(cfg Env) []AttributePath { return attrPaths(af, "") } +// GetSystemAttributePaths behaves as GetAttributePaths, and loads information +// only from the system gitattributes file, respecting the $PREFIX environment +// variable. +func GetSystemAttributePaths(env Env) []AttributePath { + prefix, _ := env.Get("PREFIX") + if len(prefix) == 0 { + prefix = string(filepath.Separator) + } + + path := filepath.Join(prefix, "etc", "gitattributes") + + if _, err := os.Stat(path); os.IsNotExist(err) { + return nil + } + + return attrPaths(path, "") +} + // GetAttributePaths returns a list of entries in .gitattributes which are // configured with the filter=lfs attribute // workingDir is the root of the working copy From 719921585e7a655a1de4458b18f7891b04506b6a Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 18 Jun 2018 19:30:46 -0500 Subject: [PATCH 89/94] test/test-track: examine global gitattributes --- test/test-track.sh | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/test/test-track.sh b/test/test-track.sh index 02ff7ce0..453e27a0 100755 --- a/test/test-track.sh +++ b/test/test-track.sh @@ -558,3 +558,21 @@ begin_test "track (with current-directory prefix)" grep -e "^a.dat" .gitattributes ) end_test + +begin_test "track (global gitattributes)" +( + set -e + + reponame="track-global-gitattributes" + git init "$reponame" + cd "$reponame" + + global="$(cd .. && pwd)/gitattributes-global" + + echo "*.dat filter=lfs diff=lfs merge=lfs -text" > "$global" + git config --local core.attributesfile "$global" + + git lfs track 2>&1 | tee track.log + grep "*.dat" track.log +) +end_test From 0cdbe90662a1876866a582af1f0a8690b2f63fa2 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 18 Jun 2018 19:42:22 -0500 Subject: [PATCH 90/94] test/test-track: examine system gitattributes --- test/test-track.sh | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/test/test-track.sh b/test/test-track.sh index 453e27a0..3823a1c7 100755 --- a/test/test-track.sh +++ b/test/test-track.sh @@ -576,3 +576,22 @@ begin_test "track (global gitattributes)" grep "*.dat" track.log ) end_test + +begin_test "track (system gitattributes)" +( + set -e + + reponame="track-system-gitattributes" + git init "$reponame" + cd "$reponame" + + pushd "$TRASHDIR" > /dev/null + mkdir -p "prefix/${reponame}/etc" + cd "prefix/${reponame}/etc" + echo "*.dat filter=lfs diff=lfs merge=lfs -text" > gitattributes + popd > /dev/null + + PREFIX="${TRASHDIR}/prefix/${reponame}" git lfs track 2>&1 | tee track.log + grep "*.dat" track.log +) +end_test From 707a7175a70cc2c25df9552090ecd2d019fdff35 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Mon, 18 Jun 2018 19:55:27 -0500 Subject: [PATCH 91/94] commands/command_track: allow overwriting repository-level patterns --- commands/command_track.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/commands/command_track.go b/commands/command_track.go index 94a43c08..8d160dcb 100644 --- a/commands/command_track.go +++ b/commands/command_track.go @@ -49,7 +49,9 @@ func trackCommand(cmd *cobra.Command, args []string) { return } - knownPatterns := getAllKnownPatterns() + // Intentionally do _not_ consider global- and system-level + // .gitattributes here. + knownPatterns := git.GetAttributePaths(cfg.LocalWorkingDir(), cfg.LocalGitDir()) lineEnd := getAttributeLineEnding(knownPatterns) if len(lineEnd) == 0 { lineEnd = gitLineEnding(cfg.Git) From 5d645c2ad1dfc8b624d541489fcbad4b05d2008a Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Thu, 21 Jun 2018 15:37:24 -0500 Subject: [PATCH 92/94] commands/status: open files with absolute paths --- commands/command_status.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/commands/command_status.go b/commands/command_status.go index 010b499b..3e60421f 100644 --- a/commands/command_status.go +++ b/commands/command_status.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "os" + "path/filepath" "regexp" "strings" @@ -134,7 +135,7 @@ func blobInfo(s *lfs.PointerScanner, blobSha, name string) (sha, from string, er return s.ContentsSha()[:7], from, nil } - f, err := os.Open(name) + f, err := os.Open(filepath.Join(cfg.LocalWorkingDir(), name)) if err != nil { return "", "", err } From 3d879fec4ea17a60a9038e50ed878c1e79ba6b24 Mon Sep 17 00:00:00 2001 From: Taylor Blau Date: Thu, 21 Jun 2018 15:24:18 -0500 Subject: [PATCH 93/94] commands/status: make paths relative to the working directory --- commands/command_status.go | 49 +++++++++++++++++++++++++++++++++++--- test/test-status.sh | 28 ++++++++++++++++++++++ 2 files changed, 74 insertions(+), 3 deletions(-) diff --git a/commands/command_status.go b/commands/command_status.go index 3e60421f..47bec0ca 100644 --- a/commands/command_status.go +++ b/commands/command_status.go @@ -53,19 +53,29 @@ func statusCommand(cmd *cobra.Command, args []string) { ExitWithError(err) } + wd, _ := os.Getwd() + repo := cfg.LocalWorkingDir() + Print("\nGit LFS objects to be committed:\n") for _, entry := range staged { + // Find a path from the current working directory to the + // absolute path of each side of the entry. + src := relativize(wd, filepath.Join(repo, entry.SrcName)) + dst := relativize(wd, filepath.Join(repo, entry.DstName)) + switch entry.Status { case lfs.StatusRename, lfs.StatusCopy: - Print("\t%s -> %s (%s)", entry.SrcName, entry.DstName, formatBlobInfo(scanner, entry)) + Print("\t%s -> %s (%s)", src, dst, formatBlobInfo(scanner, entry)) default: - Print("\t%s (%s)", entry.SrcName, formatBlobInfo(scanner, entry)) + Print("\t%s (%s)", src, formatBlobInfo(scanner, entry)) } } Print("\nGit LFS objects not staged for commit:\n") for _, entry := range unstaged { - Print("\t%s (%s)", entry.SrcName, formatBlobInfo(scanner, entry)) + src := relativize(wd, filepath.Join(repo, entry.SrcName)) + + Print("\t%s (%s)", src, formatBlobInfo(scanner, entry)) } Print("") @@ -312,6 +322,39 @@ func porcelainStatusLine(entry *lfs.DiffIndexEntry) string { return fmt.Sprintf("%s %s", entry.Status, entry.SrcName) } +// relativize relatives a path from "from" to "to". For instance, note that, for +// any paths "from" and "to", that: +// +// to == filepath.Clean(filepath.Join(from, relativize(from, to))) +func relativize(from, to string) string { + if len(from) == 0 { + return to + } + + flist := strings.Split(filepath.ToSlash(from), "/") + tlist := strings.Split(filepath.ToSlash(to), "/") + + var ( + divergence int + min int + ) + + if lf, lt := len(flist), len(tlist); lf < lt { + min = lf + } else { + min = lt + } + + for ; divergence < min; divergence++ { + if flist[divergence] != tlist[divergence] { + break + } + } + + return strings.Repeat("../", len(flist)-divergence) + + strings.Join(tlist[divergence:], "/") +} + func init() { RegisterCommand("status", statusCommand, func(cmd *cobra.Command) { cmd.Flags().BoolVarP(&porcelain, "porcelain", "p", false, "Give the output in an easy-to-parse format for scripts.") diff --git a/test/test-status.sh b/test/test-status.sh index cfe437e6..3c6ab029 100755 --- a/test/test-status.sh +++ b/test/test-status.sh @@ -119,6 +119,34 @@ begin_test "status --json" ) end_test +begin_test "status in a sub-directory" +( + set -e + + reponame="status-sub-directory" + git init "$reponame" + cd "$reponame" + + git lfs track "*.dat" + printf "asdf" > file.dat + mkdir -p dir + git add .gitattributes file.dat + git commit -m "initial commit" + + printf "ASDF" > file.dat + + expected="On branch master + +Git LFS objects to be committed: + + +Git LFS objects not staged for commit: + + ../file.dat (LFS: f0e4c2f -> File: 99b3bcf)" + + [ "$expected" = "$(cd dir && git lfs status)" ] +) +end_test begin_test "status: outside git repository" ( From 9236a1a32dd404f905ea3cabf11016d303f1dacd Mon Sep 17 00:00:00 2001 From: Stephen Gelman Date: Fri, 22 Jun 2018 17:49:52 -0500 Subject: [PATCH 94/94] Run `go generate` on commands in deb build The deb packages don't currently run `go generate` when building which means commands like `git-lfs help` don't work properly. This changes the packaging script to run it. Fixes #3043 --- debian/rules | 1 + 1 file changed, 1 insertion(+) diff --git a/debian/rules b/debian/rules index ddae758a..a20376d7 100755 --- a/debian/rules +++ b/debian/rules @@ -32,6 +32,7 @@ override_dh_clean: dh_clean override_dh_auto_build: + cd ${BUILD_DIR}/src/github.com/git-lfs/git-lfs && go generate ./commands dh_auto_build #dh_golang doesn't do anything here in deb 8, and it's needed in both if [ "$(DEB_HOST_GNU_TYPE)" != "$(DEB_BUILD_GNU_TYPE)" ]; then\