From 1f8662cd9518c3d1e14d058f2a88d438b59170b2 Mon Sep 17 00:00:00 2001 From: decentral1se Date: Tue, 9 Jul 2024 13:57:54 +0200 Subject: [PATCH] refactor: urfave v3 --- cli/app/app.go | 12 +- cli/app/backup.go | 63 +- cli/app/check.go | 25 +- cli/app/cmd.go | 67 +- cli/app/config.go | 35 +- cli/app/cp.go | 30 +- cli/app/deploy.go | 28 +- cli/app/list.go | 21 +- cli/app/logs.go | 16 +- cli/app/new.go | 34 +- cli/app/ps.go | 14 +- cli/app/remove.go | 19 +- cli/app/restart.go | 26 +- cli/app/restore.go | 16 +- cli/app/rollback.go | 26 +- cli/app/run.go | 30 +- cli/app/secret.go | 114 +- cli/app/services.go | 22 +- cli/app/undeploy.go | 19 +- cli/app/upgrade.go | 26 +- cli/app/volume.go | 46 +- cli/catalogue/catalogue.go | 30 +- cli/cli.go | 101 +- cli/internal/cli.go | 11 +- cli/internal/errors.go | 6 +- cli/internal/validate.go | 36 +- cli/recipe/diff.go | 27 +- cli/recipe/fetch.go | 30 +- cli/recipe/lint.go | 17 +- cli/recipe/list.go | 17 +- cli/recipe/new.go | 18 +- cli/recipe/recipe.go | 16 +- cli/recipe/release.go | 26 +- cli/recipe/reset.go | 29 +- cli/recipe/sync.go | 22 +- cli/recipe/upgrade.go | 39 +- cli/recipe/version.go | 17 +- cli/server/add.go | 37 +- cli/server/list.go | 27 +- cli/server/prune.go | 26 +- cli/server/remove.go | 28 +- cli/server/server.go | 11 +- cli/updater/updater.go | 68 +- go.mod | 7 +- go.sum | 8 +- pkg/autocomplete/autocomplete.go | 19 +- scripts/autocomplete/bash | 24 +- scripts/autocomplete/fish | 2 +- scripts/autocomplete/powershell | 2 +- scripts/autocomplete/zsh | 39 +- .../Azure/go-ansiterm/winterm/ansi.go | 1 - .../Azure/go-ansiterm/winterm/api.go | 1 - .../go-ansiterm/winterm/attr_translation.go | 1 - .../go-ansiterm/winterm/cursor_helpers.go | 1 - .../go-ansiterm/winterm/erase_helpers.go | 1 - .../go-ansiterm/winterm/scroll_helper.go | 1 - .../Azure/go-ansiterm/winterm/utilities.go | 1 - .../go-ansiterm/winterm/win_event_handler.go | 1 - .../ProtonMail/go-crypto/openpgp/keys.go | 4 +- .../go-crypto/openpgp/packet/private_key.go | 8 +- .../ProtonMail/go-crypto/openpgp/s2k/s2k.go | 19 +- .../go-crypto/openpgp/s2k/s2k_cache.go | 2 +- .../go-crypto/openpgp/s2k/s2k_config.go | 6 +- .../beorn7/perks/quantile/stream.go | 2 +- .../cenkalti/backoff/v4/exponential.go | 38 +- .../image/docker/reference/reference.go | 4 +- .../pkg/docker/config/config_unsupported.go | 1 - .../containers/image/pkg/keyctl/key.go | 1 - .../containers/image/pkg/keyctl/keyring.go | 1 - .../containers/image/pkg/keyctl/perm.go | 1 - .../containers/image/pkg/keyctl/sys_linux.go | 1 - .../containers/image/types/types.go | 29 +- .../cpuguy83/go-md2man/v2/LICENSE.md | 21 - .../cpuguy83/go-md2man/v2/md2man/md2man.go | 16 - .../cpuguy83/go-md2man/v2/md2man/roff.go | 382 --- .../github.com/davecgh/go-spew/spew/bypass.go | 1 - .../davecgh/go-spew/spew/bypasssafe.go | 1 - .../github.com/davecgh/go-spew/spew/config.go | 30 +- vendor/github.com/davecgh/go-spew/spew/doc.go | 128 +- .../github.com/davecgh/go-spew/spew/dump.go | 18 +- .../github.com/docker/go-metrics/namespace.go | 4 +- .../docker/go/canonical/json/decode.go | 3 +- .../docker/go/canonical/json/encode.go | 28 +- .../docker/go/canonical/json/fold.go | 5 +- .../docker/go/canonical/json/stream.go | 1 + .../emirpasic/gods/containers/iterator.go | 4 +- .../gods/lists/arraylist/arraylist.go | 2 +- .../emirpasic/gods/utils/comparator.go | 7 +- .../httpsnoop/wrap_generated_gteq_1.8.go | 2 - .../httpsnoop/wrap_generated_lt_1.8.go | 2 - vendor/github.com/ghodss/yaml/fields.go | 5 +- vendor/github.com/ghodss/yaml/yaml.go | 12 +- vendor/github.com/go-git/gcfg/doc.go | 89 +- vendor/github.com/go-git/gcfg/errors.go | 7 +- .../github.com/go-git/gcfg/scanner/errors.go | 4 + vendor/github.com/go-git/gcfg/set.go | 2 +- .../github.com/go-git/gcfg/token/position.go | 17 + vendor/github.com/go-git/gcfg/token/token.go | 4 + .../go-git/go-billy/v5/memfs/memory.go | 2 +- .../go-git/go-billy/v5/util/walk.go | 8 +- .../go-git/v5/plumbing/format/config/doc.go | 189 +- .../v5/plumbing/format/config/encoder.go | 5 +- .../v5/plumbing/format/config/option.go | 2 +- .../v5/plumbing/format/config/section.go | 13 +- .../v5/plumbing/format/gitignore/doc.go | 96 +- .../go-git/v5/plumbing/format/idxfile/doc.go | 200 +- .../go-git/v5/plumbing/format/index/doc.go | 474 +-- .../go-git/v5/plumbing/format/index/index.go | 4 +- .../go-git/v5/plumbing/format/packfile/doc.go | 45 +- .../go-git/v5/plumbing/object/object.go | 24 +- .../v5/plumbing/protocol/packp/updreq.go | 1 - .../go-git/go-git/v5/utils/binary/read.go | 7 +- .../utils/merkletrie/internal/frame/frame.go | 5 +- .../go-git/go-git/v5/utils/merkletrie/iter.go | 17 +- .../go-git/v5/utils/merkletrie/noder/noder.go | 2 +- .../go-git/go-git/v5/worktree_bsd.go | 1 - .../go-git/go-git/v5/worktree_js.go | 1 - .../go-git/go-git/v5/worktree_linux.go | 1 - .../go-git/go-git/v5/worktree_unix_other.go | 1 - .../go-git/go-git/v5/worktree_windows.go | 1 - vendor/github.com/gogo/protobuf/proto/lib.go | 36 +- .../gogo/protobuf/proto/pointer_reflect.go | 1 - .../protobuf/proto/pointer_reflect_gogo.go | 1 - .../gogo/protobuf/proto/pointer_unsafe.go | 1 - .../protobuf/proto/pointer_unsafe_gogo.go | 1 - .../gogo/protobuf/proto/table_unmarshal.go | 14 +- .../google/go-cmp/cmp/report_references.go | 4 +- vendor/github.com/google/shlex/shlex.go | 19 +- vendor/github.com/google/uuid/dce.go | 4 +- vendor/github.com/google/uuid/hash.go | 4 +- vendor/github.com/google/uuid/node_js.go | 1 - vendor/github.com/google/uuid/node_net.go | 1 - vendor/github.com/google/uuid/null.go | 17 +- vendor/github.com/google/uuid/uuid.go | 10 +- vendor/github.com/google/uuid/version4.go | 14 +- .../github.com/hashicorp/go-cleanhttp/doc.go | 1 + .../kballard/go-shellquote/unquote.go | 2 +- .../kevinburke/ssh_config/config.go | 4 +- .../lucasb-eyer/go-colorful/hsluv.go | 3 +- .../mattn/go-isatty/isatty_windows.go | 3 +- vendor/github.com/mgutz/ansi/doc.go | 4 +- vendor/github.com/miekg/pkcs11/params.go | 13 +- .../opencontainers/go-digest/digest.go | 2 +- .../opencontainers/go-digest/doc.go | 11 +- vendor/github.com/pkg/errors/errors.go | 74 +- vendor/github.com/pkg/errors/go113.go | 1 - vendor/github.com/pkg/errors/stack.go | 20 +- .../pmezard/go-difflib/difflib/difflib.go | 21 +- .../russross/blackfriday/v2/.gitignore | 8 - .../russross/blackfriday/v2/.travis.yml | 17 - .../russross/blackfriday/v2/LICENSE.txt | 29 - .../russross/blackfriday/v2/README.md | 335 -- .../russross/blackfriday/v2/block.go | 1612 ---------- .../github.com/russross/blackfriday/v2/doc.go | 46 - .../russross/blackfriday/v2/entities.go | 2236 -------------- .../github.com/russross/blackfriday/v2/esc.go | 70 - .../russross/blackfriday/v2/html.go | 952 ------ .../russross/blackfriday/v2/inline.go | 1230 -------- .../russross/blackfriday/v2/markdown.go | 954 ------ .../russross/blackfriday/v2/node.go | 360 --- .../russross/blackfriday/v2/smartypants.go | 457 --- .../sergi/go-diff/diffmatchpatch/diff.go | 6 +- .../sergi/go-diff/diffmatchpatch/patch.go | 4 +- vendor/github.com/sirupsen/logrus/doc.go | 26 +- .../github.com/sirupsen/logrus/formatter.go | 4 +- vendor/github.com/sirupsen/logrus/logger.go | 18 +- .../logrus/terminal_check_appengine.go | 1 - .../sirupsen/logrus/terminal_check_bsd.go | 1 - .../sirupsen/logrus/terminal_check_js.go | 1 - .../logrus/terminal_check_no_terminal.go | 1 - .../logrus/terminal_check_notappengine.go | 1 - .../sirupsen/logrus/terminal_check_unix.go | 1 - .../sirupsen/logrus/terminal_check_windows.go | 1 - vendor/github.com/spf13/pflag/flag.go | 19 +- vendor/github.com/spf13/pflag/string_slice.go | 28 +- .../notary/client/client.go | 2 +- .../notary/client/reader.go | 2 +- .../theupdateframework/notary/client/repo.go | 1 - .../notary/client/repo_pkcs11.go | 1 - .../notary/const_nowindows.go | 1 - .../notary/const_windows.go | 1 - .../notary/trustmanager/yubikey/import.go | 1 - .../trustmanager/yubikey/pkcs11_darwin.go | 1 - .../trustmanager/yubikey/pkcs11_interface.go | 1 - .../trustmanager/yubikey/pkcs11_linux.go | 1 - .../trustmanager/yubikey/yubikeystore.go | 1 - .../notary/tuf/utils/pkcs8.go | 2 +- vendor/github.com/urfave/cli/.flake8 | 2 - vendor/github.com/urfave/cli/.gitignore | 10 - .../github.com/urfave/cli/CODE_OF_CONDUCT.md | 74 - vendor/github.com/urfave/cli/LICENSE | 21 - vendor/github.com/urfave/cli/README.md | 51 - vendor/github.com/urfave/cli/app.go | 531 ---- vendor/github.com/urfave/cli/category.go | 44 - vendor/github.com/urfave/cli/cli.go | 24 - vendor/github.com/urfave/cli/command.go | 386 --- vendor/github.com/urfave/cli/context.go | 348 --- vendor/github.com/urfave/cli/docs.go | 151 - vendor/github.com/urfave/cli/errors.go | 115 - vendor/github.com/urfave/cli/fish.go | 194 -- vendor/github.com/urfave/cli/flag.go | 348 --- vendor/github.com/urfave/cli/flag_bool.go | 109 - vendor/github.com/urfave/cli/flag_bool_t.go | 110 - vendor/github.com/urfave/cli/flag_duration.go | 106 - vendor/github.com/urfave/cli/flag_float64.go | 106 - vendor/github.com/urfave/cli/flag_generic.go | 110 - vendor/github.com/urfave/cli/flag_int.go | 105 - vendor/github.com/urfave/cli/flag_int64.go | 106 - .../github.com/urfave/cli/flag_int64_slice.go | 199 -- .../github.com/urfave/cli/flag_int_slice.go | 198 -- vendor/github.com/urfave/cli/flag_string.go | 98 - .../urfave/cli/flag_string_slice.go | 184 -- vendor/github.com/urfave/cli/flag_uint.go | 106 - vendor/github.com/urfave/cli/flag_uint64.go | 106 - vendor/github.com/urfave/cli/funcs.go | 44 - vendor/github.com/urfave/cli/help.go | 363 --- vendor/github.com/urfave/cli/parse.go | 94 - vendor/github.com/urfave/cli/template.go | 121 - vendor/github.com/urfave/cli/v2/.flake8 | 2 - vendor/github.com/urfave/cli/v2/README.md | 19 - vendor/github.com/urfave/cli/v2/app.go | 536 ---- vendor/github.com/urfave/cli/v2/args.go | 54 - vendor/github.com/urfave/cli/v2/cli.go | 25 - vendor/github.com/urfave/cli/v2/command.go | 421 --- vendor/github.com/urfave/cli/v2/context.go | 272 -- vendor/github.com/urfave/cli/v2/docs.go | 203 -- .../github.com/urfave/cli/v2/flag-spec.yaml | 131 - vendor/github.com/urfave/cli/v2/flag_bool.go | 178 -- .../github.com/urfave/cli/v2/flag_duration.go | 108 - .../github.com/urfave/cli/v2/flag_float64.go | 107 - .../urfave/cli/v2/flag_float64_slice.go | 216 -- .../github.com/urfave/cli/v2/flag_generic.go | 131 - vendor/github.com/urfave/cli/v2/flag_int.go | 109 - vendor/github.com/urfave/cli/v2/flag_int64.go | 108 - .../urfave/cli/v2/flag_int64_slice.go | 215 -- .../urfave/cli/v2/flag_int_slice.go | 226 -- vendor/github.com/urfave/cli/v2/flag_path.go | 102 - .../github.com/urfave/cli/v2/flag_string.go | 100 - .../urfave/cli/v2/flag_string_slice.go | 216 -- .../urfave/cli/v2/flag_timestamp.go | 205 -- vendor/github.com/urfave/cli/v2/flag_uint.go | 108 - .../github.com/urfave/cli/v2/flag_uint64.go | 108 - .../urfave/cli/v2/flag_uint64_slice.go | 219 -- .../urfave/cli/v2/flag_uint_slice.go | 230 -- .../urfave/cli/v2/godoc-current.txt | 2724 ----------------- vendor/github.com/urfave/cli/v2/help.go | 564 ---- .../github.com/urfave/cli/v2/mkdocs-reqs.txt | 5 - vendor/github.com/urfave/cli/v2/sliceflag.go | 290 -- vendor/github.com/urfave/cli/v2/sort.go | 29 - .../github.com/urfave/cli/v2/suggestions.go | 68 - .../urfave/cli/v2/zz_generated.flags.go | 865 ------ .../urfave/cli/{v2 => v3}/.gitignore | 3 - .../urfave/cli/{v2 => v3}/.golangci.yaml | 1 + .../urfave/cli/{v2 => v3}/CODE_OF_CONDUCT.md | 0 .../github.com/urfave/cli/{v2 => v3}/LICENSE | 2 +- .../github.com/urfave/cli/{v2 => v3}/Makefile | 2 +- vendor/github.com/urfave/cli/v3/README.md | 56 + vendor/github.com/urfave/cli/v3/args.go | 153 + .../cli/v3/autocomplete/bash_autocomplete | 35 + .../autocomplete/powershell_autocomplete.ps1 | 9 + .../cli/v3/autocomplete/zsh_autocomplete | 30 + .../urfave/cli/{v2 => v3}/category.go | 23 +- vendor/github.com/urfave/cli/v3/cli.go | 60 + vendor/github.com/urfave/cli/v3/command.go | 1296 ++++++++ vendor/github.com/urfave/cli/v3/completion.go | 68 + .../urfave/cli/{v2 => v3}/errors.go | 55 +- .../github.com/urfave/cli/{v2 => v3}/fish.go | 83 +- .../github.com/urfave/cli/{v2 => v3}/flag.go | 210 +- vendor/github.com/urfave/cli/v3/flag_bool.go | 87 + .../urfave/cli/v3/flag_bool_with_inverse.go | 194 ++ .../github.com/urfave/cli/v3/flag_duration.go | 47 + .../urfave/cli/{v2 => v3}/flag_ext.go | 0 vendor/github.com/urfave/cli/v3/flag_float.go | 48 + .../urfave/cli/v3/flag_float_slice.go | 35 + vendor/github.com/urfave/cli/v3/flag_impl.go | 286 ++ vendor/github.com/urfave/cli/v3/flag_int.go | 59 + .../urfave/cli/v3/flag_int_slice.go | 20 + .../github.com/urfave/cli/v3/flag_map_impl.go | 116 + vendor/github.com/urfave/cli/v3/flag_mutex.go | 56 + .../urfave/cli/v3/flag_slice_base.go | 110 + .../github.com/urfave/cli/v3/flag_string.go | 66 + .../urfave/cli/v3/flag_string_map.go | 20 + .../urfave/cli/v3/flag_string_slice.go | 20 + .../urfave/cli/v3/flag_timestamp.go | 152 + vendor/github.com/urfave/cli/v3/flag_uint.go | 54 + .../urfave/cli/v3/flag_uint_slice.go | 20 + .../github.com/urfave/cli/{v2 => v3}/funcs.go | 29 +- .../urfave/cli/v3/godoc-current.txt | 1038 +++++++ vendor/github.com/urfave/cli/v3/help.go | 588 ++++ .../github.com/urfave/cli/v3/mkdocs-reqs.txt | 5 + .../urfave/cli/{v2 => v3}/mkdocs.yml | 4 +- .../github.com/urfave/cli/{v2 => v3}/parse.go | 32 +- vendor/github.com/urfave/cli/{ => v3}/sort.go | 0 .../github.com/urfave/cli/v3/staticcheck.conf | 1 + .../github.com/urfave/cli/v3/suggestions.go | 147 + .../urfave/cli/{v2 => v3}/template.go | 72 +- .../github.com/urfave/cli/v3/value_source.go | 145 + .../github.com/xeipuuv/gojsonschema/schema.go | 1 + .../xeipuuv/gojsonschema/schemaLoader.go | 2 +- vendor/github.com/xrash/smetrics/.travis.yml | 9 - vendor/github.com/xrash/smetrics/LICENSE | 21 - vendor/github.com/xrash/smetrics/README.md | 49 - vendor/github.com/xrash/smetrics/doc.go | 19 - vendor/github.com/xrash/smetrics/hamming.go | 25 - .../github.com/xrash/smetrics/jaro-winkler.go | 28 - vendor/github.com/xrash/smetrics/jaro.go | 86 - vendor/github.com/xrash/smetrics/soundex.go | 63 - vendor/github.com/xrash/smetrics/ukkonen.go | 94 - .../xrash/smetrics/wagner-fischer.go | 48 - .../proto/otlp/metrics/v1/metrics.pb.go | 96 +- .../proto/otlp/trace/v1/trace.pb.go | 2 +- .../x/sys/unix/syscall_zos_s390x.go | 8 +- .../x/text/internal/language/lookup.go | 56 +- vendor/golang.org/x/text/language/tables.go | 6 +- .../protobuf/internal/impl/merge_gen.go | 2 + vendor/gopkg.in/warnings.v0/warnings.go | 97 +- vendor/gopkg.in/yaml.v2/apic.go | 2 +- vendor/gopkg.in/yaml.v2/emitterc.go | 7 +- vendor/gopkg.in/yaml.v2/parserc.go | 140 +- vendor/gopkg.in/yaml.v2/readerc.go | 2 +- vendor/gopkg.in/yaml.v2/resolve.go | 2 +- vendor/gopkg.in/yaml.v2/scannerc.go | 34 +- vendor/gopkg.in/yaml.v2/sorter.go | 2 +- vendor/gopkg.in/yaml.v2/yaml.go | 55 +- vendor/gopkg.in/yaml.v2/yamlh.go | 9 +- vendor/gopkg.in/yaml.v3/apic.go | 8 +- vendor/gopkg.in/yaml.v3/emitterc.go | 9 +- vendor/gopkg.in/yaml.v3/parserc.go | 140 +- vendor/gopkg.in/yaml.v3/readerc.go | 8 +- vendor/gopkg.in/yaml.v3/scannerc.go | 42 +- vendor/gopkg.in/yaml.v3/writerc.go | 8 +- vendor/gopkg.in/yaml.v3/yaml.go | 75 +- vendor/gopkg.in/yaml.v3/yamlh.go | 10 +- vendor/gopkg.in/yaml.v3/yamlprivateh.go | 20 +- .../v3/internal/difflib/difflib.go | 16 +- vendor/modules.txt | 13 +- 336 files changed, 7332 insertions(+), 25145 deletions(-) delete mode 100644 vendor/github.com/cpuguy83/go-md2man/v2/LICENSE.md delete mode 100644 vendor/github.com/cpuguy83/go-md2man/v2/md2man/md2man.go delete mode 100644 vendor/github.com/cpuguy83/go-md2man/v2/md2man/roff.go delete mode 100644 vendor/github.com/russross/blackfriday/v2/.gitignore delete mode 100644 vendor/github.com/russross/blackfriday/v2/.travis.yml delete mode 100644 vendor/github.com/russross/blackfriday/v2/LICENSE.txt delete mode 100644 vendor/github.com/russross/blackfriday/v2/README.md delete mode 100644 vendor/github.com/russross/blackfriday/v2/block.go delete mode 100644 vendor/github.com/russross/blackfriday/v2/doc.go delete mode 100644 vendor/github.com/russross/blackfriday/v2/entities.go delete mode 100644 vendor/github.com/russross/blackfriday/v2/esc.go delete mode 100644 vendor/github.com/russross/blackfriday/v2/html.go delete mode 100644 vendor/github.com/russross/blackfriday/v2/inline.go delete mode 100644 vendor/github.com/russross/blackfriday/v2/markdown.go delete mode 100644 vendor/github.com/russross/blackfriday/v2/node.go delete mode 100644 vendor/github.com/russross/blackfriday/v2/smartypants.go delete mode 100644 vendor/github.com/urfave/cli/.flake8 delete mode 100644 vendor/github.com/urfave/cli/.gitignore delete mode 100644 vendor/github.com/urfave/cli/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/urfave/cli/LICENSE delete mode 100644 vendor/github.com/urfave/cli/README.md delete mode 100644 vendor/github.com/urfave/cli/app.go delete mode 100644 vendor/github.com/urfave/cli/category.go delete mode 100644 vendor/github.com/urfave/cli/cli.go delete mode 100644 vendor/github.com/urfave/cli/command.go delete mode 100644 vendor/github.com/urfave/cli/context.go delete mode 100644 vendor/github.com/urfave/cli/docs.go delete mode 100644 vendor/github.com/urfave/cli/errors.go delete mode 100644 vendor/github.com/urfave/cli/fish.go delete mode 100644 vendor/github.com/urfave/cli/flag.go delete mode 100644 vendor/github.com/urfave/cli/flag_bool.go delete mode 100644 vendor/github.com/urfave/cli/flag_bool_t.go delete mode 100644 vendor/github.com/urfave/cli/flag_duration.go delete mode 100644 vendor/github.com/urfave/cli/flag_float64.go delete mode 100644 vendor/github.com/urfave/cli/flag_generic.go delete mode 100644 vendor/github.com/urfave/cli/flag_int.go delete mode 100644 vendor/github.com/urfave/cli/flag_int64.go delete mode 100644 vendor/github.com/urfave/cli/flag_int64_slice.go delete mode 100644 vendor/github.com/urfave/cli/flag_int_slice.go delete mode 100644 vendor/github.com/urfave/cli/flag_string.go delete mode 100644 vendor/github.com/urfave/cli/flag_string_slice.go delete mode 100644 vendor/github.com/urfave/cli/flag_uint.go delete mode 100644 vendor/github.com/urfave/cli/flag_uint64.go delete mode 100644 vendor/github.com/urfave/cli/funcs.go delete mode 100644 vendor/github.com/urfave/cli/help.go delete mode 100644 vendor/github.com/urfave/cli/parse.go delete mode 100644 vendor/github.com/urfave/cli/template.go delete mode 100644 vendor/github.com/urfave/cli/v2/.flake8 delete mode 100644 vendor/github.com/urfave/cli/v2/README.md delete mode 100644 vendor/github.com/urfave/cli/v2/app.go delete mode 100644 vendor/github.com/urfave/cli/v2/args.go delete mode 100644 vendor/github.com/urfave/cli/v2/cli.go delete mode 100644 vendor/github.com/urfave/cli/v2/command.go delete mode 100644 vendor/github.com/urfave/cli/v2/context.go delete mode 100644 vendor/github.com/urfave/cli/v2/docs.go delete mode 100644 vendor/github.com/urfave/cli/v2/flag-spec.yaml delete mode 100644 vendor/github.com/urfave/cli/v2/flag_bool.go delete mode 100644 vendor/github.com/urfave/cli/v2/flag_duration.go delete mode 100644 vendor/github.com/urfave/cli/v2/flag_float64.go delete mode 100644 vendor/github.com/urfave/cli/v2/flag_float64_slice.go delete mode 100644 vendor/github.com/urfave/cli/v2/flag_generic.go delete mode 100644 vendor/github.com/urfave/cli/v2/flag_int.go delete mode 100644 vendor/github.com/urfave/cli/v2/flag_int64.go delete mode 100644 vendor/github.com/urfave/cli/v2/flag_int64_slice.go delete mode 100644 vendor/github.com/urfave/cli/v2/flag_int_slice.go delete mode 100644 vendor/github.com/urfave/cli/v2/flag_path.go delete mode 100644 vendor/github.com/urfave/cli/v2/flag_string.go delete mode 100644 vendor/github.com/urfave/cli/v2/flag_string_slice.go delete mode 100644 vendor/github.com/urfave/cli/v2/flag_timestamp.go delete mode 100644 vendor/github.com/urfave/cli/v2/flag_uint.go delete mode 100644 vendor/github.com/urfave/cli/v2/flag_uint64.go delete mode 100644 vendor/github.com/urfave/cli/v2/flag_uint64_slice.go delete mode 100644 vendor/github.com/urfave/cli/v2/flag_uint_slice.go delete mode 100644 vendor/github.com/urfave/cli/v2/godoc-current.txt delete mode 100644 vendor/github.com/urfave/cli/v2/help.go delete mode 100644 vendor/github.com/urfave/cli/v2/mkdocs-reqs.txt delete mode 100644 vendor/github.com/urfave/cli/v2/sliceflag.go delete mode 100644 vendor/github.com/urfave/cli/v2/sort.go delete mode 100644 vendor/github.com/urfave/cli/v2/suggestions.go delete mode 100644 vendor/github.com/urfave/cli/v2/zz_generated.flags.go rename vendor/github.com/urfave/cli/{v2 => v3}/.gitignore (52%) rename vendor/github.com/urfave/cli/{v2 => v3}/.golangci.yaml (84%) rename vendor/github.com/urfave/cli/{v2 => v3}/CODE_OF_CONDUCT.md (100%) rename vendor/github.com/urfave/cli/{v2 => v3}/LICENSE (96%) rename vendor/github.com/urfave/cli/{v2 => v3}/Makefile (92%) create mode 100644 vendor/github.com/urfave/cli/v3/README.md create mode 100644 vendor/github.com/urfave/cli/v3/args.go create mode 100644 vendor/github.com/urfave/cli/v3/autocomplete/bash_autocomplete create mode 100644 vendor/github.com/urfave/cli/v3/autocomplete/powershell_autocomplete.ps1 create mode 100644 vendor/github.com/urfave/cli/v3/autocomplete/zsh_autocomplete rename vendor/github.com/urfave/cli/{v2 => v3}/category.go (89%) create mode 100644 vendor/github.com/urfave/cli/v3/cli.go create mode 100644 vendor/github.com/urfave/cli/v3/command.go create mode 100644 vendor/github.com/urfave/cli/v3/completion.go rename vendor/github.com/urfave/cli/{v2 => v3}/errors.go (78%) rename vendor/github.com/urfave/cli/{v2 => v3}/fish.go (59%) rename vendor/github.com/urfave/cli/{v2 => v3}/flag.go (66%) create mode 100644 vendor/github.com/urfave/cli/v3/flag_bool.go create mode 100644 vendor/github.com/urfave/cli/v3/flag_bool_with_inverse.go create mode 100644 vendor/github.com/urfave/cli/v3/flag_duration.go rename vendor/github.com/urfave/cli/{v2 => v3}/flag_ext.go (100%) create mode 100644 vendor/github.com/urfave/cli/v3/flag_float.go create mode 100644 vendor/github.com/urfave/cli/v3/flag_float_slice.go create mode 100644 vendor/github.com/urfave/cli/v3/flag_impl.go create mode 100644 vendor/github.com/urfave/cli/v3/flag_int.go create mode 100644 vendor/github.com/urfave/cli/v3/flag_int_slice.go create mode 100644 vendor/github.com/urfave/cli/v3/flag_map_impl.go create mode 100644 vendor/github.com/urfave/cli/v3/flag_mutex.go create mode 100644 vendor/github.com/urfave/cli/v3/flag_slice_base.go create mode 100644 vendor/github.com/urfave/cli/v3/flag_string.go create mode 100644 vendor/github.com/urfave/cli/v3/flag_string_map.go create mode 100644 vendor/github.com/urfave/cli/v3/flag_string_slice.go create mode 100644 vendor/github.com/urfave/cli/v3/flag_timestamp.go create mode 100644 vendor/github.com/urfave/cli/v3/flag_uint.go create mode 100644 vendor/github.com/urfave/cli/v3/flag_uint_slice.go rename vendor/github.com/urfave/cli/{v2 => v3}/funcs.go (59%) create mode 100644 vendor/github.com/urfave/cli/v3/godoc-current.txt create mode 100644 vendor/github.com/urfave/cli/v3/help.go create mode 100644 vendor/github.com/urfave/cli/v3/mkdocs-reqs.txt rename vendor/github.com/urfave/cli/{v2 => v3}/mkdocs.yml (96%) rename vendor/github.com/urfave/cli/{v2 => v3}/parse.go (75%) rename vendor/github.com/urfave/cli/{ => v3}/sort.go (100%) create mode 100644 vendor/github.com/urfave/cli/v3/staticcheck.conf create mode 100644 vendor/github.com/urfave/cli/v3/suggestions.go rename vendor/github.com/urfave/cli/{v2 => v3}/template.go (59%) create mode 100644 vendor/github.com/urfave/cli/v3/value_source.go delete mode 100644 vendor/github.com/xrash/smetrics/.travis.yml delete mode 100644 vendor/github.com/xrash/smetrics/LICENSE delete mode 100644 vendor/github.com/xrash/smetrics/README.md delete mode 100644 vendor/github.com/xrash/smetrics/doc.go delete mode 100644 vendor/github.com/xrash/smetrics/hamming.go delete mode 100644 vendor/github.com/xrash/smetrics/jaro-winkler.go delete mode 100644 vendor/github.com/xrash/smetrics/jaro.go delete mode 100644 vendor/github.com/xrash/smetrics/soundex.go delete mode 100644 vendor/github.com/xrash/smetrics/ukkonen.go delete mode 100644 vendor/github.com/xrash/smetrics/wagner-fischer.go diff --git a/cli/app/app.go b/cli/app/app.go index 72ff7da1..60745f5a 100644 --- a/cli/app/app.go +++ b/cli/app/app.go @@ -1,15 +1,15 @@ package app import ( - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var AppCommand = cli.Command{ - Name: "app", - Aliases: []string{"a"}, - Usage: "Manage apps", - ArgsUsage: "", - Subcommands: []*cli.Command{ + Name: "app", + Aliases: []string{"a"}, + Usage: "Manage apps", + UsageText: "abra app [command] [options] [arguments]", + Commands: []*cli.Command{ &appBackupCommand, &appCheckCommand, &appCmdCommand, diff --git a/cli/app/backup.go b/cli/app/backup.go index 879e21bc..96f0583b 100644 --- a/cli/app/backup.go +++ b/cli/app/backup.go @@ -1,13 +1,14 @@ package app import ( + "context" "fmt" "coopcloud.tech/abra/cli/internal" "coopcloud.tech/abra/pkg/autocomplete" "coopcloud.tech/abra/pkg/client" "coopcloud.tech/abra/pkg/log" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var snapshot string @@ -38,16 +39,16 @@ var appBackupListCommand = cli.Command{ Name: "list", Aliases: []string{"ls"}, Flags: []cli.Flag{ - internal.DebugFlag, - internal.OfflineFlag, snapshotFlag, includePathFlag, }, - Before: internal.SubCommandBefore, - Usage: "List all backups", - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + Before: internal.SubCommandBefore, + Usage: "List all backups", + UsageText: "abra app backup list [options]", + ShellComplete: autocomplete.AppNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) if err := app.Recipe.Ensure(internal.Chaos, internal.Offline); err != nil { log.Fatal(err) @@ -85,16 +86,16 @@ var appBackupDownloadCommand = cli.Command{ Name: "download", Aliases: []string{"d"}, Flags: []cli.Flag{ - internal.DebugFlag, - internal.OfflineFlag, snapshotFlag, includePathFlag, }, - Before: internal.SubCommandBefore, - Usage: "Download a backup", - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + Before: internal.SubCommandBefore, + Usage: "Download a backup", + UsageText: "abra app backup download [options]", + ShellComplete: autocomplete.AppNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) if err := app.Recipe.EnsureExists(); err != nil { log.Fatal(err) @@ -156,15 +157,15 @@ var appBackupCreateCommand = cli.Command{ Name: "create", Aliases: []string{"c"}, Flags: []cli.Flag{ - internal.DebugFlag, - internal.OfflineFlag, resticRepoFlag, }, - Before: internal.SubCommandBefore, - Usage: "Create a new backup", - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + Before: internal.SubCommandBefore, + Usage: "Create a new backup", + UsageText: "abra app backup create [options]", + ShellComplete: autocomplete.AppNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) if err := app.Recipe.EnsureExists(); err != nil { log.Fatal(err) @@ -214,15 +215,15 @@ var appBackupSnapshotsCommand = cli.Command{ Name: "snapshots", Aliases: []string{"s"}, Flags: []cli.Flag{ - internal.DebugFlag, - internal.OfflineFlag, snapshotFlag, }, - Before: internal.SubCommandBefore, - Usage: "List backup snapshots", - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + Before: internal.SubCommandBefore, + Usage: "List backup snapshots", + UsageText: "abra app backup snapshots [options]", + ShellComplete: autocomplete.AppNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) if err := app.Recipe.EnsureExists(); err != nil { log.Fatal(err) @@ -272,8 +273,8 @@ var appBackupCommand = cli.Command{ Name: "backup", Aliases: []string{"b"}, Usage: "Manage app backups", - ArgsUsage: "", - Subcommands: []*cli.Command{ + UsageText: "abra app backup [command] [arguments] [options]", + Commands: []*cli.Command{ &appBackupListCommand, &appBackupSnapshotsCommand, &appBackupDownloadCommand, diff --git a/cli/app/check.go b/cli/app/check.go index 6b083cde..c2fa312c 100644 --- a/cli/app/check.go +++ b/cli/app/check.go @@ -1,6 +1,7 @@ package app import ( + "context" "fmt" "coopcloud.tech/abra/cli/internal" @@ -9,16 +10,15 @@ import ( "coopcloud.tech/abra/pkg/formatter" "coopcloud.tech/abra/pkg/log" "github.com/charmbracelet/lipgloss" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var appCheckCommand = cli.Command{ - Name: "check", - Aliases: []string{"chk"}, - Usage: "Ensure an app is well configured", - Description: ` -This command compares env vars in both the app ".env" and recipe ".env.sample" -file. + Name: "check", + Aliases: []string{"chk"}, + UsageText: "abra app check [options]", + Usage: "Ensure an app is well configured", + Description: `Compare env vars in both the app ".env" and recipe ".env.sample" file. The goal is to ensure that recipe ".env.sample" env vars are defined in your app ".env" file. Only env var definitions in the ".env.sample" which are @@ -28,16 +28,15 @@ these env vars, then "check" will complain. Recipe maintainers may or may not provide defaults for env vars within their recipes regardless of commenting or not (e.g. through the use of ${FOO:} syntax). "check" does not confirm or deny this for you.`, - ArgsUsage: "", Flags: []cli.Flag{ - internal.DebugFlag, internal.ChaosFlag, internal.OfflineFlag, }, - Before: internal.SubCommandBefore, - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.AppNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) if err := app.Recipe.Ensure(internal.Chaos, internal.Offline); err != nil { log.Fatal(err) diff --git a/cli/app/cmd.go b/cli/app/cmd.go index 26baea0e..3350c3ce 100644 --- a/cli/app/cmd.go +++ b/cli/app/cmd.go @@ -1,6 +1,7 @@ package app import ( + "context" "errors" "fmt" "os" @@ -14,61 +15,53 @@ import ( "coopcloud.tech/abra/pkg/autocomplete" "coopcloud.tech/abra/pkg/client" "coopcloud.tech/abra/pkg/log" - "github.com/urfave/cli/v2" + "coopcloud.tech/abra/pkg/recipe" + "github.com/urfave/cli/v3" ) var appCmdCommand = cli.Command{ - Name: "command", - Aliases: []string{"cmd"}, - Usage: "Run app commands", + Name: "command", + Aliases: []string{"cmd"}, + Usage: "Run app commands", + UsageText: "abra app cmd [] [] [options]", Description: `Run an app specific command. These commands are bash functions, defined in the abra.sh of the recipe itself. They can be run within the context of a service (e.g. app) or locally on your -work station by passing "--local". Arguments can be passed into these functions -using the "-- " syntax. - -**WARNING**: options must be passed directly after the sub-command "cmd". - -EXAMPLE: - - abra app cmd --local example.com app create_user -- me@example.com`, - ArgsUsage: " [] [-- ]", +work station by passing "--local".`, Flags: []cli.Flag{ - internal.DebugFlag, internal.LocalCmdFlag, internal.RemoteUserFlag, internal.TtyFlag, - internal.OfflineFlag, internal.ChaosFlag, }, Before: internal.SubCommandBefore, - Subcommands: []*cli.Command{ + Commands: []*cli.Command{ &appCmdListCommand, }, - BashComplete: func(ctx *cli.Context) { - args := ctx.Args() + ShellComplete: func(ctx context.Context, cmd *cli.Command) { + args := cmd.Args() switch args.Len() { case 0: - autocomplete.AppNameComplete(ctx) + autocomplete.AppNameComplete(ctx, cmd) case 1: autocomplete.ServiceNameComplete(args.Get(0)) case 2: cmdNameComplete(args.Get(0)) } }, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) if err := app.Recipe.Ensure(internal.Chaos, internal.Offline); err != nil { log.Fatal(err) } if internal.LocalCmd && internal.RemoteUser != "" { - internal.ShowSubcommandHelpAndError(c, errors.New("cannot use --local & --user together")) + internal.ShowSubcommandHelpAndError(cmd, errors.New("cannot use --local & --user together")) } - hasCmdArgs, parsedCmdArgs := parseCmdArgs(c.Args().Slice(), internal.LocalCmd) + hasCmdArgs, parsedCmdArgs := parseCmdArgs(cmd.Args().Slice(), internal.LocalCmd) if _, err := os.Stat(app.Recipe.AbraShPath); err != nil { if os.IsNotExist(err) { @@ -78,11 +71,11 @@ EXAMPLE: } if internal.LocalCmd { - if !(c.Args().Len() >= 2) { - internal.ShowSubcommandHelpAndError(c, errors.New("missing arguments")) + if !(cmd.Args().Len() >= 2) { + internal.ShowSubcommandHelpAndError(cmd, errors.New("missing arguments")) } - cmdName := c.Args().Get(1) + cmdName := cmd.Args().Get(1) if err := internal.EnsureCommand(app.Recipe.AbraShPath, app.Recipe.Name, cmdName); err != nil { log.Fatal(err) } @@ -114,13 +107,13 @@ EXAMPLE: log.Fatal(err) } } else { - if !(c.Args().Len() >= 3) { - internal.ShowSubcommandHelpAndError(c, errors.New("missing arguments")) + if !(cmd.Args().Len() >= 3) { + internal.ShowSubcommandHelpAndError(cmd, errors.New("missing arguments")) } - targetServiceName := c.Args().Get(1) + targetServiceName := cmd.Args().Get(1) - cmdName := c.Args().Get(2) + cmdName := cmd.Args().Get(2) if err := internal.EnsureCommand(app.Recipe.AbraShPath, app.Recipe.Name, cmdName); err != nil { log.Fatal(err) } @@ -200,16 +193,16 @@ var appCmdListCommand = cli.Command{ Name: "list", Aliases: []string{"ls"}, Usage: "List all available commands", - ArgsUsage: "", + UsageText: "abra app cmd ls [options]", Flags: []cli.Flag{ - internal.DebugFlag, - internal.OfflineFlag, internal.ChaosFlag, }, - BashComplete: autocomplete.AppNameComplete, - Before: internal.SubCommandBefore, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + ShellComplete: autocomplete.AppNameComplete, + Before: internal.SubCommandBefore, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) + r := recipe.Get(app.Recipe.Name) if err := app.Recipe.EnsureExists(); err != nil { log.Fatal(err) diff --git a/cli/app/config.go b/cli/app/config.go index 5b583deb..bb7ace0d 100644 --- a/cli/app/config.go +++ b/cli/app/config.go @@ -1,6 +1,7 @@ package app import ( + "context" "errors" "os" "os/exec" @@ -10,24 +11,22 @@ import ( "coopcloud.tech/abra/pkg/autocomplete" "coopcloud.tech/abra/pkg/log" "github.com/AlecAivazis/survey/v2" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var appConfigCommand = cli.Command{ - Name: "config", - Aliases: []string{"cfg"}, - Usage: "Edit app config", - ArgsUsage: "", - Flags: []cli.Flag{ - internal.DebugFlag, - }, - Before: internal.SubCommandBefore, - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { - appName := c.Args().First() + Name: "config", + Aliases: []string{"cfg"}, + Usage: "Edit app config", + UsageText: "abra app config [options]", + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.AppNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + appName := cmd.Args().First() if appName == "" { - internal.ShowSubcommandHelpAndError(c, errors.New("no app provided")) + internal.ShowSubcommandHelpAndError(cmd, errors.New("no app provided")) } files, err := appPkg.LoadAppFiles("") @@ -51,11 +50,11 @@ var appConfigCommand = cli.Command{ } } - cmd := exec.Command(ed, appFile.Path) - cmd.Stdin = os.Stdin - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - if err := cmd.Run(); err != nil { + c := exec.Command(ed, appFile.Path) + c.Stdin = os.Stdin + c.Stdout = os.Stdout + c.Stderr = os.Stderr + if err := c.Run(); err != nil { log.Fatal(err) } diff --git a/cli/app/cp.go b/cli/app/cp.go index 26124b3d..e7d965a7 100644 --- a/cli/app/cp.go +++ b/cli/app/cp.go @@ -22,21 +22,16 @@ import ( dockerClient "github.com/docker/docker/client" "github.com/docker/docker/errdefs" "github.com/docker/docker/pkg/archive" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var appCpCommand = cli.Command{ Name: "cp", Aliases: []string{"c"}, - ArgsUsage: " ", - Flags: []cli.Flag{ - internal.DebugFlag, - internal.NoInputFlag, - }, - Before: internal.SubCommandBefore, - Usage: "Copy files to/from a deployed app service", - Description: ` -Copy files to and from any app service file system. + Before: internal.SubCommandBefore, + Usage: "Copy files to/from a deployed app service", + UsageText: "abra app cp [options]", + Description: `Copy files to and from any app service file system. If you want to copy a myfile.txt to the root of the app service: @@ -44,18 +39,17 @@ If you want to copy a myfile.txt to the root of the app service: And if you want to copy that file back to your current working directory locally: - abra app cp app:/myfile.txt . -`, - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) - + abra app cp app:/myfile.txt`, + ShellComplete: autocomplete.AppNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) if err := app.Recipe.Ensure(internal.Chaos, internal.Offline); err != nil { log.Fatal(err) } - src := c.Args().Get(1) - dst := c.Args().Get(2) + src := cmd.Args().Get(1) + dst := cmd.Args().Get(2) if src == "" { log.Fatal("missing argument") } diff --git a/cli/app/deploy.go b/cli/app/deploy.go index cb2aca5a..9bf3828e 100644 --- a/cli/app/deploy.go +++ b/cli/app/deploy.go @@ -17,22 +17,19 @@ import ( "coopcloud.tech/abra/pkg/lint" "coopcloud.tech/abra/pkg/log" "coopcloud.tech/abra/pkg/upstream/stack" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var appDeployCommand = cli.Command{ Name: "deploy", Aliases: []string{"d"}, Usage: "Deploy an app", - ArgsUsage: " []", + UsageText: "abra app deploy [] [options]", Flags: []cli.Flag{ - internal.DebugFlag, - internal.NoInputFlag, internal.ForceFlag, internal.ChaosFlag, internal.NoDomainChecksFlag, internal.DontWaitConvergeFlag, - internal.OfflineFlag, }, Before: internal.SubCommandBefore, Description: `Deploy an app. @@ -40,21 +37,20 @@ var appDeployCommand = cli.Command{ This command supports chaos operations. Use "--chaos" to deploy your recipe checkout as-is. Recipe commit hashes are also supported values for "[]". Please note, "upgrade"/"rollback" do not support chaos -operations. - -EXAMPLE: - - abra app deploy foo.example.com - abra app deploy foo.example.com 1.2.3+3.2.1 - abra app deploy foo.example.com 1e83340e`, - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { +operations.`, + ShellComplete: autocomplete.AppNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { var warnMessages []string - app := internal.ValidateApp(c) + app := internal.ValidateApp(cmd) stackName := app.StackName() - specificVersion := c.Args().Get(1) + specificVersion := cmd.Args().Get(1) + if specificVersion == "" { + specificVersion = app.Recipe.Version + } + if specificVersion != "" && internal.Chaos { log.Fatal("cannot use and --chaos together") } diff --git a/cli/app/list.go b/cli/app/list.go index 9fdb23b0..25eeb2e9 100644 --- a/cli/app/list.go +++ b/cli/app/list.go @@ -1,6 +1,7 @@ package app import ( + "context" "encoding/json" "fmt" "sort" @@ -12,7 +13,7 @@ import ( "coopcloud.tech/abra/pkg/formatter" "coopcloud.tech/abra/pkg/log" "coopcloud.tech/tagcmp" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var ( @@ -70,26 +71,24 @@ type serverStatus struct { } var appListCommand = cli.Command{ - Name: "list", - Aliases: []string{"ls"}, - Usage: "List all managed apps", - Description: ` -Read the local file system listing of apps and servers (e.g. ~/.abra/) to -generate a report of all your apps. + Name: "list", + Aliases: []string{"ls"}, + Usage: "List all managed apps", + UsageText: "abra app list [options]", + Description: `Generate a report of all managed apps. By passing the "--status/-S" flag, you can query all your servers for the actual live deployment status. Depending on how many servers you manage, this can take some time.`, Flags: []cli.Flag{ - internal.DebugFlag, internal.MachineReadableFlag, statusFlag, listAppServerFlag, recipeFlag, - internal.OfflineFlag, }, - Before: internal.SubCommandBefore, - Action: func(c *cli.Context) error { + Before: internal.SubCommandBefore, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { appFiles, err := appPkg.LoadAppFiles(listAppServer) if err != nil { log.Fatal(err) diff --git a/cli/app/logs.go b/cli/app/logs.go index ff8bc2ac..46980dea 100644 --- a/cli/app/logs.go +++ b/cli/app/logs.go @@ -19,23 +19,23 @@ import ( "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/swarm" dockerClient "github.com/docker/docker/client" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var appLogsCommand = cli.Command{ Name: "logs", Aliases: []string{"l"}, - ArgsUsage: " []", Usage: "Tail app logs", + UsageText: "abra app logs [] [options]", Flags: []cli.Flag{ internal.StdErrOnlyFlag, internal.SinceLogsFlag, - internal.DebugFlag, }, - Before: internal.SubCommandBefore, - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.AppNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) stackName := app.StackName() if err := app.Recipe.EnsureExists(); err != nil { @@ -56,7 +56,7 @@ var appLogsCommand = cli.Command{ log.Fatalf("%s is not deployed?", app.Name) } - serviceName := c.Args().Get(1) + serviceName := cmd.Args().Get(1) serviceNames := []string{} if serviceName != "" { serviceNames = []string{serviceName} diff --git a/cli/app/new.go b/cli/app/new.go index 88b7f654..3a2f7e95 100644 --- a/cli/app/new.go +++ b/cli/app/new.go @@ -1,6 +1,7 @@ package app import ( + "context" "fmt" "coopcloud.tech/abra/cli/internal" @@ -16,12 +17,13 @@ import ( "github.com/AlecAivazis/survey/v2" "github.com/charmbracelet/lipgloss/table" dockerClient "github.com/docker/docker/client" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) -var appNewDescription = ` -Creates a new app from a default recipe. This new app configuration is stored -in your $ABRA_DIR directory under the appropriate server. +var appNewDescription = `Creates a new app from a default recipe. + +This new app configuration is stored in your $ABRA_DIR directory under the +appropriate server. This command does not deploy your app for you. You will need to run "abra app deploy " to do so. @@ -44,30 +46,28 @@ var appNewCommand = cli.Command{ Name: "new", Aliases: []string{"n"}, Usage: "Create a new app", + UsageText: "abra app new [] [] [options]", Description: appNewDescription, Flags: []cli.Flag{ - internal.DebugFlag, - internal.NoInputFlag, internal.NewAppServerFlag, internal.DomainFlag, internal.PassFlag, internal.SecretsFlag, - internal.OfflineFlag, internal.ChaosFlag, }, - Before: internal.SubCommandBefore, - ArgsUsage: "[] []", - BashComplete: func(ctx *cli.Context) { - args := ctx.Args() + Before: internal.SubCommandBefore, + HideHelp: true, + ShellComplete: func(ctx context.Context, cmd *cli.Command) { + args := cmd.Args() switch args.Len() { case 0: - autocomplete.RecipeNameComplete(ctx) + autocomplete.RecipeNameComplete(ctx, cmd) case 1: - autocomplete.RecipeVersionComplete(ctx.Args().Get(0)) + autocomplete.RecipeVersionComplete(cmd.Args().Get(0)) } }, - Action: func(c *cli.Context) error { - recipe := internal.ValidateRecipe(c) + Action: func(ctx context.Context, cmd *cli.Command) error { + recipe := internal.ValidateRecipe(cmd) var version string if !internal.Chaos { @@ -80,7 +80,7 @@ var appNewCommand = cli.Command{ } } - if c.Args().Get(1) == "" { + if cmd.Args().Get(1) == "" { recipeVersions, err := recipe.GetRecipeVersions() if err != nil { log.Fatal(err) @@ -101,7 +101,7 @@ var appNewCommand = cli.Command{ } } } else { - version = c.Args().Get(1) + version = cmd.Args().Get(1) if _, err := recipe.EnsureVersion(version); err != nil { log.Fatal(err) } diff --git a/cli/app/ps.go b/cli/app/ps.go index d1372d68..fddb2faa 100644 --- a/cli/app/ps.go +++ b/cli/app/ps.go @@ -18,25 +18,25 @@ import ( containerTypes "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" dockerClient "github.com/docker/docker/client" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var appPsCommand = cli.Command{ Name: "ps", Aliases: []string{"p"}, Usage: "Check app status", - ArgsUsage: "", + UsageText: "abra app ps [options]", Description: "Show status of a deployed app.", Flags: []cli.Flag{ internal.MachineReadableFlag, - internal.DebugFlag, internal.ChaosFlag, internal.OfflineFlag, }, - Before: internal.SubCommandBefore, - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.AppNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) if err := app.Recipe.Ensure(internal.Chaos, internal.Offline); err != nil { log.Fatal(err) } diff --git a/cli/app/remove.go b/cli/app/remove.go index 7e2e6dc1..4cc7ddd3 100644 --- a/cli/app/remove.go +++ b/cli/app/remove.go @@ -12,16 +12,15 @@ import ( stack "coopcloud.tech/abra/pkg/upstream/stack" "github.com/AlecAivazis/survey/v2" "github.com/docker/docker/api/types" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var appRemoveCommand = cli.Command{ Name: "remove", Aliases: []string{"rm"}, - ArgsUsage: "", + UsageText: "abra app remove [options]", Usage: "Remove all app data, locally and remotely", - Description: ` -This command removes everything related to an app which is already undeployed. + Description: `Remove everything related to an app which is already undeployed. By default, it will prompt for confirmation before proceeding. All secrets, volumes and the local app env file will be deleted. @@ -39,14 +38,12 @@ To delete everything without prompt, use the "--force/-f" or the "--no-input/n" flag.`, Flags: []cli.Flag{ internal.ForceFlag, - internal.DebugFlag, - internal.NoInputFlag, - internal.OfflineFlag, }, - BashComplete: autocomplete.AppNameComplete, - Before: internal.SubCommandBefore, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + ShellComplete: autocomplete.AppNameComplete, + Before: internal.SubCommandBefore, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) if !internal.Force && !internal.NoInput { log.Warnf("ALERTA ALERTA: this will completely remove %s data and config locally and remotely", app.Name) diff --git a/cli/app/restart.go b/cli/app/restart.go index 3de623c9..b684d19f 100644 --- a/cli/app/restart.go +++ b/cli/app/restart.go @@ -12,41 +12,35 @@ import ( "coopcloud.tech/abra/pkg/log" upstream "coopcloud.tech/abra/pkg/upstream/service" stack "coopcloud.tech/abra/pkg/upstream/stack" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var appRestartCommand = cli.Command{ Name: "restart", Aliases: []string{"re"}, Usage: "Restart an app", - ArgsUsage: " []", + UsageText: "abra app restart [] [options]", Flags: []cli.Flag{ - internal.DebugFlag, - internal.OfflineFlag, internal.AllServicesFlag, }, Before: internal.SubCommandBefore, - Description: ` -This command restarts services within a deployed app. + Description: `This command restarts services within a deployed app. Run "abra app ps " to see a list of service names. -Pass "--all-services/-a" to restart all services. - -EXAMPLE: - - abra app restart example.com app`, - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) +Pass "--all-services/-a" to restart all services.`, + ShellComplete: autocomplete.AppNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) if err := app.Recipe.Ensure(false, false); err != nil { log.Fatal(err) } - serviceName := c.Args().Get(1) + serviceName := cmd.Args().Get(1) if serviceName == "" && !internal.AllServices { err := errors.New("missing ") - internal.ShowSubcommandHelpAndError(c, err) + internal.ShowSubcommandHelpAndError(cmd, err) } if serviceName != "" && internal.AllServices { diff --git a/cli/app/restore.go b/cli/app/restore.go index c73a347b..2d123a31 100644 --- a/cli/app/restore.go +++ b/cli/app/restore.go @@ -1,13 +1,14 @@ package app import ( + "context" "fmt" "coopcloud.tech/abra/cli/internal" "coopcloud.tech/abra/pkg/autocomplete" "coopcloud.tech/abra/pkg/client" "coopcloud.tech/abra/pkg/log" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var targetPath string @@ -22,16 +23,15 @@ var appRestoreCommand = cli.Command{ Name: "restore", Aliases: []string{"rs"}, Usage: "Restore an app backup", - ArgsUsage: " ", + UsageText: "abra app restore [options]", Flags: []cli.Flag{ - internal.DebugFlag, - internal.OfflineFlag, targetPathFlag, }, - Before: internal.SubCommandBefore, - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.AppNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) if err := app.Recipe.Ensure(internal.Chaos, internal.Offline); err != nil { log.Fatal(err) } diff --git a/cli/app/rollback.go b/cli/app/rollback.go index 3d735a19..3cb22431 100644 --- a/cli/app/rollback.go +++ b/cli/app/rollback.go @@ -16,44 +16,36 @@ import ( "coopcloud.tech/abra/pkg/client" "coopcloud.tech/abra/pkg/log" "github.com/AlecAivazis/survey/v2" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var appRollbackCommand = cli.Command{ Name: "rollback", Aliases: []string{"rl"}, Usage: "Roll an app back to a previous version", - ArgsUsage: " []", + UsageText: "abra app rollback [] [options]", Flags: []cli.Flag{ - internal.DebugFlag, - internal.NoInputFlag, internal.ForceFlag, internal.NoDomainChecksFlag, internal.DontWaitConvergeFlag, - internal.OfflineFlag, }, Before: internal.SubCommandBefore, - Description: ` -This command rolls an app back to a previous version. + Description: `This command rolls an app back to a previous version. Unlike "deploy", chaos operations are not supported here. Only recipe versions are supported values for "[]". A rollback can be destructive, please ensure you have a copy of your app data -beforehand. - -EXAMPLE: - - abra app rollback foo.example.com - abra app rollback foo.example.com 1.2.3+3.2.1`, - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { +beforehand.`, + ShellComplete: autocomplete.AppNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { var warnMessages []string - app := internal.ValidateApp(c) + app := internal.ValidateApp(cmd) stackName := app.StackName() - specificVersion := c.Args().Get(1) + specificVersion := cmd.Args().Get(1) if specificVersion != "" { log.Debugf("overriding env file version (%s) with %s", app.Recipe.Version, specificVersion) app.Recipe.Version = specificVersion diff --git a/cli/app/run.go b/cli/app/run.go index b7192157..e13031af 100644 --- a/cli/app/run.go +++ b/cli/app/run.go @@ -14,7 +14,7 @@ import ( "github.com/docker/cli/cli/command" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var user string @@ -36,23 +36,23 @@ var appRunCommand = cli.Command{ Name: "run", Aliases: []string{"r"}, Flags: []cli.Flag{ - internal.DebugFlag, noTTYFlag, userFlag, }, - Before: internal.SubCommandBefore, - ArgsUsage: " ...", - Usage: "Run a command in a service container", - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + Before: internal.SubCommandBefore, + Usage: "Run a command in an app service", + UsageText: "abra app run [options]", + ShellComplete: autocomplete.AppNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) - if c.Args().Len() < 2 { - internal.ShowSubcommandHelpAndError(c, errors.New("no provided?")) + if cmd.Args().Len() < 2 { + internal.ShowSubcommandHelpAndError(cmd, errors.New("no provided?")) } - if c.Args().Len() < 3 { - internal.ShowSubcommandHelpAndError(c, errors.New("no provided?")) + if cmd.Args().Len() < 3 { + internal.ShowSubcommandHelpAndError(cmd, errors.New("no provided?")) } cl, err := client.New(app.Server) @@ -60,7 +60,7 @@ var appRunCommand = cli.Command{ log.Fatal(err) } - serviceName := c.Args().Get(1) + serviceName := cmd.Args().Get(1) stackAndServiceName := fmt.Sprintf("^%s_%s", app.StackName(), serviceName) filters := filters.NewArgs() filters.Add("name", stackAndServiceName) @@ -70,12 +70,12 @@ var appRunCommand = cli.Command{ log.Fatal(err) } - cmd := c.Args().Slice()[2:] + c := cmd.Args().Slice()[2:] execCreateOpts := types.ExecConfig{ AttachStderr: true, AttachStdin: true, AttachStdout: true, - Cmd: cmd, + Cmd: c, Detach: false, Tty: true, } diff --git a/cli/app/secret.go b/cli/app/secret.go index 67c90faf..7a11fad9 100644 --- a/cli/app/secret.go +++ b/cli/app/secret.go @@ -17,7 +17,7 @@ import ( "coopcloud.tech/abra/pkg/secret" "github.com/docker/docker/api/types" dockerClient "github.com/docker/docker/client" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var ( @@ -44,31 +44,30 @@ var appSecretGenerateCommand = cli.Command{ Name: "generate", Aliases: []string{"g"}, Usage: "Generate secrets", - ArgsUsage: " ", + UsageText: "abra app secret generate [options]", Flags: []cli.Flag{ - internal.DebugFlag, allSecretsFlag, internal.PassFlag, internal.MachineReadableFlag, - internal.OfflineFlag, internal.ChaosFlag, }, - Before: internal.SubCommandBefore, - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.AppNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) if err := app.Recipe.Ensure(internal.Chaos, internal.Offline); err != nil { log.Fatal(err) } - if c.Args().Len() == 1 && !allSecrets { + if cmd.Args().Len() == 1 && !allSecrets { err := errors.New("missing arguments / or '--all'") - internal.ShowSubcommandHelpAndError(c, err) + internal.ShowSubcommandHelpAndError(cmd, err) } - if c.Args().Get(1) != "" && allSecrets { + if cmd.Args().Get(1) != "" && allSecrets { err := errors.New("cannot use ' ' and '--all' together") - internal.ShowSubcommandHelpAndError(c, err) + internal.ShowSubcommandHelpAndError(cmd, err) } composeFiles, err := app.Recipe.GetComposeFiles(app.Env) @@ -82,8 +81,8 @@ var appSecretGenerateCommand = cli.Command{ } if !allSecrets { - secretName := c.Args().Get(1) - secretVersion := c.Args().Get(2) + secretName := cmd.Args().Get(1) + secretVersion := cmd.Args().Get(2) s, ok := secrets[secretName] if !ok { log.Fatalf("%s doesn't exist in the env config?", secretName) @@ -154,39 +153,32 @@ var appSecretGenerateCommand = cli.Command{ } var appSecretInsertCommand = cli.Command{ - Name: "insert", - Aliases: []string{"i"}, - Usage: "Insert secret", + Name: "insert", + Aliases: []string{"i"}, + Usage: "Insert secret", + UsageText: "abra app secret insert [options]", Flags: []cli.Flag{ - internal.DebugFlag, internal.PassFlag, internal.FileFlag, internal.TrimFlag, internal.ChaosFlag, }, - Before: internal.SubCommandBefore, - ArgsUsage: " ", - BashComplete: autocomplete.AppNameComplete, - Description: ` -This command inserts a secret into an app environment. + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.AppNameComplete, + HideHelpCommand: true, + Description: `This command inserts a secret into an app environment. This can be useful when you want to manually generate secrets for an app environment. Typically, you can let Abra generate them for you on app creation -(see "abra app new --secrets" for more). - -Example: - - abra app secret insert myapp db_pass v1 mySecretPassword - -`, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) +(see "abra app new --secrets" for more).`, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) if err := app.Recipe.Ensure(internal.Chaos, internal.Offline); err != nil { log.Fatal(err) } - if c.Args().Len() != 4 { - internal.ShowSubcommandHelpAndError(c, errors.New("missing arguments?")) + if cmd.Args().Len() != 4 { + internal.ShowSubcommandHelpAndError(cmd, errors.New("missing arguments?")) } cl, err := client.New(app.Server) @@ -194,9 +186,9 @@ Example: log.Fatal(err) } - name := c.Args().Get(1) - version := c.Args().Get(2) - data := c.Args().Get(3) + name := cmd.Args().Get(1) + version := cmd.Args().Get(2) + data := cmd.Args().Get(3) if internal.File { raw, err := os.ReadFile(data) @@ -247,29 +239,28 @@ func secretRm(cl *dockerClient.Client, app appPkg.App, secretName, parsed string } var appSecretRmCommand = cli.Command{ - Name: "remove", - Aliases: []string{"rm"}, - Usage: "Remove a secret", + Name: "remove", + Aliases: []string{"rm"}, + Usage: "Remove a secret", + UsageText: "abra app remove [options]", Flags: []cli.Flag{ - internal.DebugFlag, internal.NoInputFlag, rmAllSecretsFlag, internal.PassRemoveFlag, internal.OfflineFlag, internal.ChaosFlag, }, - Before: internal.SubCommandBefore, - ArgsUsage: " []", - BashComplete: autocomplete.AppNameComplete, + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.AppNameComplete, Description: ` This command removes app secrets. Example: - abra app secret remove myapp db_pass -`, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + abra app secret remove myapp db_pass`, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) if err := app.Recipe.Ensure(internal.Chaos, internal.Offline); err != nil { log.Fatal(err) } @@ -284,12 +275,12 @@ Example: log.Fatal(err) } - if c.Args().Get(1) != "" && rmAllSecrets { - internal.ShowSubcommandHelpAndError(c, errors.New("cannot use '' and '--all' together")) + if cmd.Args().Get(1) != "" && rmAllSecrets { + internal.ShowSubcommandHelpAndError(cmd, errors.New("cannot use '' and '--all' together")) } - if c.Args().Get(1) == "" && !rmAllSecrets { - internal.ShowSubcommandHelpAndError(c, errors.New("no secret(s) specified?")) + if cmd.Args().Get(1) == "" && !rmAllSecrets { + internal.ShowSubcommandHelpAndError(cmd, errors.New("no secret(s) specified?")) } cl, err := client.New(app.Server) @@ -313,7 +304,7 @@ Example: } match := false - secretToRm := c.Args().Get(1) + secretToRm := cmd.Args().Get(1) for secretName, val := range secrets { secretRemoteName := fmt.Sprintf("%s_%s_%s", app.StackName(), secretName, val.Version) if _, ok := remoteSecretNames[secretRemoteName]; ok { @@ -351,16 +342,17 @@ var appSecretLsCommand = cli.Command{ Name: "list", Aliases: []string{"ls"}, Flags: []cli.Flag{ - internal.DebugFlag, internal.OfflineFlag, internal.ChaosFlag, internal.MachineReadableFlag, }, - Before: internal.SubCommandBefore, - Usage: "List all secrets", - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + Before: internal.SubCommandBefore, + Usage: "List all secrets", + UsageText: "abra app secret list [options]", + HideHelp: true, + ShellComplete: autocomplete.AppNameComplete, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) if err := app.Recipe.Ensure(internal.Chaos, internal.Offline); err != nil { log.Fatal(err) } @@ -420,8 +412,8 @@ var appSecretCommand = cli.Command{ Name: "secret", Aliases: []string{"s"}, Usage: "Manage app secrets", - ArgsUsage: "", - Subcommands: []*cli.Command{ + UsageText: "abra app secret [command] [arguments] [options]", + Commands: []*cli.Command{ &appSecretGenerateCommand, &appSecretInsertCommand, &appSecretRmCommand, diff --git a/cli/app/services.go b/cli/app/services.go index bf7f0caf..6290c621 100644 --- a/cli/app/services.go +++ b/cli/app/services.go @@ -13,21 +13,19 @@ import ( "coopcloud.tech/abra/pkg/service" stack "coopcloud.tech/abra/pkg/upstream/stack" containerTypes "github.com/docker/docker/api/types/container" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var appServicesCommand = cli.Command{ - Name: "services", - Aliases: []string{"sr"}, - Usage: "Display all services of an app", - ArgsUsage: "", - Flags: []cli.Flag{ - internal.DebugFlag, - }, - Before: internal.SubCommandBefore, - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + Name: "services", + Aliases: []string{"sr"}, + Usage: "Display all services of an app", + UsageText: "abra app services [options]", + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.AppNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) if err := app.Recipe.Ensure(internal.Chaos, internal.Offline); err != nil { log.Fatal(err) } diff --git a/cli/app/undeploy.go b/cli/app/undeploy.go index f9d318bc..663865c7 100644 --- a/cli/app/undeploy.go +++ b/cli/app/undeploy.go @@ -14,7 +14,7 @@ import ( stack "coopcloud.tech/abra/pkg/upstream/stack" "github.com/docker/docker/api/types/filters" dockerClient "github.com/docker/docker/client" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var prune bool @@ -65,25 +65,24 @@ func pruneApp(cl *dockerClient.Client, app appPkg.App) error { var appUndeployCommand = cli.Command{ Name: "undeploy", Aliases: []string{"un"}, - ArgsUsage: "", + UsageText: "abra app undeploy [options]", Flags: []cli.Flag{ - internal.DebugFlag, internal.NoInputFlag, internal.OfflineFlag, pruneFlag, }, - Before: internal.SubCommandBefore, - Usage: "Undeploy an app", - BashComplete: autocomplete.AppNameComplete, - Description: ` -This does not destroy any of the application data. + Before: internal.SubCommandBefore, + Usage: "Undeploy an app", + ShellComplete: autocomplete.AppNameComplete, + HideHelp: true, + Description: `This does not destroy any of the application data. However, you should remain vigilant, as your swarm installation will consider any previously attached volumes as eligible for pruning once undeployed. Passing "-p/--prune" does not remove those volumes.`, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) stackName := app.StackName() cl, err := client.New(app.Server) diff --git a/cli/app/upgrade.go b/cli/app/upgrade.go index acf26432..41effa69 100644 --- a/cli/app/upgrade.go +++ b/cli/app/upgrade.go @@ -15,45 +15,37 @@ import ( stack "coopcloud.tech/abra/pkg/upstream/stack" "coopcloud.tech/tagcmp" "github.com/AlecAivazis/survey/v2" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var appUpgradeCommand = cli.Command{ Name: "upgrade", Aliases: []string{"up"}, Usage: "Upgrade an app", - ArgsUsage: " []", + UsageText: "abra app upgrade [] [options]", Flags: []cli.Flag{ - internal.DebugFlag, - internal.NoInputFlag, internal.ForceFlag, internal.NoDomainChecksFlag, internal.DontWaitConvergeFlag, - internal.OfflineFlag, internal.ReleaseNotesFlag, }, Before: internal.SubCommandBefore, - Description: ` -Upgrade an app. + Description: `Upgrade an app. Unlike "deploy", chaos operations are not supported here. Only recipe versions are supported values for "[]". An upgrade can be destructive, please ensure you have a copy of your app data -beforehand. - -EXAMPLE: - - abra app upgrade foo.example.com - abra app upgrade foo.example.com 1.2.3+3.2.1`, - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { +beforehand.`, + HideHelp: true, + ShellComplete: autocomplete.AppNameComplete, + Action: func(ctx context.Context, cmd *cli.Command) error { var warnMessages []string - app := internal.ValidateApp(c) + app := internal.ValidateApp(cmd) stackName := app.StackName() - specificVersion := c.Args().Get(1) + specificVersion := cmd.Args().Get(1) if specificVersion != "" { log.Debugf("overriding env file version (%s) with %s", app.Recipe.Version, specificVersion) app.Recipe.Version = specificVersion diff --git a/cli/app/volume.go b/cli/app/volume.go index 290ac141..da9bd404 100644 --- a/cli/app/volume.go +++ b/cli/app/volume.go @@ -11,22 +11,19 @@ import ( "coopcloud.tech/abra/pkg/log" "coopcloud.tech/abra/pkg/upstream/stack" "github.com/AlecAivazis/survey/v2" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var appVolumeListCommand = cli.Command{ - Name: "list", - Aliases: []string{"ls"}, - ArgsUsage: "", - Flags: []cli.Flag{ - internal.DebugFlag, - internal.NoInputFlag, - }, - Before: internal.SubCommandBefore, - Usage: "List volumes associated with an app", - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + Name: "list", + Aliases: []string{"ls"}, + UsageText: "abra app volume list [options]", + Before: internal.SubCommandBefore, + Usage: "List volumes associated with an app", + ShellComplete: autocomplete.AppNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) cl, err := client.New(app.Server) if err != nil { @@ -74,27 +71,26 @@ var appVolumeListCommand = cli.Command{ var appVolumeRemoveCommand = cli.Command{ Name: "remove", Usage: "Remove volume(s) associated with an app", - Description: ` -This command supports removing volumes associated with an app. The app in -question must be undeployed before you try to remove volumes. See "abra app -undeploy " for more. + Description: `Remove volumes associated with an app. + +The app in question must be undeployed before you try to remove volumes. See +"abra app undeploy " for more. The command is interactive and will show a multiple select input which allows you to make a seclection. Use the "?" key to see more help on navigating this interface. Passing "--force/-f" will select all volumes for removal. Be careful.`, - ArgsUsage: "", + UsageText: "abra app volume remove [options] ", Aliases: []string{"rm"}, Flags: []cli.Flag{ - internal.DebugFlag, internal.NoInputFlag, internal.ForceFlag, }, - Before: internal.SubCommandBefore, - BashComplete: autocomplete.AppNameComplete, - Action: func(c *cli.Context) error { - app := internal.ValidateApp(c) + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.AppNameComplete, + Action: func(ctx context.Context, cmd *cli.Command) error { + app := internal.ValidateApp(cmd) cl, err := client.New(app.Server) if err != nil { @@ -158,8 +154,8 @@ var appVolumeCommand = cli.Command{ Name: "volume", Aliases: []string{"vl"}, Usage: "Manage app volumes", - ArgsUsage: "", - Subcommands: []*cli.Command{ + UsageText: "abra app volume [command] [options] [arguments]", + Commands: []*cli.Command{ &appVolumeListCommand, &appVolumeRemoveCommand, }, diff --git a/cli/catalogue/catalogue.go b/cli/catalogue/catalogue.go index d3ef81ce..bf37489e 100644 --- a/cli/catalogue/catalogue.go +++ b/cli/catalogue/catalogue.go @@ -1,6 +1,7 @@ package catalogue import ( + "context" "encoding/json" "fmt" "io/ioutil" @@ -15,25 +16,22 @@ import ( "coopcloud.tech/abra/pkg/log" "coopcloud.tech/abra/pkg/recipe" "github.com/go-git/go-git/v5" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var catalogueGenerateCommand = cli.Command{ - Name: "generate", - Aliases: []string{"g"}, - Usage: "Generate the recipe catalogue", + Name: "generate", + Aliases: []string{"g"}, + Usage: "Generate the recipe catalogue", + UsageText: "abra catalogue generate [] [options]", Flags: []cli.Flag{ - internal.DebugFlag, - internal.NoInputFlag, internal.PublishFlag, internal.DryFlag, internal.SkipUpdatesFlag, internal.ChaosFlag, - internal.OfflineFlag, }, Before: internal.SubCommandBefore, - Description: ` -Generate a new copy of the recipe catalogue. + Description: `Generate a new copy of the recipe catalogue. It is possible to generate new metadata for a single recipe by passing . The existing local catalogue will be updated, not overwritten. @@ -45,14 +43,14 @@ If you have a Hub account you can have Abra log you in to avoid this. Pass Push your new release to git.coopcloud.tech with "-p/--publish". This requires that you have permission to git push to these repositories and have your SSH keys configured on your account.`, - ArgsUsage: "[]", - BashComplete: autocomplete.RecipeNameComplete, - Action: func(c *cli.Context) error { - recipeName := c.Args().First() + ShellComplete: autocomplete.RecipeNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + recipeName := cmd.Args().First() r := recipe.Get(recipeName) if recipeName != "" { - internal.ValidateRecipe(c) + internal.ValidateRecipe(cmd) } if !internal.Chaos { @@ -208,8 +206,8 @@ var CatalogueCommand = cli.Command{ Name: "catalogue", Usage: "Manage the recipe catalogue", Aliases: []string{"c"}, - ArgsUsage: "", - Subcommands: []*cli.Command{ + UsageText: "abra catalogue [command] [options] [arguments]", + Commands: []*cli.Command{ &catalogueGenerateCommand, }, } diff --git a/cli/cli.go b/cli/cli.go index af057490..dfb21c1c 100644 --- a/cli/cli.go +++ b/cli/cli.go @@ -2,6 +2,7 @@ package cli import ( + "context" "errors" "fmt" "os" @@ -18,31 +19,24 @@ import ( "coopcloud.tech/abra/pkg/log" "coopcloud.tech/abra/pkg/web" charmLog "github.com/charmbracelet/log" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) // AutoCompleteCommand helps people set up auto-complete in their shells var AutoCompleteCommand = cli.Command{ - Name: "autocomplete", - Aliases: []string{"ac"}, - Usage: "Configure shell autocompletion", - Description: ` -Set up shell auto-completion. + Name: "autocomplete", + Aliases: []string{"ac"}, + Usage: "Configure shell autocompletion", + UsageText: "abra autocomplete [options]", + Description: `Set up shell auto-completion. -Supported shells are: bash, fish, fizsh & zsh. - -EXAMPLE: - - abra autocomplete bash`, - ArgsUsage: "", - Flags: []cli.Flag{ - internal.DebugFlag, - }, - Action: func(c *cli.Context) error { - shellType := c.Args().First() +Supported shells are: bash, fish, fizsh & zsh.`, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + shellType := cmd.Args().First() if shellType == "" { - internal.ShowSubcommandHelpAndError(c, errors.New("no shell provided")) + internal.ShowSubcommandHelpAndError(cmd, errors.New("no shell provided")) } supportedShells := map[string]bool{ @@ -113,33 +107,29 @@ source /etc/fish/completions/abra // UpgradeCommand upgrades abra in-place. var UpgradeCommand = cli.Command{ - Name: "upgrade", - Aliases: []string{"u"}, - Usage: "Upgrade abra", - Description: ` -Upgrade abra in-place with the latest stable or release candidate. + Name: "upgrade", + Aliases: []string{"u"}, + Usage: "Upgrade abra", + UsageText: "abra upgrade [options]", + Description: `Upgrade abra in-place with the latest stable or release candidate. -Use "-r/--rc" to install the latest release candidate. Please bear in mind that +Use "--rc/-r" to install the latest release candidate. Please bear in mind that it may contain absolutely catastrophic deal-breaker bugs. Thank you very much -for the testing efforts 💗 - -EXAMPLE: - - abra upgrade - abra upgrade --rc`, - Flags: []cli.Flag{internal.RCFlag}, - Action: func(c *cli.Context) error { +for the testing efforts 💗`, + Flags: []cli.Flag{internal.RCFlag}, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { mainURL := "https://install.abra.coopcloud.tech" - cmd := exec.Command("bash", "-c", fmt.Sprintf("wget -q -O- %s | bash", mainURL)) + c := exec.Command("bash", "-c", fmt.Sprintf("wget -q -O- %s | bash", mainURL)) if internal.RC { releaseCandidateURL := "https://git.coopcloud.tech/coop-cloud/abra/raw/branch/main/scripts/installer/installer" - cmd = exec.Command("bash", "-c", fmt.Sprintf("wget -q -O- %s | bash -s -- --rc", releaseCandidateURL)) + c = exec.Command("bash", "-c", fmt.Sprintf("wget -q -O- %s | bash -s -- --rc", releaseCandidateURL)) } - log.Debugf("attempting to run %s", cmd) + log.Debugf("attempting to run %s", c) - if err := internal.RunCmd(cmd); err != nil { + if err := internal.RunCmd(c); err != nil { log.Fatal(err) } @@ -147,18 +137,16 @@ EXAMPLE: }, } -func newAbraApp(version, commit string) *cli.App { - app := &cli.App{ - Name: "abra", - Usage: `the Co-op Cloud command-line utility belt 🎩🐇 - ____ ____ _ _ - / ___|___ ___ _ __ / ___| | ___ _ _ __| | - | | / _ \ _____ / _ \| '_ \ | | | |/ _ \| | | |/ _' | - | |__| (_) |_____| (_) | |_) | | |___| | (_) | |_| | (_| | - \____\___/ \___/| .__/ \____|_|\___/ \__,_|\__,_| - |_| -`, - Version: fmt.Sprintf("%s-%s", version, commit[:7]), +func newAbraApp(version, commit string) *cli.Command { + app := &cli.Command{ + Name: "abra", + Usage: "The Co-op Cloud command-line utility belt 🎩🐇", + UsageText: "abra [command] [arguments] [options]", + Version: fmt.Sprintf("%s-%s", version, commit[:7]), + Flags: []cli.Flag{ + // NOTE(d1): "GLOBAL OPTIONS" flags + internal.DebugFlag, + }, Commands: []*cli.Command{ &app.AppCommand, &server.ServerCommand, @@ -167,12 +155,13 @@ func newAbraApp(version, commit string) *cli.App { &UpgradeCommand, &AutoCompleteCommand, }, - BashComplete: autocomplete.SubcommandComplete, + EnableShellCompletion: true, + UseShortOptionHandling: true, + HideHelpCommand: true, + ShellComplete: autocomplete.SubcommandComplete, } - app.EnableBashCompletion = true - - app.Before = func(c *cli.Context) error { + app.Before = func(ctx context.Context, cmd *cli.Command) error { paths := []string{ config.ABRA_DIR, config.SERVERS_DIR, @@ -198,6 +187,12 @@ func newAbraApp(version, commit string) *cli.App { return nil } + cli.HelpFlag = &cli.BoolFlag{ + Name: "help", + Aliases: []string{"h, H"}, + Usage: "Show help", + } + return app } @@ -205,7 +200,7 @@ func newAbraApp(version, commit string) *cli.App { func RunApp(version, commit string) { app := newAbraApp(version, commit) - if err := app.Run(os.Args); err != nil { + if err := app.Run(context.Background(), os.Args); err != nil { log.Fatal(err) } } diff --git a/cli/internal/cli.go b/cli/internal/cli.go index ae4c52a7..63e8f9ce 100644 --- a/cli/internal/cli.go +++ b/cli/internal/cli.go @@ -1,10 +1,11 @@ package internal import ( + "context" "os" "coopcloud.tech/abra/pkg/log" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) // Secrets stores the variable from SecretsFlag @@ -74,7 +75,7 @@ var Chaos bool var ChaosFlag = &cli.BoolFlag{ Name: "chaos", Aliases: []string{"C"}, - Usage: "Proceed with uncommitted recipes changes. Use with care!", + Usage: "Ignore uncommitted recipes changes. Use with care!", Destination: &Chaos, } @@ -116,7 +117,7 @@ var OfflineFlag = &cli.BoolFlag{ Name: "offline", Aliases: []string{"o"}, Destination: &Offline, - Usage: "Prefer offline & filesystem access when possible", + Usage: "Prefer offline & filesystem access", } // ReleaseNotes stores the variable from ReleaseNotesFlag. @@ -138,7 +139,7 @@ var MachineReadableFlag = &cli.BoolFlag{ Name: "machine", Aliases: []string{"m"}, Destination: &MachineReadable, - Usage: "Output in a machine-readable format (where supported)", + Usage: "Machine-readable output", } // RC signifies the latest release candidate @@ -319,7 +320,7 @@ var AllServicesFlag = &cli.BoolFlag{ } // SubCommandBefore wires up pre-action machinery (e.g. --debug handling). -func SubCommandBefore(c *cli.Context) error { +func SubCommandBefore(ctx context.Context, cmd *cli.Command) error { if Debug { log.SetLevel(log.DebugLevel) log.SetOutput(os.Stderr) diff --git a/cli/internal/errors.go b/cli/internal/errors.go index 199accd7..45a19752 100644 --- a/cli/internal/errors.go +++ b/cli/internal/errors.go @@ -4,13 +4,13 @@ import ( "os" "coopcloud.tech/abra/pkg/log" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) // ShowSubcommandHelpAndError exits the program on error, logs the error to the // terminal, and shows the help command. -func ShowSubcommandHelpAndError(c *cli.Context, err interface{}) { - if err2 := cli.ShowSubcommandHelp(c); err2 != nil { +func ShowSubcommandHelpAndError(cmd *cli.Command, err interface{}) { + if err2 := cli.ShowSubcommandHelp(cmd); err2 != nil { log.Error(err2) } log.Error(err) diff --git a/cli/internal/validate.go b/cli/internal/validate.go index 42bb6635..29a41b1e 100644 --- a/cli/internal/validate.go +++ b/cli/internal/validate.go @@ -9,12 +9,12 @@ import ( "coopcloud.tech/abra/pkg/log" "coopcloud.tech/abra/pkg/recipe" "github.com/AlecAivazis/survey/v2" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) // ValidateRecipe ensures the recipe arg is valid. -func ValidateRecipe(c *cli.Context) recipe.Recipe { - recipeName := c.Args().First() +func ValidateRecipe(cmd *cli.Command) recipe.Recipe { + recipeName := cmd.Args().First() if recipeName == "" && !NoInput { var recipes []string @@ -54,7 +54,7 @@ func ValidateRecipe(c *cli.Context) recipe.Recipe { } if recipeName == "" { - ShowSubcommandHelpAndError(c, errors.New("no recipe name provided")) + ShowSubcommandHelpAndError(cmd, errors.New("no recipe name provided")) } chosenRecipe := recipe.Get(recipeName) @@ -64,7 +64,7 @@ func ValidateRecipe(c *cli.Context) recipe.Recipe { } _, err = chosenRecipe.GetComposeConfig(nil) if err != nil { - if c.Command.Name == "generate" { + if cmd.Name == "generate" { if strings.Contains(err.Error(), "missing a compose") { log.Fatal(err) } @@ -83,11 +83,11 @@ func ValidateRecipe(c *cli.Context) recipe.Recipe { } // ValidateApp ensures the app name arg is valid. -func ValidateApp(c *cli.Context) app.App { - appName := c.Args().First() +func ValidateApp(cmd *cli.Command) app.App { + appName := cmd.Args().First() if appName == "" { - ShowSubcommandHelpAndError(c, errors.New("no app provided")) + ShowSubcommandHelpAndError(cmd, errors.New("no app provided")) } app, err := app.Get(appName) @@ -101,8 +101,8 @@ func ValidateApp(c *cli.Context) app.App { } // ValidateDomain ensures the domain name arg is valid. -func ValidateDomain(c *cli.Context) string { - domainName := c.Args().First() +func ValidateDomain(cmd *cli.Command) string { + domainName := cmd.Args().First() if domainName == "" && !NoInput { prompt := &survey.Input{ @@ -115,7 +115,7 @@ func ValidateDomain(c *cli.Context) string { } if domainName == "" { - ShowSubcommandHelpAndError(c, errors.New("no domain provided")) + ShowSubcommandHelpAndError(cmd, errors.New("no domain provided")) } log.Debugf("validated %s as domain argument", domainName) @@ -124,10 +124,10 @@ func ValidateDomain(c *cli.Context) string { } // ValidateSubCmdFlags ensures flag order conforms to correct order -func ValidateSubCmdFlags(c *cli.Context) bool { - for argIdx, arg := range c.Args().Slice() { +func ValidateSubCmdFlags(cmd *cli.Command) bool { + for argIdx, arg := range cmd.Args().Slice() { if !strings.HasPrefix(arg, "--") { - for _, flag := range c.Args().Slice()[argIdx:] { + for _, flag := range cmd.Args().Slice()[argIdx:] { if strings.HasPrefix(flag, "--") { return false } @@ -138,8 +138,8 @@ func ValidateSubCmdFlags(c *cli.Context) bool { } // ValidateServer ensures the server name arg is valid. -func ValidateServer(c *cli.Context) string { - serverName := c.Args().First() +func ValidateServer(cmd *cli.Command) string { + serverName := cmd.Args().First() serverNames, err := config.ReadServerNames() if err != nil { @@ -164,11 +164,11 @@ func ValidateServer(c *cli.Context) string { } if serverName == "" { - ShowSubcommandHelpAndError(c, errors.New("no server provided")) + ShowSubcommandHelpAndError(cmd, errors.New("no server provided")) } if !matched { - ShowSubcommandHelpAndError(c, errors.New("server doesn't exist?")) + ShowSubcommandHelpAndError(cmd, errors.New("server doesn't exist?")) } log.Debugf("validated %s as server argument", serverName) diff --git a/cli/recipe/diff.go b/cli/recipe/diff.go index 3eb42482..81c5fff5 100644 --- a/cli/recipe/diff.go +++ b/cli/recipe/diff.go @@ -1,27 +1,26 @@ package recipe import ( + "context" + "coopcloud.tech/abra/cli/internal" "coopcloud.tech/abra/pkg/autocomplete" gitPkg "coopcloud.tech/abra/pkg/git" "coopcloud.tech/abra/pkg/log" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var recipeDiffCommand = cli.Command{ - Name: "diff", - Usage: "Show unstaged changes in recipe config", - Description: "This command requires /usr/bin/git.", - Aliases: []string{"d"}, - ArgsUsage: "", - Flags: []cli.Flag{ - internal.DebugFlag, - internal.NoInputFlag, - }, - Before: internal.SubCommandBefore, - BashComplete: autocomplete.RecipeNameComplete, - Action: func(c *cli.Context) error { - r := internal.ValidateRecipe(c) + Name: "diff", + Usage: "Show unstaged changes in recipe config", + Description: "This command requires /usr/bin/git.", + Aliases: []string{"d"}, + UsageText: "abra recipe diff [options]", + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.RecipeNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + r := internal.ValidateRecipe(cmd) if err := gitPkg.DiffUnstaged(r.Dir); err != nil { log.Fatal(err) diff --git a/cli/recipe/fetch.go b/cli/recipe/fetch.go index d9da2eed..8dd7d1e0 100644 --- a/cli/recipe/fetch.go +++ b/cli/recipe/fetch.go @@ -1,32 +1,30 @@ package recipe import ( + "context" + "coopcloud.tech/abra/cli/internal" "coopcloud.tech/abra/pkg/autocomplete" "coopcloud.tech/abra/pkg/formatter" "coopcloud.tech/abra/pkg/log" "coopcloud.tech/abra/pkg/recipe" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var recipeFetchCommand = cli.Command{ - Name: "fetch", - Usage: "Fetch recipe(s)", - Aliases: []string{"f"}, - ArgsUsage: "[]", - Description: "Retrieves all recipes if no argument is passed", - Flags: []cli.Flag{ - internal.DebugFlag, - internal.NoInputFlag, - internal.OfflineFlag, - }, - Before: internal.SubCommandBefore, - BashComplete: autocomplete.RecipeNameComplete, - Action: func(c *cli.Context) error { - recipeName := c.Args().First() + Name: "fetch", + Usage: "Fetch recipe(s)", + Aliases: []string{"f"}, + UsageText: "abra recipe fetch [] [options]", + Description: "Retrieves all recipes if no argument is passed", + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.RecipeNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + recipeName := cmd.Args().First() r := recipe.Get(recipeName) if recipeName != "" { - internal.ValidateRecipe(c) + internal.ValidateRecipe(cmd) if err := r.Ensure(false, false); err != nil { log.Fatal(err) } diff --git a/cli/recipe/lint.go b/cli/recipe/lint.go index 295f2704..afac0c2c 100644 --- a/cli/recipe/lint.go +++ b/cli/recipe/lint.go @@ -1,6 +1,7 @@ package recipe import ( + "context" "fmt" "coopcloud.tech/abra/cli/internal" @@ -8,25 +9,23 @@ import ( "coopcloud.tech/abra/pkg/formatter" "coopcloud.tech/abra/pkg/lint" "coopcloud.tech/abra/pkg/log" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var recipeLintCommand = cli.Command{ Name: "lint", Usage: "Lint a recipe", Aliases: []string{"l"}, - ArgsUsage: "", + UsageText: "abra recipe lint [options]", Flags: []cli.Flag{ - internal.DebugFlag, internal.OnlyErrorFlag, - internal.OfflineFlag, - internal.NoInputFlag, internal.ChaosFlag, }, - Before: internal.SubCommandBefore, - BashComplete: autocomplete.RecipeNameComplete, - Action: func(c *cli.Context) error { - recipe := internal.ValidateRecipe(c) + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.RecipeNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + recipe := internal.ValidateRecipe(cmd) if err := recipe.Ensure(internal.Chaos, internal.Offline); err != nil { log.Fatal(err) diff --git a/cli/recipe/list.go b/cli/recipe/list.go index 82be8c78..a3ccf03b 100644 --- a/cli/recipe/list.go +++ b/cli/recipe/list.go @@ -1,6 +1,7 @@ package recipe import ( + "context" "fmt" "sort" "strconv" @@ -10,7 +11,7 @@ import ( "coopcloud.tech/abra/pkg/formatter" "coopcloud.tech/abra/pkg/log" "coopcloud.tech/abra/pkg/recipe" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var pattern string @@ -23,17 +24,17 @@ var patternFlag = &cli.StringFlag{ } var recipeListCommand = cli.Command{ - Name: "list", - Usage: "List available recipes", - Aliases: []string{"ls"}, + Name: "list", + Usage: "List recipes", + UsageText: "abra recipe list [options]", + Aliases: []string{"ls"}, Flags: []cli.Flag{ - internal.DebugFlag, internal.MachineReadableFlag, patternFlag, - internal.OfflineFlag, }, - Before: internal.SubCommandBefore, - Action: func(c *cli.Context) error { + Before: internal.SubCommandBefore, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { catl, err := recipe.ReadRecipeCatalogue(internal.Offline) if err != nil { log.Fatal(err.Error()) diff --git a/cli/recipe/new.go b/cli/recipe/new.go index 16e8f6f7..93b65c67 100644 --- a/cli/recipe/new.go +++ b/cli/recipe/new.go @@ -2,6 +2,7 @@ package recipe import ( "bytes" + "context" "errors" "fmt" "os" @@ -13,7 +14,7 @@ import ( "coopcloud.tech/abra/pkg/git" "coopcloud.tech/abra/pkg/log" "coopcloud.tech/abra/pkg/recipe" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) // recipeMetadata is the recipe metadata for the README.md @@ -34,27 +35,24 @@ var recipeNewCommand = cli.Command{ Name: "new", Aliases: []string{"n"}, Flags: []cli.Flag{ - internal.DebugFlag, - internal.NoInputFlag, - internal.OfflineFlag, internal.GitNameFlag, internal.GitEmailFlag, }, Before: internal.SubCommandBefore, Usage: "Create a new recipe", - ArgsUsage: "", - Description: ` -Create a new recipe. + UsageText: "abra recipe new [options]", + Description: `Create a new recipe. Abra uses the built-in example repository which is available here: https://git.coopcloud.tech/coop-cloud/example`, - Action: func(c *cli.Context) error { - recipeName := c.Args().First() + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + recipeName := cmd.Args().First() r := recipe.Get(recipeName) if recipeName == "" { - internal.ShowSubcommandHelpAndError(c, errors.New("no recipe name provided")) + internal.ShowSubcommandHelpAndError(cmd, errors.New("no recipe name provided")) } if _, err := os.Stat(r.Dir); !os.IsNotExist(err) { diff --git a/cli/recipe/recipe.go b/cli/recipe/recipe.go index bed88864..0b9e68c4 100644 --- a/cli/recipe/recipe.go +++ b/cli/recipe/recipe.go @@ -1,7 +1,7 @@ package recipe import ( - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) // RecipeCommand defines all recipe related sub-commands. @@ -9,17 +9,17 @@ var RecipeCommand = cli.Command{ Name: "recipe", Aliases: []string{"r"}, Usage: "Manage recipes", - ArgsUsage: "", - Description: ` -A recipe is a blueprint for an app. It is a bunch of config files which -describe how to deploy and maintain an app. Recipes are maintained by the Co-op -Cloud community and you can use Abra to read them, deploy them and create apps -for you. + UsageText: "abra recipe [command] [arguments] [options]", + Description: `A recipe is a blueprint for an app. + +It is a bunch of config files which describe how to deploy and maintain an app. +Recipes are maintained by the Co-op Cloud community and you can use Abra to +read them, deploy them and create apps for you. Anyone who uses a recipe can become a maintainer. Maintainers typically make sure the recipe is in good working order and the config upgraded in a timely manner.`, - Subcommands: []*cli.Command{ + Commands: []*cli.Command{ &recipeFetchCommand, &recipeLintCommand, &recipeListCommand, diff --git a/cli/recipe/release.go b/cli/recipe/release.go index 1fdae64c..58987931 100644 --- a/cli/recipe/release.go +++ b/cli/recipe/release.go @@ -1,6 +1,7 @@ package recipe import ( + "context" "errors" "fmt" "os" @@ -18,17 +19,18 @@ import ( "github.com/AlecAivazis/survey/v2" "github.com/distribution/reference" "github.com/go-git/go-git/v5" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var recipeReleaseCommand = cli.Command{ Name: "release", Aliases: []string{"rl"}, Usage: "Release a new recipe version", - ArgsUsage: " []", - Description: ` -Create a new version of a recipe. These versions are then published on the -Co-op Cloud recipe catalogue. These versions take the following form: + UsageText: "abra recipe release [] [options]", + Description: `Create a new version of a recipe. + +These versions are then published on the Co-op Cloud recipe catalogue. These +versions take the following form: a.b.c+x.y.z @@ -46,19 +48,17 @@ Publish your new release to git.coopcloud.tech with "-p/--publish". This requires that you have permission to git push to these repositories and have your SSH keys configured on your account.`, Flags: []cli.Flag{ - internal.DebugFlag, - internal.NoInputFlag, internal.DryFlag, internal.MajorFlag, internal.MinorFlag, internal.PatchFlag, internal.PublishFlag, - internal.OfflineFlag, }, - Before: internal.SubCommandBefore, - BashComplete: autocomplete.RecipeNameComplete, - Action: func(c *cli.Context) error { - recipe := internal.ValidateRecipe(c) + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.RecipeNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + recipe := internal.ValidateRecipe(cmd) imagesTmp, err := getImageVersions(recipe) if err != nil { @@ -75,7 +75,7 @@ your SSH keys configured on your account.`, log.Fatalf("main app service version for %s is empty?", recipe.Name) } - tagString := c.Args().Get(1) + tagString := cmd.Args().Get(1) if tagString != "" { if _, err := tagcmp.Parse(tagString); err != nil { log.Fatalf("cannot parse %s, invalid tag specified?", tagString) diff --git a/cli/recipe/reset.go b/cli/recipe/reset.go index 158be4a0..74a7a28c 100644 --- a/cli/recipe/reset.go +++ b/cli/recipe/reset.go @@ -1,32 +1,31 @@ package recipe import ( + "context" + "coopcloud.tech/abra/cli/internal" "coopcloud.tech/abra/pkg/autocomplete" "coopcloud.tech/abra/pkg/log" "coopcloud.tech/abra/pkg/recipe" "github.com/go-git/go-git/v5" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var recipeResetCommand = cli.Command{ - Name: "reset", - Usage: "Remove all unstaged changes from recipe config", - Description: "WARNING: this will delete your changes. Be Careful.", - Aliases: []string{"rs"}, - ArgsUsage: "", - Flags: []cli.Flag{ - internal.DebugFlag, - internal.NoInputFlag, - }, - Before: internal.SubCommandBefore, - BashComplete: autocomplete.RecipeNameComplete, - Action: func(c *cli.Context) error { - recipeName := c.Args().First() + Name: "reset", + Usage: "Remove all unstaged changes from recipe config", + Description: "WARNING: this will delete your changes. Be Careful.", + Aliases: []string{"rs"}, + UsageText: "abra recipe reset [options]", + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.RecipeNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + recipeName := cmd.Args().First() r := recipe.Get(recipeName) if recipeName != "" { - internal.ValidateRecipe(c) + internal.ValidateRecipe(cmd) } repo, err := git.PlainOpen(r.Dir) diff --git a/cli/recipe/sync.go b/cli/recipe/sync.go index 06f11b73..04f5468d 100644 --- a/cli/recipe/sync.go +++ b/cli/recipe/sync.go @@ -1,6 +1,7 @@ package recipe import ( + "context" "fmt" "strconv" @@ -12,35 +13,34 @@ import ( "github.com/AlecAivazis/survey/v2" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var recipeSyncCommand = cli.Command{ Name: "sync", Aliases: []string{"s"}, Usage: "Sync recipe version label", - ArgsUsage: " []", + UsageText: "abra recipe lint [] [options]", Flags: []cli.Flag{ - internal.DebugFlag, - internal.NoInputFlag, internal.DryFlag, internal.MajorFlag, internal.MinorFlag, internal.PatchFlag, }, Before: internal.SubCommandBefore, - Description: ` -Generate labels for the main recipe service (i.e. by convention, the service -named "app") which corresponds to the following format: + Description: `Generate labels for the main recipe service. + +By convention, the service named "app" using the following format: coop-cloud.${STACK_NAME}.version= Where can be specifed on the command-line or Abra can attempt to auto-generate it for you. The configuration will be updated on the local file system.`, - BashComplete: autocomplete.RecipeNameComplete, - Action: func(c *cli.Context) error { - recipe := internal.ValidateRecipe(c) + ShellComplete: autocomplete.RecipeNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + recipe := internal.ValidateRecipe(cmd) mainApp, err := internal.GetMainAppImage(recipe) if err != nil { @@ -59,7 +59,7 @@ local file system.`, log.Fatal(err) } - nextTag := c.Args().Get(1) + nextTag := cmd.Args().Get(1) if len(tags) == 0 && nextTag == "" { log.Warnf("no git tags found for %s", recipe.Name) if internal.NoInput { diff --git a/cli/recipe/upgrade.go b/cli/recipe/upgrade.go index 69c089e7..856dc1e7 100644 --- a/cli/recipe/upgrade.go +++ b/cli/recipe/upgrade.go @@ -2,6 +2,7 @@ package recipe import ( "bufio" + "context" "encoding/json" "fmt" "os" @@ -19,7 +20,7 @@ import ( "coopcloud.tech/tagcmp" "github.com/AlecAivazis/survey/v2" "github.com/distribution/reference" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) type imgPin struct { @@ -27,8 +28,8 @@ type imgPin struct { version tagcmp.Tag } -// anUpgrade represents a single service upgrade (as within a recipe), and the list of tags that it can be upgraded to, -// for serialization purposes. +// anUpgrade represents a single service upgrade (as within a recipe), and the +// list of tags that it can be upgraded to, for serialization purposes. type anUpgrade struct { Service string `json:"service"` Image string `json:"image"` @@ -37,13 +38,13 @@ type anUpgrade struct { } var recipeUpgradeCommand = cli.Command{ - Name: "upgrade", - Aliases: []string{"u"}, - Usage: "Upgrade recipe image tags", - Description: ` -Parse all image tags within the given configuration and prompt with -more recent tags to upgrade to. It will update the relevant compose file tags -on the local file system. + Name: "upgrade", + Aliases: []string{"u"}, + Usage: "Upgrade recipe image tags", + UsageText: "abra recipe upgrade [] [options]", + Description: `Upgrade a given configuration. + +It will update the relevant compose file tags on the local file system. Some image tags cannot be parsed because they do not follow some sort of semver-like convention. In this case, all possible tags will be listed and it @@ -53,25 +54,19 @@ The command is interactive and will show a select input which allows you to make a seclection. Use the "?" key to see more help on navigating this interface. -You may invoke this command in "wizard" mode and be prompted for input. - -EXAMPLE: - - abra recipe upgrade`, - ArgsUsage: "", +You may invoke this command in "wizard" mode and be prompted for input.`, Flags: []cli.Flag{ - internal.DebugFlag, - internal.NoInputFlag, internal.PatchFlag, internal.MinorFlag, internal.MajorFlag, internal.MachineReadableFlag, internal.AllTagsFlag, }, - Before: internal.SubCommandBefore, - BashComplete: autocomplete.RecipeNameComplete, - Action: func(c *cli.Context) error { - recipe := internal.ValidateRecipe(c) + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.RecipeNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + recipe := internal.ValidateRecipe(cmd) if err := recipe.Ensure(internal.Chaos, internal.Offline); err != nil { log.Fatal(err) diff --git a/cli/recipe/version.go b/cli/recipe/version.go index 30c70641..24302cb7 100644 --- a/cli/recipe/version.go +++ b/cli/recipe/version.go @@ -1,6 +1,7 @@ package recipe import ( + "context" "fmt" "sort" @@ -9,7 +10,7 @@ import ( "coopcloud.tech/abra/pkg/formatter" "coopcloud.tech/abra/pkg/log" recipePkg "coopcloud.tech/abra/pkg/recipe" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) func sortServiceByName(versions [][]string) func(i, j int) bool { @@ -26,19 +27,17 @@ var recipeVersionCommand = cli.Command{ Name: "versions", Aliases: []string{"v"}, Usage: "List recipe versions", - ArgsUsage: "", + UsageText: "abra recipe version [options]", Flags: []cli.Flag{ - internal.DebugFlag, - internal.OfflineFlag, - internal.NoInputFlag, internal.MachineReadableFlag, }, - Before: internal.SubCommandBefore, - BashComplete: autocomplete.RecipeNameComplete, - Action: func(c *cli.Context) error { + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.RecipeNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { var warnMessages []string - recipe := internal.ValidateRecipe(c) + recipe := internal.ValidateRecipe(cmd) catl, err := recipePkg.ReadRecipeCatalogue(internal.Offline) if err != nil { diff --git a/cli/server/add.go b/cli/server/add.go index c19ab42c..949fe970 100644 --- a/cli/server/add.go +++ b/cli/server/add.go @@ -1,6 +1,7 @@ package server import ( + "context" "errors" "os" "path/filepath" @@ -13,7 +14,7 @@ import ( "coopcloud.tech/abra/pkg/log" "coopcloud.tech/abra/pkg/server" sshPkg "coopcloud.tech/abra/pkg/ssh" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var local bool @@ -93,15 +94,15 @@ func createServerDir(name string) (bool, error) { } var serverAddCommand = cli.Command{ - Name: "add", - Aliases: []string{"a"}, - Usage: "Add a new server to your configuration", - Description: ` -Add a new server to your configuration so that it can be managed by Abra. + Name: "add", + Aliases: []string{"a"}, + Usage: "Add a new server", + UsageText: "abra server add [options]", + Description: `Add a new server to your configuration so that it can be managed by Abra. Abra relies on the standard SSH command-line and ~/.ssh/config for client connection details. You must configure an entry per-host in your ~/.ssh/config -for each server. For example: +for each server: Host example.com example Hostname example.com @@ -109,10 +110,6 @@ for each server. For example: Port 12345 IdentityFile ~/.ssh/example@somewhere -You can then add a server like so: - - abra server add example.com - If "--local" is passed, then Abra assumes that the current local server is intended as the target server. This is useful when you want to have your entire Co-op Cloud config located on the server itself, and not on your local @@ -120,28 +117,24 @@ developer machine. The domain is then set to "default". You can also pass "--no-domain-checks/-D" flag to use any arbitrary name instead of a real domain. The host will be resolved with the "Hostname" entry -of your ~/.ssh/config. Checks for a valid online domain will be skipped: - - abra server add -D example`, +of your ~/.ssh/config. Checks for a valid online domain will be skipped.`, Flags: []cli.Flag{ - internal.DebugFlag, - internal.NoInputFlag, internal.NoDomainChecksFlag, localFlag, }, - Before: internal.SubCommandBefore, - ArgsUsage: "", - Action: func(c *cli.Context) error { - if c.Args().Len() > 0 && local || !internal.ValidateSubCmdFlags(c) { + Before: internal.SubCommandBefore, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + if cmd.Args().Len() > 0 && local || !internal.ValidateSubCmdFlags(cmd) { err := errors.New("cannot use and --local together") - internal.ShowSubcommandHelpAndError(c, err) + internal.ShowSubcommandHelpAndError(cmd, err) } var name string if local { name = "default" } else { - name = internal.ValidateDomain(c) + name = internal.ValidateDomain(cmd) } // NOTE(d1): reasonable 5 second timeout for connections which can't diff --git a/cli/server/list.go b/cli/server/list.go index 788aebb2..1db5161e 100644 --- a/cli/server/list.go +++ b/cli/server/list.go @@ -1,30 +1,31 @@ package server import ( + "context" "fmt" "strings" "coopcloud.tech/abra/cli/internal" "coopcloud.tech/abra/pkg/config" - "coopcloud.tech/abra/pkg/context" + contextPkg "coopcloud.tech/abra/pkg/context" "coopcloud.tech/abra/pkg/formatter" "coopcloud.tech/abra/pkg/log" "github.com/docker/cli/cli/connhelper/ssh" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var serverListCommand = cli.Command{ - Name: "list", - Aliases: []string{"ls"}, - Usage: "List managed servers", + Name: "list", + Aliases: []string{"ls"}, + Usage: "List managed servers", + UsageText: "abra server list [options]", Flags: []cli.Flag{ - internal.DebugFlag, internal.MachineReadableFlag, - internal.OfflineFlag, }, - Before: internal.SubCommandBefore, - Action: func(c *cli.Context) error { - dockerContextStore := context.NewDefaultDockerContextStore() + Before: internal.SubCommandBefore, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + dockerContextStore := contextPkg.NewDefaultDockerContextStore() contexts, err := dockerContextStore.Store.List() if err != nil { log.Fatal(err) @@ -46,14 +47,14 @@ var serverListCommand = cli.Command{ var rows [][]string for _, serverName := range serverNames { var row []string - for _, ctx := range contexts { - endpoint, err := context.GetContextEndpoint(ctx) + for _, dockerCtx := range contexts { + endpoint, err := contextPkg.GetContextEndpoint(dockerCtx) if err != nil && strings.Contains(err.Error(), "does not exist") { // No local context found, we can continue safely continue } - if ctx.Name == serverName { + if dockerCtx.Name == serverName { sp, err := ssh.ParseURL(endpoint) if err != nil { log.Fatal(err) diff --git a/cli/server/prune.go b/cli/server/prune.go index b913ee4b..b8993c4d 100644 --- a/cli/server/prune.go +++ b/cli/server/prune.go @@ -9,7 +9,7 @@ import ( "coopcloud.tech/abra/pkg/formatter" "coopcloud.tech/abra/pkg/log" "github.com/docker/docker/api/types/filters" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var allFilter bool @@ -31,26 +31,23 @@ var volumesFilterFlag = &cli.BoolFlag{ } var serverPruneCommand = cli.Command{ - Name: "prune", - Aliases: []string{"p"}, - Usage: "Prune resources on a server", - Description: ` -Prunes unused containers, networks, and dangling images. + Name: "prune", + Aliases: []string{"p"}, + Usage: "Prune resources on a server", + UsageText: "abra server prune [options]", + Description: `Prunes unused containers, networks, and dangling images. Use "-v/--volumes" to remove volumes that are not associated with a deployed app. This can result in unwanted data loss if not used carefully.`, - ArgsUsage: "[]", Flags: []cli.Flag{ allFilterFlag, volumesFilterFlag, - internal.DebugFlag, - internal.OfflineFlag, - internal.NoInputFlag, }, - Before: internal.SubCommandBefore, - BashComplete: autocomplete.ServerNameComplete, - Action: func(c *cli.Context) error { - serverName := internal.ValidateServer(c) + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.ServerNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + serverName := internal.ValidateServer(cmd) cl, err := client.New(serverName) if err != nil { @@ -59,7 +56,6 @@ app. This can result in unwanted data loss if not used carefully.`, var args filters.Args - ctx := context.Background() cr, err := cl.ContainersPrune(ctx, args) if err != nil { log.Fatal(err) diff --git a/cli/server/remove.go b/cli/server/remove.go index 5364e12e..56a0ccbe 100644 --- a/cli/server/remove.go +++ b/cli/server/remove.go @@ -1,6 +1,7 @@ package server import ( + "context" "os" "path/filepath" @@ -9,29 +10,24 @@ import ( "coopcloud.tech/abra/pkg/client" "coopcloud.tech/abra/pkg/config" "coopcloud.tech/abra/pkg/log" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) var serverRemoveCommand = cli.Command{ Name: "remove", Aliases: []string{"rm"}, - ArgsUsage: "", + UsageText: "abra server remove [options]", Usage: "Remove a managed server", - Description: ` -Remove a managed server. + Description: `Remove a managed server. -Abra will remove the internal bookkeeping (~/.abra/servers/...) and underlying -client connection context. This server will then be lost in time, like tears in -rain.`, - Flags: []cli.Flag{ - internal.DebugFlag, - internal.NoInputFlag, - internal.OfflineFlag, - }, - Before: internal.SubCommandBefore, - BashComplete: autocomplete.ServerNameComplete, - Action: func(c *cli.Context) error { - serverName := internal.ValidateServer(c) +Abra will remove the internal bookkeeping ($ABRA_DIR/servers/...) and +underlying client connection context. This server will then be lost in time, +like tears in rain.`, + Before: internal.SubCommandBefore, + ShellComplete: autocomplete.ServerNameComplete, + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { + serverName := internal.ValidateServer(cmd) if err := client.DeleteContext(serverName); err != nil { log.Fatal(err) diff --git a/cli/server/server.go b/cli/server/server.go index 196702dd..e941ab9a 100644 --- a/cli/server/server.go +++ b/cli/server/server.go @@ -1,15 +1,16 @@ package server import ( - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) // ServerCommand defines the `abra server` command and its subcommands var ServerCommand = cli.Command{ - Name: "server", - Aliases: []string{"s"}, - Usage: "Manage servers", - Subcommands: []*cli.Command{ + Name: "server", + Aliases: []string{"s"}, + Usage: "Manage servers", + UsageText: "abra server [command] [arguments] [options]", + Commands: []*cli.Command{ &serverAddCommand, &serverListCommand, &serverRemoveCommand, diff --git a/cli/updater/updater.go b/cli/updater/updater.go index 62c7a3b1..9a59cf4b 100644 --- a/cli/updater/updater.go +++ b/cli/updater/updater.go @@ -23,7 +23,7 @@ import ( dockerclient "github.com/docker/docker/client" "coopcloud.tech/abra/pkg/log" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) const SERVER = "localhost" @@ -46,23 +46,21 @@ var allFlag = &cli.BoolFlag{ // Notify checks for available upgrades var Notify = cli.Command{ - Name: "notify", - Aliases: []string{"n"}, - Usage: "Check for available upgrades", + Name: "notify", + Aliases: []string{"n"}, + Usage: "Check for available upgrades", + UsageText: "kadabra notify [options]", Flags: []cli.Flag{ - internal.DebugFlag, majorFlag, - internal.OfflineFlag, }, Before: internal.SubCommandBefore, - Description: ` -Read the deployed app versions and look for new versions in the recipe -catalogue. + Description: `Notify on new versions for deployed apps. If a new patch/minor version is available, a notification is printed. Use "--major" to include new major versions.`, - Action: func(c *cli.Context) error { + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { cl, err := client.New("default") if err != nil { log.Fatal(err) @@ -97,17 +95,14 @@ var UpgradeApp = cli.Command{ Name: "upgrade", Aliases: []string{"u"}, Usage: "Upgrade apps", - ArgsUsage: " ", + UsageText: "kadabra notify [options]", Flags: []cli.Flag{ - internal.DebugFlag, internal.ChaosFlag, majorFlag, allFlag, - internal.OfflineFlag, }, Before: internal.SubCommandBefore, - Description: ` -Upgrade an app by specifying stack name and recipe. + Description: `Upgrade an app by specifying stack name and recipe. Use "--all" to upgrade every deployed app. @@ -118,15 +113,16 @@ available, the app is upgraded. To include major versions use the "--major" flag. You probably don't want that as it will break things. Only apps that are not deployed with "--chaos" are upgraded, to update chaos deployments use the "--chaos" flag. Use it with care.`, - Action: func(c *cli.Context) error { + HideHelp: true, + Action: func(ctx context.Context, cmd *cli.Command) error { cl, err := client.New("default") if err != nil { log.Fatal(err) } if !updateAll { - stackName := c.Args().Get(0) - recipeName := c.Args().Get(1) + stackName := cmd.Args().Get(0) + recipeName := cmd.Args().Get(1) err = tryUpgrade(cl, stackName, recipeName) if err != nil { log.Fatal(err) @@ -470,25 +466,25 @@ func upgrade(cl *dockerclient.Client, stackName, recipeName, upgradeVersion stri return err } -func newAbraApp(version, commit string) *cli.App { - app := &cli.App{ - Name: "kadabra", - Usage: `The Co-op Cloud auto-updater - ____ ____ _ _ - / ___|___ ___ _ __ / ___| | ___ _ _ __| | - | | / _ \ _____ / _ \| '_ \ | | | |/ _ \| | | |/ _' | - | |__| (_) |_____| (_) | |_) | | |___| | (_) | |_| | (_| | - \____\___/ \___/| .__/ \____|_|\___/ \__,_|\__,_| - |_| -`, - Version: fmt.Sprintf("%s-%s", version, commit[:7]), +func newKadabraApp(version, commit string) *cli.Command { + app := &cli.Command{ + Name: "kadabra", + Version: fmt.Sprintf("%s-%s", version, commit[:7]), + Usage: "The Co-op Cloud auto-updater 🤖 🚀", + UsageText: "kadabra [command] [options]", + UseShortOptionHandling: true, + HideHelpCommand: true, + Flags: []cli.Flag{ + // NOTE(d1): "GLOBAL OPTIONS" flags + internal.DebugFlag, + }, Commands: []*cli.Command{ &Notify, &UpgradeApp, }, } - app.Before = func(c *cli.Context) error { + app.Before = func(ctx context.Context, cmd *cli.Command) error { log.Logger.SetStyles(log.Styles()) charmLog.SetDefault(log.Logger) @@ -497,14 +493,20 @@ func newAbraApp(version, commit string) *cli.App { return nil } + cli.HelpFlag = &cli.BoolFlag{ + Name: "help", + Aliases: []string{"h, H"}, + Usage: "Show help", + } + return app } // RunApp runs CLI abra app. func RunApp(version, commit string) { - app := newAbraApp(version, commit) + app := newKadabraApp(version, commit) - if err := app.Run(os.Args); err != nil { + if err := app.Run(context.Background(), os.Args); err != nil { log.Fatal(err) } } diff --git a/go.mod b/go.mod index 5450d227..f63e27b6 100644 --- a/go.mod +++ b/go.mod @@ -2,6 +2,8 @@ module coopcloud.tech/abra go 1.21 +replace github.com/urfave/cli/v3 => github.com/urfave/cli/v3 v3.0.0-alpha9.1.0.20241019193437-5053ec708a44 + require ( coopcloud.tech/tagcmp v0.0.0-20230809071031-eb3e7758d4eb git.coopcloud.tech/coop-cloud/godotenv v1.5.2-0.20231130100509-01bff8284355 @@ -18,7 +20,7 @@ require ( github.com/moby/term v0.5.0 github.com/pkg/errors v0.9.1 github.com/schollz/progressbar/v3 v3.14.4 - github.com/urfave/cli/v2 v2.27.2 + github.com/urfave/cli/v3 v3.0.0-alpha9 golang.org/x/term v0.22.0 gopkg.in/yaml.v3 v3.0.1 gotest.tools/v3 v3.5.1 @@ -37,7 +39,6 @@ require ( github.com/charmbracelet/x/ansi v0.1.3 // indirect github.com/cloudflare/circl v1.3.9 // indirect github.com/containerd/log v0.1.0 // indirect - github.com/cpuguy83/go-md2man/v2 v2.0.4 // indirect github.com/cyphar/filepath-securejoin v0.2.5 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/docker/distribution v2.8.3+incompatible // indirect @@ -85,14 +86,12 @@ require ( github.com/prometheus/common v0.55.0 // indirect github.com/prometheus/procfs v0.15.1 // indirect github.com/rivo/uniseg v0.4.7 // indirect - github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/skeema/knownhosts v1.2.2 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/xanzy/ssh-agent v0.3.3 // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect - github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.53.0 // indirect go.opentelemetry.io/otel v1.28.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.28.0 // indirect diff --git a/go.sum b/go.sum index 484f4807..8db8fd89 100644 --- a/go.sum +++ b/go.sum @@ -273,7 +273,6 @@ github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfc github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4= github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= @@ -799,7 +798,6 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/safchain/ethtool v0.0.0-20190326074333-42ed695e3de8/go.mod h1:Z0q5wiBQGYcxhMZ6gUqHn6pYNLypFAvaL3UvgZLR0U4= github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= @@ -883,8 +881,8 @@ github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijb github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= github.com/urfave/cli v1.22.2/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= github.com/urfave/cli v1.22.4/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= -github.com/urfave/cli/v2 v2.27.2 h1:6e0H+AkS+zDckwPCUrZkKX38mRaau4nL2uipkJpbkcI= -github.com/urfave/cli/v2 v2.27.2/go.mod h1:g0+79LmHHATl7DAcHO99smiR/T7uGLw84w8Y42x+4eM= +github.com/urfave/cli/v3 v3.0.0-alpha9.1.0.20241019193437-5053ec708a44 h1:BeSTAZEDkDVNv9EOrycIGCkEg+6EhRRgSsbdc93Q3OM= +github.com/urfave/cli/v3 v3.0.0-alpha9.1.0.20241019193437-5053ec708a44/go.mod h1:FnIeEMYu+ko8zP1F9Ypr3xkZMIDqW3DR92yUtY39q1Y= github.com/vbatts/tar-split v0.11.2/go.mod h1:vV3ZuO2yWSVsz+pfFzDG/upWH1JhjOiEaWq6kXyQ3VI= github.com/vishvananda/netlink v0.0.0-20181108222139-023a6dafdcdf/go.mod h1:+SR5DhBJrl6ZM7CoCKvpw5BKroDKQ+PJqOg65H/2ktk= github.com/vishvananda/netlink v1.1.0/go.mod h1:cTgwzPIzzgDAYoQrMm0EdrjRUBkTqKYppBueQtXaqoE= @@ -906,8 +904,6 @@ github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17 github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= -github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913 h1:+qGGcbkzsfDQNPPe9UDgpxAWQrhbbBXOYJFQDq/dtJw= -github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913/go.mod h1:4aEEwZQutDLsQv2Deui4iYQ6DWTxR14g6m8Wv88+Xqk= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= diff --git a/pkg/autocomplete/autocomplete.go b/pkg/autocomplete/autocomplete.go index 93e57d73..b4cce02a 100644 --- a/pkg/autocomplete/autocomplete.go +++ b/pkg/autocomplete/autocomplete.go @@ -1,22 +1,23 @@ package autocomplete import ( + "context" "fmt" "coopcloud.tech/abra/pkg/app" "coopcloud.tech/abra/pkg/log" "coopcloud.tech/abra/pkg/recipe" - "github.com/urfave/cli/v2" + "github.com/urfave/cli/v3" ) // AppNameComplete copletes app names. -func AppNameComplete(c *cli.Context) { +func AppNameComplete(ctx context.Context, cmd *cli.Command) { appNames, err := app.GetAppNames() if err != nil { log.Warn(err) } - if c.NArg() > 0 { + if cmd.NArg() > 0 { return } @@ -36,13 +37,13 @@ func ServiceNameComplete(appName string) { } // RecipeNameComplete completes recipe names. -func RecipeNameComplete(c *cli.Context) { +func RecipeNameComplete(ctx context.Context, cmd *cli.Command) { catl, err := recipe.ReadRecipeCatalogue(false) if err != nil { log.Warn(err) } - if c.NArg() > 0 { + if cmd.NArg() > 0 { return } @@ -66,13 +67,13 @@ func RecipeVersionComplete(recipeName string) { } // ServerNameComplete completes server names. -func ServerNameComplete(c *cli.Context) { +func ServerNameComplete(ctx context.Context, cmd *cli.Command) { files, err := app.LoadAppFiles("") if err != nil { log.Fatal(err) } - if c.NArg() > 0 { + if cmd.NArg() > 0 { return } @@ -82,8 +83,8 @@ func ServerNameComplete(c *cli.Context) { } // SubcommandComplete completes sub-commands. -func SubcommandComplete(c *cli.Context) { - if c.NArg() > 0 { +func SubcommandComplete(ctx context.Context, cmd *cli.Command) { + if cmd.NArg() > 0 { return } diff --git a/scripts/autocomplete/bash b/scripts/autocomplete/bash index f0f62418..7120a0d2 100755 --- a/scripts/autocomplete/bash +++ b/scripts/autocomplete/bash @@ -2,17 +2,31 @@ : ${PROG:=$(basename ${BASH_SOURCE})} +# Macs have bash3 for which the bash-completion package doesn't include +# _init_completion. This is a minimal version of that function. +_cli_init_completion() { + COMPREPLY=() + _get_comp_words_by_ref "$@" cur prev words cword +} + _cli_bash_autocomplete() { if [[ "${COMP_WORDS[0]}" != "source" ]]; then - local cur opts base + local cur opts base words COMPREPLY=() cur="${COMP_WORDS[COMP_CWORD]}" - if [[ "$cur" == "-"* ]]; then - opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} ${cur} --generate-bash-completion ) + if declare -F _init_completion >/dev/null 2>&1; then + _init_completion -n "=:" || return else - opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} --generate-bash-completion ) + _cli_init_completion -n "=:" || return fi - COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) + words=("${words[@]:0:$cword}") + if [[ "$cur" == "-"* ]]; then + requestComp="${words[*]} ${cur} --generate-shell-completion" + else + requestComp="${words[*]} --generate-shell-completion" + fi + opts=$(eval "${requestComp}" 2>/dev/null) + COMPREPLY=($(compgen -W "${opts}" -- ${cur})) return 0 fi } diff --git a/scripts/autocomplete/fish b/scripts/autocomplete/fish index 54427187..c40fae9d 100644 --- a/scripts/autocomplete/fish +++ b/scripts/autocomplete/fish @@ -1,5 +1,5 @@ function complete_abra_args - set -l cmd (commandline -poc) --generate-bash-completion + set -l cmd (commandline -poc) --generate-shell-completion $cmd end complete -c abra -f -n "not __fish_seen_subcommand_from -h --help -v --version complete_abra_args" -a "(complete_abra_args)" diff --git a/scripts/autocomplete/powershell b/scripts/autocomplete/powershell index cfffbf4f..6e0c422e 100644 --- a/scripts/autocomplete/powershell +++ b/scripts/autocomplete/powershell @@ -2,7 +2,7 @@ $fn = $($MyInvocation.MyCommand.Name) $name = $fn -replace "(.*)\.ps1$", '$1' Register-ArgumentCompleter -Native -CommandName $name -ScriptBlock { param($commandName, $wordToComplete, $cursorPosition) - $other = "$wordToComplete --generate-bash-completion" + $other = "$wordToComplete --generate-shell-completion" Invoke-Expression $other | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) } diff --git a/scripts/autocomplete/zsh b/scripts/autocomplete/zsh index cf39c888..57f19d37 100644 --- a/scripts/autocomplete/zsh +++ b/scripts/autocomplete/zsh @@ -1,23 +1,26 @@ -#compdef $PROG +#compdef abra +compdef _abra abra -_cli_zsh_autocomplete() { +# https://github.com/urfave/cli/blob/main/autocomplete/zsh_autocomplete - local -a opts - local cur - cur=${words[-1]} - if [[ "$cur" == "-"* ]]; then - opts=("${(@f)$(_CLI_ZSH_AUTOCOMPLETE_HACK=1 ${words[@]:0:#words[@]-1} ${cur} --generate-bash-completion)}") - else - opts=("${(@f)$(_CLI_ZSH_AUTOCOMPLETE_HACK=1 ${words[@]:0:#words[@]-1} --generate-bash-completion)}") - fi +_abra() { + local -a opts + local cur + cur=${words[-1]} + if [[ "$cur" == "-"* ]]; then + opts=("${(@f)$(${words[@]:0:#words[@]-1} ${cur} --generate-shell-completion)}") + else + opts=("${(@f)$(${words[@]:0:#words[@]-1} --generate-shell-completion)}") + fi - if [[ "${opts[1]}" != "" ]]; then - _describe 'values' opts - else - _files - fi - - return + if [[ "${opts[1]}" != "" ]]; then + _describe 'values' opts + else + _files + fi } -compdef _cli_zsh_autocomplete $PROG +# don't run the completion function when being source-ed or eval-ed +if [ "$funcstack[1]" = "_abra" ]; then + _abra +fi diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go index bf71684f..5599082a 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/api.go b/vendor/github.com/Azure/go-ansiterm/winterm/api.go index 2f297601..6055e33b 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/api.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/api.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go b/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go index 644d8b2b..cbec8f72 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go index 6b4b8a1e..3ee06ea7 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go index 1298544a..244b5fa2 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go b/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go index 03ab280c..2d27fa1d 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go b/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go index 3535349f..afa7635d 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go b/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go index 1e19ea0c..2d40fb75 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package winterm diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go index 0ea619de..2d7b0cf3 100644 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go +++ b/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go @@ -259,7 +259,7 @@ func (e *Entity) EncryptPrivateKeys(passphrase []byte, config *packet.Config) er var keysToEncrypt []*packet.PrivateKey // Add entity private key to encrypt. if e.PrivateKey != nil && !e.PrivateKey.Dummy() && !e.PrivateKey.Encrypted { - keysToEncrypt = append(keysToEncrypt, e.PrivateKey) + keysToEncrypt = append(keysToEncrypt, e.PrivateKey) } // Add subkeys to encrypt. @@ -284,7 +284,7 @@ func (e *Entity) DecryptPrivateKeys(passphrase []byte) error { // Add subkeys to decrypt. for _, sub := range e.Subkeys { if sub.PrivateKey != nil && !sub.PrivateKey.Dummy() && sub.PrivateKey.Encrypted { - keysToDecrypt = append(keysToDecrypt, sub.PrivateKey) + keysToDecrypt = append(keysToDecrypt, sub.PrivateKey) } } return packet.DecryptPrivateKeys(keysToDecrypt, passphrase) diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/private_key.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/private_key.go index d42f1bb7..2fc43864 100644 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/private_key.go +++ b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/private_key.go @@ -458,7 +458,7 @@ func (pk *PrivateKey) Decrypt(passphrase []byte) error { } // DecryptPrivateKeys decrypts all encrypted keys with the given config and passphrase. -// Avoids recomputation of similar s2k key derivations. +// Avoids recomputation of similar s2k key derivations. func DecryptPrivateKeys(keys []*PrivateKey, passphrase []byte) error { // Create a cache to avoid recomputation of key derviations for the same passphrase. s2kCache := &s2k.Cache{} @@ -485,7 +485,7 @@ func (pk *PrivateKey) encrypt(key []byte, params *s2k.Params, cipherFunction Cip if len(key) != cipherFunction.KeySize() { return errors.InvalidArgumentError("supplied encryption key has the wrong size") } - + priv := bytes.NewBuffer(nil) err := pk.serializePrivateKey(priv) if err != nil { @@ -497,7 +497,7 @@ func (pk *PrivateKey) encrypt(key []byte, params *s2k.Params, cipherFunction Cip pk.s2k, err = pk.s2kParams.Function() if err != nil { return err - } + } privateKeyBytes := priv.Bytes() pk.sha1Checksum = true @@ -581,7 +581,7 @@ func (pk *PrivateKey) Encrypt(passphrase []byte) error { S2KMode: s2k.IteratedSaltedS2K, S2KCount: 65536, Hash: crypto.SHA256, - }, + } , DefaultCipher: CipherAES256, } return pk.EncryptWithConfig(passphrase, config) diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/s2k/s2k.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/s2k/s2k.go index e7189b19..a4369596 100644 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/s2k/s2k.go +++ b/vendor/github.com/ProtonMail/go-crypto/openpgp/s2k/s2k.go @@ -87,10 +87,10 @@ func decodeCount(c uint8) int { // encodeMemory converts the Argon2 "memory" in the range parallelism*8 to // 2**31, inclusive, to an encoded memory. The return value is the // octet that is actually stored in the GPG file. encodeMemory panics -// if is not in the above range +// if is not in the above range // See OpenPGP crypto refresh Section 3.7.1.4. func encodeMemory(memory uint32, parallelism uint8) uint8 { - if memory < (8*uint32(parallelism)) || memory > uint32(2147483648) { + if memory < (8 * uint32(parallelism)) || memory > uint32(2147483648) { panic("Memory argument memory is outside the required range") } @@ -199,8 +199,8 @@ func Generate(rand io.Reader, c *Config) (*Params, error) { } params = &Params{ - mode: SaltedS2K, - hashId: hashId, + mode: SaltedS2K, + hashId: hashId, } } else { // Enforce IteratedSaltedS2K method otherwise hashId, ok := algorithm.HashToHashId(c.hash()) @@ -211,7 +211,7 @@ func Generate(rand io.Reader, c *Config) (*Params, error) { c.S2KMode = IteratedSaltedS2K } params = &Params{ - mode: IteratedSaltedS2K, + mode: IteratedSaltedS2K, hashId: hashId, countByte: c.EncodedCount(), } @@ -306,12 +306,9 @@ func (params *Params) Dummy() bool { func (params *Params) salt() []byte { switch params.mode { - case SaltedS2K, IteratedSaltedS2K: - return params.saltBytes[:8] - case Argon2S2K: - return params.saltBytes[:Argon2SaltSize] - default: - return nil + case SaltedS2K, IteratedSaltedS2K: return params.saltBytes[:8] + case Argon2S2K: return params.saltBytes[:Argon2SaltSize] + default: return nil } } diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/s2k/s2k_cache.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/s2k/s2k_cache.go index 616e0d12..25a4442d 100644 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/s2k/s2k_cache.go +++ b/vendor/github.com/ProtonMail/go-crypto/openpgp/s2k/s2k_cache.go @@ -5,7 +5,7 @@ package s2k // the same parameters. type Cache map[Params][]byte -// GetOrComputeDerivedKey tries to retrieve the key +// GetOrComputeDerivedKey tries to retrieve the key // for the given s2k parameters from the cache. // If there is no hit, it derives the key with the s2k function from the passphrase, // updates the cache, and returns the key. diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/s2k/s2k_config.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/s2k/s2k_config.go index 1a6b7f14..b40be522 100644 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/s2k/s2k_config.go +++ b/vendor/github.com/ProtonMail/go-crypto/openpgp/s2k/s2k_config.go @@ -50,9 +50,9 @@ type Config struct { type Argon2Config struct { NumberOfPasses uint8 DegreeOfParallelism uint8 - // The memory parameter for Argon2 specifies desired memory usage in kibibytes. + // The memory parameter for Argon2 specifies desired memory usage in kibibytes. // For example memory=64*1024 sets the memory cost to ~64 MB. - Memory uint32 + Memory uint32 } func (c *Config) Mode() Mode { @@ -115,7 +115,7 @@ func (c *Argon2Config) EncodedMemory() uint8 { } memory := c.Memory - lowerBound := uint32(c.Parallelism()) * 8 + lowerBound := uint32(c.Parallelism())*8 upperBound := uint32(2147483648) switch { diff --git a/vendor/github.com/beorn7/perks/quantile/stream.go b/vendor/github.com/beorn7/perks/quantile/stream.go index 59362543..d7d14f8e 100644 --- a/vendor/github.com/beorn7/perks/quantile/stream.go +++ b/vendor/github.com/beorn7/perks/quantile/stream.go @@ -9,7 +9,7 @@ // // For more detailed information about the algorithm used, see: // -// # Effective Computation of Biased Quantiles over Data Streams +// Effective Computation of Biased Quantiles over Data Streams // // http://www.cs.rutgers.edu/~muthu/bquant.pdf package quantile diff --git a/vendor/github.com/cenkalti/backoff/v4/exponential.go b/vendor/github.com/cenkalti/backoff/v4/exponential.go index c022296a..aac99f19 100644 --- a/vendor/github.com/cenkalti/backoff/v4/exponential.go +++ b/vendor/github.com/cenkalti/backoff/v4/exponential.go @@ -11,17 +11,17 @@ period for each retry attempt using a randomization function that grows exponent NextBackOff() is calculated using the following formula: - randomized interval = - RetryInterval * (random value in range [1 - RandomizationFactor, 1 + RandomizationFactor]) + randomized interval = + RetryInterval * (random value in range [1 - RandomizationFactor, 1 + RandomizationFactor]) In other words NextBackOff() will range between the randomization factor percentage below and above the retry interval. For example, given the following parameters: - RetryInterval = 2 - RandomizationFactor = 0.5 - Multiplier = 2 + RetryInterval = 2 + RandomizationFactor = 0.5 + Multiplier = 2 the actual backoff period used in the next retry attempt will range between 1 and 3 seconds, multiplied by the exponential, that is, between 2 and 6 seconds. @@ -36,18 +36,18 @@ The elapsed time can be reset by calling Reset(). Example: Given the following default arguments, for 10 tries the sequence will be, and assuming we go over the MaxElapsedTime on the 10th try: - Request # RetryInterval (seconds) Randomized Interval (seconds) + Request # RetryInterval (seconds) Randomized Interval (seconds) - 1 0.5 [0.25, 0.75] - 2 0.75 [0.375, 1.125] - 3 1.125 [0.562, 1.687] - 4 1.687 [0.8435, 2.53] - 5 2.53 [1.265, 3.795] - 6 3.795 [1.897, 5.692] - 7 5.692 [2.846, 8.538] - 8 8.538 [4.269, 12.807] - 9 12.807 [6.403, 19.210] - 10 19.210 backoff.Stop + 1 0.5 [0.25, 0.75] + 2 0.75 [0.375, 1.125] + 3 1.125 [0.562, 1.687] + 4 1.687 [0.8435, 2.53] + 5 2.53 [1.265, 3.795] + 6 3.795 [1.897, 5.692] + 7 5.692 [2.846, 8.538] + 8 8.538 [4.269, 12.807] + 9 12.807 [6.403, 19.210] + 10 19.210 backoff.Stop Note: Implementation is not thread-safe. */ @@ -167,8 +167,7 @@ func (b *ExponentialBackOff) Reset() { } // NextBackOff calculates the next backoff interval using the formula: -// -// Randomized interval = RetryInterval * (1 ± RandomizationFactor) +// Randomized interval = RetryInterval * (1 ± RandomizationFactor) func (b *ExponentialBackOff) NextBackOff() time.Duration { // Make sure we have not gone over the maximum elapsed time. elapsed := b.GetElapsedTime() @@ -201,8 +200,7 @@ func (b *ExponentialBackOff) incrementCurrentInterval() { } // Returns a random value from the following interval: -// -// [currentInterval - randomizationFactor * currentInterval, currentInterval + randomizationFactor * currentInterval]. +// [currentInterval - randomizationFactor * currentInterval, currentInterval + randomizationFactor * currentInterval]. func getRandomValueFromInterval(randomizationFactor, random float64, currentInterval time.Duration) time.Duration { if randomizationFactor == 0 { return currentInterval // make sure no randomness is used when randomizationFactor is 0. diff --git a/vendor/github.com/containers/image/docker/reference/reference.go b/vendor/github.com/containers/image/docker/reference/reference.go index b7cd00b0..8c0c23b2 100644 --- a/vendor/github.com/containers/image/docker/reference/reference.go +++ b/vendor/github.com/containers/image/docker/reference/reference.go @@ -3,13 +3,13 @@ // // Grammar // -// reference := name [ ":" tag ] [ "@" digest ] +// reference := name [ ":" tag ] [ "@" digest ] // name := [domain '/'] path-component ['/' path-component]* // domain := domain-component ['.' domain-component]* [':' port-number] // domain-component := /([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])/ // port-number := /[0-9]+/ // path-component := alpha-numeric [separator alpha-numeric]* -// alpha-numeric := /[a-z0-9]+/ +// alpha-numeric := /[a-z0-9]+/ // separator := /[_.]|__|[-]*/ // // tag := /[\w][\w.-]{0,127}/ diff --git a/vendor/github.com/containers/image/pkg/docker/config/config_unsupported.go b/vendor/github.com/containers/image/pkg/docker/config/config_unsupported.go index a7cd2485..1c1a0251 100644 --- a/vendor/github.com/containers/image/pkg/docker/config/config_unsupported.go +++ b/vendor/github.com/containers/image/pkg/docker/config/config_unsupported.go @@ -1,4 +1,3 @@ -//go:build !linux && (!386 || !amd64) // +build !linux // +build !386 !amd64 diff --git a/vendor/github.com/containers/image/pkg/keyctl/key.go b/vendor/github.com/containers/image/pkg/keyctl/key.go index c808e3cd..e4396a9d 100644 --- a/vendor/github.com/containers/image/pkg/keyctl/key.go +++ b/vendor/github.com/containers/image/pkg/keyctl/key.go @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build linux // +build linux package keyctl diff --git a/vendor/github.com/containers/image/pkg/keyctl/keyring.go b/vendor/github.com/containers/image/pkg/keyctl/keyring.go index 6935a60d..6e029c92 100644 --- a/vendor/github.com/containers/image/pkg/keyctl/keyring.go +++ b/vendor/github.com/containers/image/pkg/keyctl/keyring.go @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build linux // +build linux // Package keyctl is a Go interface to linux kernel keyrings (keyctl interface) diff --git a/vendor/github.com/containers/image/pkg/keyctl/perm.go b/vendor/github.com/containers/image/pkg/keyctl/perm.go index 5f4d2157..ae969714 100644 --- a/vendor/github.com/containers/image/pkg/keyctl/perm.go +++ b/vendor/github.com/containers/image/pkg/keyctl/perm.go @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build linux // +build linux package keyctl diff --git a/vendor/github.com/containers/image/pkg/keyctl/sys_linux.go b/vendor/github.com/containers/image/pkg/keyctl/sys_linux.go index f61666e4..196c8276 100644 --- a/vendor/github.com/containers/image/pkg/keyctl/sys_linux.go +++ b/vendor/github.com/containers/image/pkg/keyctl/sys_linux.go @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build linux // +build linux package keyctl diff --git a/vendor/github.com/containers/image/types/types.go b/vendor/github.com/containers/image/types/types.go index e105b4e1..08b4241e 100644 --- a/vendor/github.com/containers/image/types/types.go +++ b/vendor/github.com/containers/image/types/types.go @@ -131,25 +131,24 @@ type BICReplacementCandidate struct { // BlobInfoCache records data useful for reusing blobs, or substituing equivalent ones, to avoid unnecessary blob copies. // // It records two kinds of data: +// - Sets of corresponding digest vs. uncompressed digest ("DiffID") pairs: +// One of the two digests is known to be uncompressed, and a single uncompressed digest may correspond to more than one compressed digest. +// This allows matching compressed layer blobs to existing local uncompressed layers (to avoid unnecessary download and decompresssion), +// or uncompressed layer blobs to existing remote compressed layers (to avoid unnecessary compression and upload)/ // -// - Sets of corresponding digest vs. uncompressed digest ("DiffID") pairs: -// One of the two digests is known to be uncompressed, and a single uncompressed digest may correspond to more than one compressed digest. -// This allows matching compressed layer blobs to existing local uncompressed layers (to avoid unnecessary download and decompresssion), -// or uncompressed layer blobs to existing remote compressed layers (to avoid unnecessary compression and upload)/ +// It is allowed to record an (uncompressed digest, the same uncompressed digest) correspondence, to express that the digest is known +// to be uncompressed (i.e. that a conversion from schema1 does not have to decompress the blob to compute a DiffID value). // -// It is allowed to record an (uncompressed digest, the same uncompressed digest) correspondence, to express that the digest is known -// to be uncompressed (i.e. that a conversion from schema1 does not have to decompress the blob to compute a DiffID value). +// This mapping is primarily maintained in generic copy.Image code, but transports may want to contribute more data points if they independently +// compress/decompress blobs for their own purposes. // -// This mapping is primarily maintained in generic copy.Image code, but transports may want to contribute more data points if they independently -// compress/decompress blobs for their own purposes. +// - Known blob locations, managed by individual transports: +// The transports call RecordKnownLocation when encountering a blob that could possibly be reused (typically in GetBlob/PutBlob/TryReusingBlob), +// recording transport-specific information that allows the transport to reuse the blob in the future; +// then, TryReusingBlob implementations can call CandidateLocations to look up previously recorded blob locations that could be reused. // -// - Known blob locations, managed by individual transports: -// The transports call RecordKnownLocation when encountering a blob that could possibly be reused (typically in GetBlob/PutBlob/TryReusingBlob), -// recording transport-specific information that allows the transport to reuse the blob in the future; -// then, TryReusingBlob implementations can call CandidateLocations to look up previously recorded blob locations that could be reused. -// -// Each transport defines its own “scopes” within which blob reuse is possible (e.g. in, the docker/distribution case, blobs -// can be directly reused within a registry, or mounted across registries within a registry server.) +// Each transport defines its own “scopes” within which blob reuse is possible (e.g. in, the docker/distribution case, blobs +// can be directly reused within a registry, or mounted across registries within a registry server.) // // None of the methods return an error indication: errors when neither reading from, nor writing to, the cache, should be fatal; // users of the cahce should just fall back to copying the blobs the usual way. diff --git a/vendor/github.com/cpuguy83/go-md2man/v2/LICENSE.md b/vendor/github.com/cpuguy83/go-md2man/v2/LICENSE.md deleted file mode 100644 index 1cade6ce..00000000 --- a/vendor/github.com/cpuguy83/go-md2man/v2/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Brian Goff - -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/cpuguy83/go-md2man/v2/md2man/md2man.go b/vendor/github.com/cpuguy83/go-md2man/v2/md2man/md2man.go deleted file mode 100644 index 42bf32aa..00000000 --- a/vendor/github.com/cpuguy83/go-md2man/v2/md2man/md2man.go +++ /dev/null @@ -1,16 +0,0 @@ -package md2man - -import ( - "github.com/russross/blackfriday/v2" -) - -// Render converts a markdown document into a roff formatted document. -func Render(doc []byte) []byte { - renderer := NewRoffRenderer() - - return blackfriday.Run(doc, - []blackfriday.Option{ - blackfriday.WithRenderer(renderer), - blackfriday.WithExtensions(renderer.GetExtensions()), - }...) -} diff --git a/vendor/github.com/cpuguy83/go-md2man/v2/md2man/roff.go b/vendor/github.com/cpuguy83/go-md2man/v2/md2man/roff.go deleted file mode 100644 index 8a290f19..00000000 --- a/vendor/github.com/cpuguy83/go-md2man/v2/md2man/roff.go +++ /dev/null @@ -1,382 +0,0 @@ -package md2man - -import ( - "bufio" - "bytes" - "fmt" - "io" - "os" - "strings" - - "github.com/russross/blackfriday/v2" -) - -// roffRenderer implements the blackfriday.Renderer interface for creating -// roff format (manpages) from markdown text -type roffRenderer struct { - extensions blackfriday.Extensions - listCounters []int - firstHeader bool - firstDD bool - listDepth int -} - -const ( - titleHeader = ".TH " - topLevelHeader = "\n\n.SH " - secondLevelHdr = "\n.SH " - otherHeader = "\n.SS " - crTag = "\n" - emphTag = "\\fI" - emphCloseTag = "\\fP" - strongTag = "\\fB" - strongCloseTag = "\\fP" - breakTag = "\n.br\n" - paraTag = "\n.PP\n" - hruleTag = "\n.ti 0\n\\l'\\n(.lu'\n" - linkTag = "\n\\[la]" - linkCloseTag = "\\[ra]" - codespanTag = "\\fB" - codespanCloseTag = "\\fR" - codeTag = "\n.EX\n" - codeCloseTag = ".EE\n" // Do not prepend a newline character since code blocks, by definition, include a newline already (or at least as how blackfriday gives us on). - quoteTag = "\n.PP\n.RS\n" - quoteCloseTag = "\n.RE\n" - listTag = "\n.RS\n" - listCloseTag = "\n.RE\n" - dtTag = "\n.TP\n" - dd2Tag = "\n" - tableStart = "\n.TS\nallbox;\n" - tableEnd = ".TE\n" - tableCellStart = "T{\n" - tableCellEnd = "\nT}\n" - tablePreprocessor = `'\" t` -) - -// NewRoffRenderer creates a new blackfriday Renderer for generating roff documents -// from markdown -func NewRoffRenderer() *roffRenderer { // nolint: golint - var extensions blackfriday.Extensions - - extensions |= blackfriday.NoIntraEmphasis - extensions |= blackfriday.Tables - extensions |= blackfriday.FencedCode - extensions |= blackfriday.SpaceHeadings - extensions |= blackfriday.Footnotes - extensions |= blackfriday.Titleblock - extensions |= blackfriday.DefinitionLists - return &roffRenderer{ - extensions: extensions, - } -} - -// GetExtensions returns the list of extensions used by this renderer implementation -func (r *roffRenderer) GetExtensions() blackfriday.Extensions { - return r.extensions -} - -// RenderHeader handles outputting the header at document start -func (r *roffRenderer) RenderHeader(w io.Writer, ast *blackfriday.Node) { - // We need to walk the tree to check if there are any tables. - // If there are, we need to enable the roff table preprocessor. - ast.Walk(func(node *blackfriday.Node, entering bool) blackfriday.WalkStatus { - if node.Type == blackfriday.Table { - out(w, tablePreprocessor+"\n") - return blackfriday.Terminate - } - return blackfriday.GoToNext - }) - - // disable hyphenation - out(w, ".nh\n") -} - -// RenderFooter handles outputting the footer at the document end; the roff -// renderer has no footer information -func (r *roffRenderer) RenderFooter(w io.Writer, ast *blackfriday.Node) { -} - -// RenderNode is called for each node in a markdown document; based on the node -// type the equivalent roff output is sent to the writer -func (r *roffRenderer) RenderNode(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus { - walkAction := blackfriday.GoToNext - - switch node.Type { - case blackfriday.Text: - escapeSpecialChars(w, node.Literal) - case blackfriday.Softbreak: - out(w, crTag) - case blackfriday.Hardbreak: - out(w, breakTag) - case blackfriday.Emph: - if entering { - out(w, emphTag) - } else { - out(w, emphCloseTag) - } - case blackfriday.Strong: - if entering { - out(w, strongTag) - } else { - out(w, strongCloseTag) - } - case blackfriday.Link: - // Don't render the link text for automatic links, because this - // will only duplicate the URL in the roff output. - // See https://daringfireball.net/projects/markdown/syntax#autolink - if !bytes.Equal(node.LinkData.Destination, node.FirstChild.Literal) { - out(w, string(node.FirstChild.Literal)) - } - // Hyphens in a link must be escaped to avoid word-wrap in the rendered man page. - escapedLink := strings.ReplaceAll(string(node.LinkData.Destination), "-", "\\-") - out(w, linkTag+escapedLink+linkCloseTag) - walkAction = blackfriday.SkipChildren - case blackfriday.Image: - // ignore images - walkAction = blackfriday.SkipChildren - case blackfriday.Code: - out(w, codespanTag) - escapeSpecialChars(w, node.Literal) - out(w, codespanCloseTag) - case blackfriday.Document: - break - case blackfriday.Paragraph: - // roff .PP markers break lists - if r.listDepth > 0 { - return blackfriday.GoToNext - } - if entering { - out(w, paraTag) - } else { - out(w, crTag) - } - case blackfriday.BlockQuote: - if entering { - out(w, quoteTag) - } else { - out(w, quoteCloseTag) - } - case blackfriday.Heading: - r.handleHeading(w, node, entering) - case blackfriday.HorizontalRule: - out(w, hruleTag) - case blackfriday.List: - r.handleList(w, node, entering) - case blackfriday.Item: - r.handleItem(w, node, entering) - case blackfriday.CodeBlock: - out(w, codeTag) - escapeSpecialChars(w, node.Literal) - out(w, codeCloseTag) - case blackfriday.Table: - r.handleTable(w, node, entering) - case blackfriday.TableHead: - case blackfriday.TableBody: - case blackfriday.TableRow: - // no action as cell entries do all the nroff formatting - return blackfriday.GoToNext - case blackfriday.TableCell: - r.handleTableCell(w, node, entering) - case blackfriday.HTMLSpan: - // ignore other HTML tags - case blackfriday.HTMLBlock: - if bytes.HasPrefix(node.Literal, []byte("|" - processingInstruction = "[<][?].*?[?][>]" - singleQuotedValue = "'[^']*'" - tagName = "[A-Za-z][A-Za-z0-9-]*" - unquotedValue = "[^\"'=<>`\\x00-\\x20]+" -) - -// HTMLRendererParameters is a collection of supplementary parameters tweaking -// the behavior of various parts of HTML renderer. -type HTMLRendererParameters struct { - // Prepend this text to each relative URL. - AbsolutePrefix string - // Add this text to each footnote anchor, to ensure uniqueness. - FootnoteAnchorPrefix string - // Show this text inside the tag for a footnote return link, if the - // HTML_FOOTNOTE_RETURN_LINKS flag is enabled. If blank, the string - // [return] is used. - FootnoteReturnLinkContents string - // If set, add this text to the front of each Heading ID, to ensure - // uniqueness. - HeadingIDPrefix string - // If set, add this text to the back of each Heading ID, to ensure uniqueness. - HeadingIDSuffix string - // Increase heading levels: if the offset is 1,

becomes

etc. - // Negative offset is also valid. - // Resulting levels are clipped between 1 and 6. - HeadingLevelOffset int - - Title string // Document title (used if CompletePage is set) - CSS string // Optional CSS file URL (used if CompletePage is set) - Icon string // Optional icon file URL (used if CompletePage is set) - - Flags HTMLFlags // Flags allow customizing this renderer's behavior -} - -// HTMLRenderer is a type that implements the Renderer interface for HTML output. -// -// Do not create this directly, instead use the NewHTMLRenderer function. -type HTMLRenderer struct { - HTMLRendererParameters - - closeTag string // how to end singleton tags: either " />" or ">" - - // Track heading IDs to prevent ID collision in a single generation. - headingIDs map[string]int - - lastOutputLen int - disableTags int - - sr *SPRenderer -} - -const ( - xhtmlClose = " />" - htmlClose = ">" -) - -// NewHTMLRenderer creates and configures an HTMLRenderer object, which -// satisfies the Renderer interface. -func NewHTMLRenderer(params HTMLRendererParameters) *HTMLRenderer { - // configure the rendering engine - closeTag := htmlClose - if params.Flags&UseXHTML != 0 { - closeTag = xhtmlClose - } - - if params.FootnoteReturnLinkContents == "" { - // U+FE0E is VARIATION SELECTOR-15. - // It suppresses automatic emoji presentation of the preceding - // U+21A9 LEFTWARDS ARROW WITH HOOK on iOS and iPadOS. - params.FootnoteReturnLinkContents = "↩\ufe0e" - } - - return &HTMLRenderer{ - HTMLRendererParameters: params, - - closeTag: closeTag, - headingIDs: make(map[string]int), - - sr: NewSmartypantsRenderer(params.Flags), - } -} - -func isHTMLTag(tag []byte, tagname string) bool { - found, _ := findHTMLTagPos(tag, tagname) - return found -} - -// Look for a character, but ignore it when it's in any kind of quotes, it -// might be JavaScript -func skipUntilCharIgnoreQuotes(html []byte, start int, char byte) int { - inSingleQuote := false - inDoubleQuote := false - inGraveQuote := false - i := start - for i < len(html) { - switch { - case html[i] == char && !inSingleQuote && !inDoubleQuote && !inGraveQuote: - return i - case html[i] == '\'': - inSingleQuote = !inSingleQuote - case html[i] == '"': - inDoubleQuote = !inDoubleQuote - case html[i] == '`': - inGraveQuote = !inGraveQuote - } - i++ - } - return start -} - -func findHTMLTagPos(tag []byte, tagname string) (bool, int) { - i := 0 - if i < len(tag) && tag[0] != '<' { - return false, -1 - } - i++ - i = skipSpace(tag, i) - - if i < len(tag) && tag[i] == '/' { - i++ - } - - i = skipSpace(tag, i) - j := 0 - for ; i < len(tag); i, j = i+1, j+1 { - if j >= len(tagname) { - break - } - - if strings.ToLower(string(tag[i]))[0] != tagname[j] { - return false, -1 - } - } - - if i == len(tag) { - return false, -1 - } - - rightAngle := skipUntilCharIgnoreQuotes(tag, i, '>') - if rightAngle >= i { - return true, rightAngle - } - - return false, -1 -} - -func skipSpace(tag []byte, i int) int { - for i < len(tag) && isspace(tag[i]) { - i++ - } - return i -} - -func isRelativeLink(link []byte) (yes bool) { - // a tag begin with '#' - if link[0] == '#' { - return true - } - - // link begin with '/' but not '//', the second maybe a protocol relative link - if len(link) >= 2 && link[0] == '/' && link[1] != '/' { - return true - } - - // only the root '/' - if len(link) == 1 && link[0] == '/' { - return true - } - - // current directory : begin with "./" - if bytes.HasPrefix(link, []byte("./")) { - return true - } - - // parent directory : begin with "../" - if bytes.HasPrefix(link, []byte("../")) { - return true - } - - return false -} - -func (r *HTMLRenderer) ensureUniqueHeadingID(id string) string { - for count, found := r.headingIDs[id]; found; count, found = r.headingIDs[id] { - tmp := fmt.Sprintf("%s-%d", id, count+1) - - if _, tmpFound := r.headingIDs[tmp]; !tmpFound { - r.headingIDs[id] = count + 1 - id = tmp - } else { - id = id + "-1" - } - } - - if _, found := r.headingIDs[id]; !found { - r.headingIDs[id] = 0 - } - - return id -} - -func (r *HTMLRenderer) addAbsPrefix(link []byte) []byte { - if r.AbsolutePrefix != "" && isRelativeLink(link) && link[0] != '.' { - newDest := r.AbsolutePrefix - if link[0] != '/' { - newDest += "/" - } - newDest += string(link) - return []byte(newDest) - } - return link -} - -func appendLinkAttrs(attrs []string, flags HTMLFlags, link []byte) []string { - if isRelativeLink(link) { - return attrs - } - val := []string{} - if flags&NofollowLinks != 0 { - val = append(val, "nofollow") - } - if flags&NoreferrerLinks != 0 { - val = append(val, "noreferrer") - } - if flags&NoopenerLinks != 0 { - val = append(val, "noopener") - } - if flags&HrefTargetBlank != 0 { - attrs = append(attrs, "target=\"_blank\"") - } - if len(val) == 0 { - return attrs - } - attr := fmt.Sprintf("rel=%q", strings.Join(val, " ")) - return append(attrs, attr) -} - -func isMailto(link []byte) bool { - return bytes.HasPrefix(link, []byte("mailto:")) -} - -func needSkipLink(flags HTMLFlags, dest []byte) bool { - if flags&SkipLinks != 0 { - return true - } - return flags&Safelink != 0 && !isSafeLink(dest) && !isMailto(dest) -} - -func isSmartypantable(node *Node) bool { - pt := node.Parent.Type - return pt != Link && pt != CodeBlock && pt != Code -} - -func appendLanguageAttr(attrs []string, info []byte) []string { - if len(info) == 0 { - return attrs - } - endOfLang := bytes.IndexAny(info, "\t ") - if endOfLang < 0 { - endOfLang = len(info) - } - return append(attrs, fmt.Sprintf("class=\"language-%s\"", info[:endOfLang])) -} - -func (r *HTMLRenderer) tag(w io.Writer, name []byte, attrs []string) { - w.Write(name) - if len(attrs) > 0 { - w.Write(spaceBytes) - w.Write([]byte(strings.Join(attrs, " "))) - } - w.Write(gtBytes) - r.lastOutputLen = 1 -} - -func footnoteRef(prefix string, node *Node) []byte { - urlFrag := prefix + string(slugify(node.Destination)) - anchor := fmt.Sprintf(`%d`, urlFrag, node.NoteID) - return []byte(fmt.Sprintf(`%s`, urlFrag, anchor)) -} - -func footnoteItem(prefix string, slug []byte) []byte { - return []byte(fmt.Sprintf(`
  • `, prefix, slug)) -} - -func footnoteReturnLink(prefix, returnLink string, slug []byte) []byte { - const format = ` %s` - return []byte(fmt.Sprintf(format, prefix, slug, returnLink)) -} - -func itemOpenCR(node *Node) bool { - if node.Prev == nil { - return false - } - ld := node.Parent.ListData - return !ld.Tight && ld.ListFlags&ListTypeDefinition == 0 -} - -func skipParagraphTags(node *Node) bool { - grandparent := node.Parent.Parent - if grandparent == nil || grandparent.Type != List { - return false - } - tightOrTerm := grandparent.Tight || node.Parent.ListFlags&ListTypeTerm != 0 - return grandparent.Type == List && tightOrTerm -} - -func cellAlignment(align CellAlignFlags) string { - switch align { - case TableAlignmentLeft: - return "left" - case TableAlignmentRight: - return "right" - case TableAlignmentCenter: - return "center" - default: - return "" - } -} - -func (r *HTMLRenderer) out(w io.Writer, text []byte) { - if r.disableTags > 0 { - w.Write(htmlTagRe.ReplaceAll(text, []byte{})) - } else { - w.Write(text) - } - r.lastOutputLen = len(text) -} - -func (r *HTMLRenderer) cr(w io.Writer) { - if r.lastOutputLen > 0 { - r.out(w, nlBytes) - } -} - -var ( - nlBytes = []byte{'\n'} - gtBytes = []byte{'>'} - spaceBytes = []byte{' '} -) - -var ( - brTag = []byte("
    ") - brXHTMLTag = []byte("
    ") - emTag = []byte("") - emCloseTag = []byte("") - strongTag = []byte("") - strongCloseTag = []byte("") - delTag = []byte("") - delCloseTag = []byte("") - ttTag = []byte("") - ttCloseTag = []byte("") - aTag = []byte("") - preTag = []byte("
    ")
    -	preCloseTag        = []byte("
    ") - codeTag = []byte("") - codeCloseTag = []byte("") - pTag = []byte("

    ") - pCloseTag = []byte("

    ") - blockquoteTag = []byte("
    ") - blockquoteCloseTag = []byte("
    ") - hrTag = []byte("
    ") - hrXHTMLTag = []byte("
    ") - ulTag = []byte("
      ") - ulCloseTag = []byte("
    ") - olTag = []byte("
      ") - olCloseTag = []byte("
    ") - dlTag = []byte("
    ") - dlCloseTag = []byte("
    ") - liTag = []byte("
  • ") - liCloseTag = []byte("
  • ") - ddTag = []byte("
    ") - ddCloseTag = []byte("
    ") - dtTag = []byte("
    ") - dtCloseTag = []byte("
    ") - tableTag = []byte("") - tableCloseTag = []byte("
    ") - tdTag = []byte("") - thTag = []byte("") - theadTag = []byte("") - theadCloseTag = []byte("") - tbodyTag = []byte("") - tbodyCloseTag = []byte("") - trTag = []byte("") - trCloseTag = []byte("") - h1Tag = []byte("") - h2Tag = []byte("") - h3Tag = []byte("") - h4Tag = []byte("") - h5Tag = []byte("") - h6Tag = []byte("") - - footnotesDivBytes = []byte("\n
    \n\n") - footnotesCloseDivBytes = []byte("\n
    \n") -) - -func headingTagsFromLevel(level int) ([]byte, []byte) { - if level <= 1 { - return h1Tag, h1CloseTag - } - switch level { - case 2: - return h2Tag, h2CloseTag - case 3: - return h3Tag, h3CloseTag - case 4: - return h4Tag, h4CloseTag - case 5: - return h5Tag, h5CloseTag - } - return h6Tag, h6CloseTag -} - -func (r *HTMLRenderer) outHRTag(w io.Writer) { - if r.Flags&UseXHTML == 0 { - r.out(w, hrTag) - } else { - r.out(w, hrXHTMLTag) - } -} - -// RenderNode is a default renderer of a single node of a syntax tree. For -// block nodes it will be called twice: first time with entering=true, second -// time with entering=false, so that it could know when it's working on an open -// tag and when on close. It writes the result to w. -// -// The return value is a way to tell the calling walker to adjust its walk -// pattern: e.g. it can terminate the traversal by returning Terminate. Or it -// can ask the walker to skip a subtree of this node by returning SkipChildren. -// The typical behavior is to return GoToNext, which asks for the usual -// traversal to the next node. -func (r *HTMLRenderer) RenderNode(w io.Writer, node *Node, entering bool) WalkStatus { - attrs := []string{} - switch node.Type { - case Text: - if r.Flags&Smartypants != 0 { - var tmp bytes.Buffer - escapeHTML(&tmp, node.Literal) - r.sr.Process(w, tmp.Bytes()) - } else { - if node.Parent.Type == Link { - escLink(w, node.Literal) - } else { - escapeHTML(w, node.Literal) - } - } - case Softbreak: - r.cr(w) - // TODO: make it configurable via out(renderer.softbreak) - case Hardbreak: - if r.Flags&UseXHTML == 0 { - r.out(w, brTag) - } else { - r.out(w, brXHTMLTag) - } - r.cr(w) - case Emph: - if entering { - r.out(w, emTag) - } else { - r.out(w, emCloseTag) - } - case Strong: - if entering { - r.out(w, strongTag) - } else { - r.out(w, strongCloseTag) - } - case Del: - if entering { - r.out(w, delTag) - } else { - r.out(w, delCloseTag) - } - case HTMLSpan: - if r.Flags&SkipHTML != 0 { - break - } - r.out(w, node.Literal) - case Link: - // mark it but don't link it if it is not a safe link: no smartypants - dest := node.LinkData.Destination - if needSkipLink(r.Flags, dest) { - if entering { - r.out(w, ttTag) - } else { - r.out(w, ttCloseTag) - } - } else { - if entering { - dest = r.addAbsPrefix(dest) - var hrefBuf bytes.Buffer - hrefBuf.WriteString("href=\"") - escLink(&hrefBuf, dest) - hrefBuf.WriteByte('"') - attrs = append(attrs, hrefBuf.String()) - if node.NoteID != 0 { - r.out(w, footnoteRef(r.FootnoteAnchorPrefix, node)) - break - } - attrs = appendLinkAttrs(attrs, r.Flags, dest) - if len(node.LinkData.Title) > 0 { - var titleBuff bytes.Buffer - titleBuff.WriteString("title=\"") - escapeHTML(&titleBuff, node.LinkData.Title) - titleBuff.WriteByte('"') - attrs = append(attrs, titleBuff.String()) - } - r.tag(w, aTag, attrs) - } else { - if node.NoteID != 0 { - break - } - r.out(w, aCloseTag) - } - } - case Image: - if r.Flags&SkipImages != 0 { - return SkipChildren - } - if entering { - dest := node.LinkData.Destination - dest = r.addAbsPrefix(dest) - if r.disableTags == 0 { - //if options.safe && potentiallyUnsafe(dest) { - //out(w, ``)
-				//} else {
-				r.out(w, []byte(`<img src=`)) - } - } - case Code: - r.out(w, codeTag) - escapeAllHTML(w, node.Literal) - r.out(w, codeCloseTag) - case Document: - break - case Paragraph: - if skipParagraphTags(node) { - break - } - if entering { - // TODO: untangle this clusterfuck about when the newlines need - // to be added and when not. - if node.Prev != nil { - switch node.Prev.Type { - case HTMLBlock, List, Paragraph, Heading, CodeBlock, BlockQuote, HorizontalRule: - r.cr(w) - } - } - if node.Parent.Type == BlockQuote && node.Prev == nil { - r.cr(w) - } - r.out(w, pTag) - } else { - r.out(w, pCloseTag) - if !(node.Parent.Type == Item && node.Next == nil) { - r.cr(w) - } - } - case BlockQuote: - if entering { - r.cr(w) - r.out(w, blockquoteTag) - } else { - r.out(w, blockquoteCloseTag) - r.cr(w) - } - case HTMLBlock: - if r.Flags&SkipHTML != 0 { - break - } - r.cr(w) - r.out(w, node.Literal) - r.cr(w) - case Heading: - headingLevel := r.HTMLRendererParameters.HeadingLevelOffset + node.Level - openTag, closeTag := headingTagsFromLevel(headingLevel) - if entering { - if node.IsTitleblock { - attrs = append(attrs, `class="title"`) - } - if node.HeadingID != "" { - id := r.ensureUniqueHeadingID(node.HeadingID) - if r.HeadingIDPrefix != "" { - id = r.HeadingIDPrefix + id - } - if r.HeadingIDSuffix != "" { - id = id + r.HeadingIDSuffix - } - attrs = append(attrs, fmt.Sprintf(`id="%s"`, id)) - } - r.cr(w) - r.tag(w, openTag, attrs) - } else { - r.out(w, closeTag) - if !(node.Parent.Type == Item && node.Next == nil) { - r.cr(w) - } - } - case HorizontalRule: - r.cr(w) - r.outHRTag(w) - r.cr(w) - case List: - openTag := ulTag - closeTag := ulCloseTag - if node.ListFlags&ListTypeOrdered != 0 { - openTag = olTag - closeTag = olCloseTag - } - if node.ListFlags&ListTypeDefinition != 0 { - openTag = dlTag - closeTag = dlCloseTag - } - if entering { - if node.IsFootnotesList { - r.out(w, footnotesDivBytes) - r.outHRTag(w) - r.cr(w) - } - r.cr(w) - if node.Parent.Type == Item && node.Parent.Parent.Tight { - r.cr(w) - } - r.tag(w, openTag[:len(openTag)-1], attrs) - r.cr(w) - } else { - r.out(w, closeTag) - //cr(w) - //if node.parent.Type != Item { - // cr(w) - //} - if node.Parent.Type == Item && node.Next != nil { - r.cr(w) - } - if node.Parent.Type == Document || node.Parent.Type == BlockQuote { - r.cr(w) - } - if node.IsFootnotesList { - r.out(w, footnotesCloseDivBytes) - } - } - case Item: - openTag := liTag - closeTag := liCloseTag - if node.ListFlags&ListTypeDefinition != 0 { - openTag = ddTag - closeTag = ddCloseTag - } - if node.ListFlags&ListTypeTerm != 0 { - openTag = dtTag - closeTag = dtCloseTag - } - if entering { - if itemOpenCR(node) { - r.cr(w) - } - if node.ListData.RefLink != nil { - slug := slugify(node.ListData.RefLink) - r.out(w, footnoteItem(r.FootnoteAnchorPrefix, slug)) - break - } - r.out(w, openTag) - } else { - if node.ListData.RefLink != nil { - slug := slugify(node.ListData.RefLink) - if r.Flags&FootnoteReturnLinks != 0 { - r.out(w, footnoteReturnLink(r.FootnoteAnchorPrefix, r.FootnoteReturnLinkContents, slug)) - } - } - r.out(w, closeTag) - r.cr(w) - } - case CodeBlock: - attrs = appendLanguageAttr(attrs, node.Info) - r.cr(w) - r.out(w, preTag) - r.tag(w, codeTag[:len(codeTag)-1], attrs) - escapeAllHTML(w, node.Literal) - r.out(w, codeCloseTag) - r.out(w, preCloseTag) - if node.Parent.Type != Item { - r.cr(w) - } - case Table: - if entering { - r.cr(w) - r.out(w, tableTag) - } else { - r.out(w, tableCloseTag) - r.cr(w) - } - case TableCell: - openTag := tdTag - closeTag := tdCloseTag - if node.IsHeader { - openTag = thTag - closeTag = thCloseTag - } - if entering { - align := cellAlignment(node.Align) - if align != "" { - attrs = append(attrs, fmt.Sprintf(`align="%s"`, align)) - } - if node.Prev == nil { - r.cr(w) - } - r.tag(w, openTag, attrs) - } else { - r.out(w, closeTag) - r.cr(w) - } - case TableHead: - if entering { - r.cr(w) - r.out(w, theadTag) - } else { - r.out(w, theadCloseTag) - r.cr(w) - } - case TableBody: - if entering { - r.cr(w) - r.out(w, tbodyTag) - // XXX: this is to adhere to a rather silly test. Should fix test. - if node.FirstChild == nil { - r.cr(w) - } - } else { - r.out(w, tbodyCloseTag) - r.cr(w) - } - case TableRow: - if entering { - r.cr(w) - r.out(w, trTag) - } else { - r.out(w, trCloseTag) - r.cr(w) - } - default: - panic("Unknown node type " + node.Type.String()) - } - return GoToNext -} - -// RenderHeader writes HTML document preamble and TOC if requested. -func (r *HTMLRenderer) RenderHeader(w io.Writer, ast *Node) { - r.writeDocumentHeader(w) - if r.Flags&TOC != 0 { - r.writeTOC(w, ast) - } -} - -// RenderFooter writes HTML document footer. -func (r *HTMLRenderer) RenderFooter(w io.Writer, ast *Node) { - if r.Flags&CompletePage == 0 { - return - } - io.WriteString(w, "\n\n\n") -} - -func (r *HTMLRenderer) writeDocumentHeader(w io.Writer) { - if r.Flags&CompletePage == 0 { - return - } - ending := "" - if r.Flags&UseXHTML != 0 { - io.WriteString(w, "\n") - io.WriteString(w, "\n") - ending = " /" - } else { - io.WriteString(w, "\n") - io.WriteString(w, "\n") - } - io.WriteString(w, "\n") - io.WriteString(w, " ") - if r.Flags&Smartypants != 0 { - r.sr.Process(w, []byte(r.Title)) - } else { - escapeHTML(w, []byte(r.Title)) - } - io.WriteString(w, "\n") - io.WriteString(w, " \n") - io.WriteString(w, " \n") - if r.CSS != "" { - io.WriteString(w, " \n") - } - if r.Icon != "" { - io.WriteString(w, " \n") - } - io.WriteString(w, "\n") - io.WriteString(w, "\n\n") -} - -func (r *HTMLRenderer) writeTOC(w io.Writer, ast *Node) { - buf := bytes.Buffer{} - - inHeading := false - tocLevel := 0 - headingCount := 0 - - ast.Walk(func(node *Node, entering bool) WalkStatus { - if node.Type == Heading && !node.HeadingData.IsTitleblock { - inHeading = entering - if entering { - node.HeadingID = fmt.Sprintf("toc_%d", headingCount) - if node.Level == tocLevel { - buf.WriteString("\n\n
  • ") - } else if node.Level < tocLevel { - for node.Level < tocLevel { - tocLevel-- - buf.WriteString("
  • \n") - } - buf.WriteString("\n\n
  • ") - } else { - for node.Level > tocLevel { - tocLevel++ - buf.WriteString("\n") - } - - if buf.Len() > 0 { - io.WriteString(w, "\n") - } - r.lastOutputLen = buf.Len() -} diff --git a/vendor/github.com/russross/blackfriday/v2/inline.go b/vendor/github.com/russross/blackfriday/v2/inline.go deleted file mode 100644 index e13d4257..00000000 --- a/vendor/github.com/russross/blackfriday/v2/inline.go +++ /dev/null @@ -1,1230 +0,0 @@ -// -// Blackfriday Markdown Processor -// Available at http://github.com/russross/blackfriday -// -// Copyright © 2011 Russ Ross . -// Distributed under the Simplified BSD License. -// See README.md for details. -// - -// -// Functions to parse inline elements. -// - -package blackfriday - -import ( - "bytes" - "regexp" - "strconv" -) - -var ( - urlRe = `((https?|ftp):\/\/|\/)[-A-Za-z0-9+&@#\/%?=~_|!:,.;\(\)]+` - anchorRe = regexp.MustCompile(`^(]+")?\s?>` + urlRe + `<\/a>)`) - - // https://www.w3.org/TR/html5/syntax.html#character-references - // highest unicode code point in 17 planes (2^20): 1,114,112d = - // 7 dec digits or 6 hex digits - // named entity references can be 2-31 characters with stuff like < - // at one end and ∳ at the other. There - // are also sometimes numbers at the end, although this isn't inherent - // in the specification; there are never numbers anywhere else in - // current character references, though; see ¾ and ▒, etc. - // https://www.w3.org/TR/html5/syntax.html#named-character-references - // - // entity := "&" (named group | number ref) ";" - // named group := [a-zA-Z]{2,31}[0-9]{0,2} - // number ref := "#" (dec ref | hex ref) - // dec ref := [0-9]{1,7} - // hex ref := ("x" | "X") [0-9a-fA-F]{1,6} - htmlEntityRe = regexp.MustCompile(`&([a-zA-Z]{2,31}[0-9]{0,2}|#([0-9]{1,7}|[xX][0-9a-fA-F]{1,6}));`) -) - -// Functions to parse text within a block -// Each function returns the number of chars taken care of -// data is the complete block being rendered -// offset is the number of valid chars before the current cursor - -func (p *Markdown) inline(currBlock *Node, data []byte) { - // handlers might call us recursively: enforce a maximum depth - if p.nesting >= p.maxNesting || len(data) == 0 { - return - } - p.nesting++ - beg, end := 0, 0 - for end < len(data) { - handler := p.inlineCallback[data[end]] - if handler != nil { - if consumed, node := handler(p, data, end); consumed == 0 { - // No action from the callback. - end++ - } else { - // Copy inactive chars into the output. - currBlock.AppendChild(text(data[beg:end])) - if node != nil { - currBlock.AppendChild(node) - } - // Skip past whatever the callback used. - beg = end + consumed - end = beg - } - } else { - end++ - } - } - if beg < len(data) { - if data[end-1] == '\n' { - end-- - } - currBlock.AppendChild(text(data[beg:end])) - } - p.nesting-- -} - -// single and double emphasis parsing -func emphasis(p *Markdown, data []byte, offset int) (int, *Node) { - data = data[offset:] - c := data[0] - - if len(data) > 2 && data[1] != c { - // whitespace cannot follow an opening emphasis; - // strikethrough only takes two characters '~~' - if c == '~' || isspace(data[1]) { - return 0, nil - } - ret, node := helperEmphasis(p, data[1:], c) - if ret == 0 { - return 0, nil - } - - return ret + 1, node - } - - if len(data) > 3 && data[1] == c && data[2] != c { - if isspace(data[2]) { - return 0, nil - } - ret, node := helperDoubleEmphasis(p, data[2:], c) - if ret == 0 { - return 0, nil - } - - return ret + 2, node - } - - if len(data) > 4 && data[1] == c && data[2] == c && data[3] != c { - if c == '~' || isspace(data[3]) { - return 0, nil - } - ret, node := helperTripleEmphasis(p, data, 3, c) - if ret == 0 { - return 0, nil - } - - return ret + 3, node - } - - return 0, nil -} - -func codeSpan(p *Markdown, data []byte, offset int) (int, *Node) { - data = data[offset:] - - nb := 0 - - // count the number of backticks in the delimiter - for nb < len(data) && data[nb] == '`' { - nb++ - } - - // find the next delimiter - i, end := 0, 0 - for end = nb; end < len(data) && i < nb; end++ { - if data[end] == '`' { - i++ - } else { - i = 0 - } - } - - // no matching delimiter? - if i < nb && end >= len(data) { - return 0, nil - } - - // trim outside whitespace - fBegin := nb - for fBegin < end && data[fBegin] == ' ' { - fBegin++ - } - - fEnd := end - nb - for fEnd > fBegin && data[fEnd-1] == ' ' { - fEnd-- - } - - // render the code span - if fBegin != fEnd { - code := NewNode(Code) - code.Literal = data[fBegin:fEnd] - return end, code - } - - return end, nil -} - -// newline preceded by two spaces becomes
    -func maybeLineBreak(p *Markdown, data []byte, offset int) (int, *Node) { - origOffset := offset - for offset < len(data) && data[offset] == ' ' { - offset++ - } - - if offset < len(data) && data[offset] == '\n' { - if offset-origOffset >= 2 { - return offset - origOffset + 1, NewNode(Hardbreak) - } - return offset - origOffset, nil - } - return 0, nil -} - -// newline without two spaces works when HardLineBreak is enabled -func lineBreak(p *Markdown, data []byte, offset int) (int, *Node) { - if p.extensions&HardLineBreak != 0 { - return 1, NewNode(Hardbreak) - } - return 0, nil -} - -type linkType int - -const ( - linkNormal linkType = iota - linkImg - linkDeferredFootnote - linkInlineFootnote -) - -func isReferenceStyleLink(data []byte, pos int, t linkType) bool { - if t == linkDeferredFootnote { - return false - } - return pos < len(data)-1 && data[pos] == '[' && data[pos+1] != '^' -} - -func maybeImage(p *Markdown, data []byte, offset int) (int, *Node) { - if offset < len(data)-1 && data[offset+1] == '[' { - return link(p, data, offset) - } - return 0, nil -} - -func maybeInlineFootnote(p *Markdown, data []byte, offset int) (int, *Node) { - if offset < len(data)-1 && data[offset+1] == '[' { - return link(p, data, offset) - } - return 0, nil -} - -// '[': parse a link or an image or a footnote -func link(p *Markdown, data []byte, offset int) (int, *Node) { - // no links allowed inside regular links, footnote, and deferred footnotes - if p.insideLink && (offset > 0 && data[offset-1] == '[' || len(data)-1 > offset && data[offset+1] == '^') { - return 0, nil - } - - var t linkType - switch { - // special case: ![^text] == deferred footnote (that follows something with - // an exclamation point) - case p.extensions&Footnotes != 0 && len(data)-1 > offset && data[offset+1] == '^': - t = linkDeferredFootnote - // ![alt] == image - case offset >= 0 && data[offset] == '!': - t = linkImg - offset++ - // ^[text] == inline footnote - // [^refId] == deferred footnote - case p.extensions&Footnotes != 0: - if offset >= 0 && data[offset] == '^' { - t = linkInlineFootnote - offset++ - } else if len(data)-1 > offset && data[offset+1] == '^' { - t = linkDeferredFootnote - } - // [text] == regular link - default: - t = linkNormal - } - - data = data[offset:] - - var ( - i = 1 - noteID int - title, link, altContent []byte - textHasNl = false - ) - - if t == linkDeferredFootnote { - i++ - } - - // look for the matching closing bracket - for level := 1; level > 0 && i < len(data); i++ { - switch { - case data[i] == '\n': - textHasNl = true - - case isBackslashEscaped(data, i): - continue - - case data[i] == '[': - level++ - - case data[i] == ']': - level-- - if level <= 0 { - i-- // compensate for extra i++ in for loop - } - } - } - - if i >= len(data) { - return 0, nil - } - - txtE := i - i++ - var footnoteNode *Node - - // skip any amount of whitespace or newline - // (this is much more lax than original markdown syntax) - for i < len(data) && isspace(data[i]) { - i++ - } - - // inline style link - switch { - case i < len(data) && data[i] == '(': - // skip initial whitespace - i++ - - for i < len(data) && isspace(data[i]) { - i++ - } - - linkB := i - - // look for link end: ' " ) - findlinkend: - for i < len(data) { - switch { - case data[i] == '\\': - i += 2 - - case data[i] == ')' || data[i] == '\'' || data[i] == '"': - break findlinkend - - default: - i++ - } - } - - if i >= len(data) { - return 0, nil - } - linkE := i - - // look for title end if present - titleB, titleE := 0, 0 - if data[i] == '\'' || data[i] == '"' { - i++ - titleB = i - - findtitleend: - for i < len(data) { - switch { - case data[i] == '\\': - i += 2 - - case data[i] == ')': - break findtitleend - - default: - i++ - } - } - - if i >= len(data) { - return 0, nil - } - - // skip whitespace after title - titleE = i - 1 - for titleE > titleB && isspace(data[titleE]) { - titleE-- - } - - // check for closing quote presence - if data[titleE] != '\'' && data[titleE] != '"' { - titleB, titleE = 0, 0 - linkE = i - } - } - - // remove whitespace at the end of the link - for linkE > linkB && isspace(data[linkE-1]) { - linkE-- - } - - // remove optional angle brackets around the link - if data[linkB] == '<' { - linkB++ - } - if data[linkE-1] == '>' { - linkE-- - } - - // build escaped link and title - if linkE > linkB { - link = data[linkB:linkE] - } - - if titleE > titleB { - title = data[titleB:titleE] - } - - i++ - - // reference style link - case isReferenceStyleLink(data, i, t): - var id []byte - altContentConsidered := false - - // look for the id - i++ - linkB := i - for i < len(data) && data[i] != ']' { - i++ - } - if i >= len(data) { - return 0, nil - } - linkE := i - - // find the reference - if linkB == linkE { - if textHasNl { - var b bytes.Buffer - - for j := 1; j < txtE; j++ { - switch { - case data[j] != '\n': - b.WriteByte(data[j]) - case data[j-1] != ' ': - b.WriteByte(' ') - } - } - - id = b.Bytes() - } else { - id = data[1:txtE] - altContentConsidered = true - } - } else { - id = data[linkB:linkE] - } - - // find the reference with matching id - lr, ok := p.getRef(string(id)) - if !ok { - return 0, nil - } - - // keep link and title from reference - link = lr.link - title = lr.title - if altContentConsidered { - altContent = lr.text - } - i++ - - // shortcut reference style link or reference or inline footnote - default: - var id []byte - - // craft the id - if textHasNl { - var b bytes.Buffer - - for j := 1; j < txtE; j++ { - switch { - case data[j] != '\n': - b.WriteByte(data[j]) - case data[j-1] != ' ': - b.WriteByte(' ') - } - } - - id = b.Bytes() - } else { - if t == linkDeferredFootnote { - id = data[2:txtE] // get rid of the ^ - } else { - id = data[1:txtE] - } - } - - footnoteNode = NewNode(Item) - if t == linkInlineFootnote { - // create a new reference - noteID = len(p.notes) + 1 - - var fragment []byte - if len(id) > 0 { - if len(id) < 16 { - fragment = make([]byte, len(id)) - } else { - fragment = make([]byte, 16) - } - copy(fragment, slugify(id)) - } else { - fragment = append([]byte("footnote-"), []byte(strconv.Itoa(noteID))...) - } - - ref := &reference{ - noteID: noteID, - hasBlock: false, - link: fragment, - title: id, - footnote: footnoteNode, - } - - p.notes = append(p.notes, ref) - - link = ref.link - title = ref.title - } else { - // find the reference with matching id - lr, ok := p.getRef(string(id)) - if !ok { - return 0, nil - } - - if t == linkDeferredFootnote { - lr.noteID = len(p.notes) + 1 - lr.footnote = footnoteNode - p.notes = append(p.notes, lr) - } - - // keep link and title from reference - link = lr.link - // if inline footnote, title == footnote contents - title = lr.title - noteID = lr.noteID - } - - // rewind the whitespace - i = txtE + 1 - } - - var uLink []byte - if t == linkNormal || t == linkImg { - if len(link) > 0 { - var uLinkBuf bytes.Buffer - unescapeText(&uLinkBuf, link) - uLink = uLinkBuf.Bytes() - } - - // links need something to click on and somewhere to go - if len(uLink) == 0 || (t == linkNormal && txtE <= 1) { - return 0, nil - } - } - - // call the relevant rendering function - var linkNode *Node - switch t { - case linkNormal: - linkNode = NewNode(Link) - linkNode.Destination = normalizeURI(uLink) - linkNode.Title = title - if len(altContent) > 0 { - linkNode.AppendChild(text(altContent)) - } else { - // links cannot contain other links, so turn off link parsing - // temporarily and recurse - insideLink := p.insideLink - p.insideLink = true - p.inline(linkNode, data[1:txtE]) - p.insideLink = insideLink - } - - case linkImg: - linkNode = NewNode(Image) - linkNode.Destination = uLink - linkNode.Title = title - linkNode.AppendChild(text(data[1:txtE])) - i++ - - case linkInlineFootnote, linkDeferredFootnote: - linkNode = NewNode(Link) - linkNode.Destination = link - linkNode.Title = title - linkNode.NoteID = noteID - linkNode.Footnote = footnoteNode - if t == linkInlineFootnote { - i++ - } - - default: - return 0, nil - } - - return i, linkNode -} - -func (p *Markdown) inlineHTMLComment(data []byte) int { - if len(data) < 5 { - return 0 - } - if data[0] != '<' || data[1] != '!' || data[2] != '-' || data[3] != '-' { - return 0 - } - i := 5 - // scan for an end-of-comment marker, across lines if necessary - for i < len(data) && !(data[i-2] == '-' && data[i-1] == '-' && data[i] == '>') { - i++ - } - // no end-of-comment marker - if i >= len(data) { - return 0 - } - return i + 1 -} - -func stripMailto(link []byte) []byte { - if bytes.HasPrefix(link, []byte("mailto://")) { - return link[9:] - } else if bytes.HasPrefix(link, []byte("mailto:")) { - return link[7:] - } else { - return link - } -} - -// autolinkType specifies a kind of autolink that gets detected. -type autolinkType int - -// These are the possible flag values for the autolink renderer. -const ( - notAutolink autolinkType = iota - normalAutolink - emailAutolink -) - -// '<' when tags or autolinks are allowed -func leftAngle(p *Markdown, data []byte, offset int) (int, *Node) { - data = data[offset:] - altype, end := tagLength(data) - if size := p.inlineHTMLComment(data); size > 0 { - end = size - } - if end > 2 { - if altype != notAutolink { - var uLink bytes.Buffer - unescapeText(&uLink, data[1:end+1-2]) - if uLink.Len() > 0 { - link := uLink.Bytes() - node := NewNode(Link) - node.Destination = link - if altype == emailAutolink { - node.Destination = append([]byte("mailto:"), link...) - } - node.AppendChild(text(stripMailto(link))) - return end, node - } - } else { - htmlTag := NewNode(HTMLSpan) - htmlTag.Literal = data[:end] - return end, htmlTag - } - } - - return end, nil -} - -// '\\' backslash escape -var escapeChars = []byte("\\`*_{}[]()#+-.!:|&<>~") - -func escape(p *Markdown, data []byte, offset int) (int, *Node) { - data = data[offset:] - - if len(data) > 1 { - if p.extensions&BackslashLineBreak != 0 && data[1] == '\n' { - return 2, NewNode(Hardbreak) - } - if bytes.IndexByte(escapeChars, data[1]) < 0 { - return 0, nil - } - - return 2, text(data[1:2]) - } - - return 2, nil -} - -func unescapeText(ob *bytes.Buffer, src []byte) { - i := 0 - for i < len(src) { - org := i - for i < len(src) && src[i] != '\\' { - i++ - } - - if i > org { - ob.Write(src[org:i]) - } - - if i+1 >= len(src) { - break - } - - ob.WriteByte(src[i+1]) - i += 2 - } -} - -// '&' escaped when it doesn't belong to an entity -// valid entities are assumed to be anything matching &#?[A-Za-z0-9]+; -func entity(p *Markdown, data []byte, offset int) (int, *Node) { - data = data[offset:] - - end := 1 - - if end < len(data) && data[end] == '#' { - end++ - } - - for end < len(data) && isalnum(data[end]) { - end++ - } - - if end < len(data) && data[end] == ';' { - end++ // real entity - } else { - return 0, nil // lone '&' - } - - ent := data[:end] - // undo & escaping or it will be converted to &amp; by another - // escaper in the renderer - if bytes.Equal(ent, []byte("&")) { - ent = []byte{'&'} - } - - return end, text(ent) -} - -func linkEndsWithEntity(data []byte, linkEnd int) bool { - entityRanges := htmlEntityRe.FindAllIndex(data[:linkEnd], -1) - return entityRanges != nil && entityRanges[len(entityRanges)-1][1] == linkEnd -} - -// hasPrefixCaseInsensitive is a custom implementation of -// -// strings.HasPrefix(strings.ToLower(s), prefix) -// -// we rolled our own because ToLower pulls in a huge machinery of lowercasing -// anything from Unicode and that's very slow. Since this func will only be -// used on ASCII protocol prefixes, we can take shortcuts. -func hasPrefixCaseInsensitive(s, prefix []byte) bool { - if len(s) < len(prefix) { - return false - } - delta := byte('a' - 'A') - for i, b := range prefix { - if b != s[i] && b != s[i]+delta { - return false - } - } - return true -} - -var protocolPrefixes = [][]byte{ - []byte("http://"), - []byte("https://"), - []byte("ftp://"), - []byte("file://"), - []byte("mailto:"), -} - -const shortestPrefix = 6 // len("ftp://"), the shortest of the above - -func maybeAutoLink(p *Markdown, data []byte, offset int) (int, *Node) { - // quick check to rule out most false hits - if p.insideLink || len(data) < offset+shortestPrefix { - return 0, nil - } - for _, prefix := range protocolPrefixes { - endOfHead := offset + 8 // 8 is the len() of the longest prefix - if endOfHead > len(data) { - endOfHead = len(data) - } - if hasPrefixCaseInsensitive(data[offset:endOfHead], prefix) { - return autoLink(p, data, offset) - } - } - return 0, nil -} - -func autoLink(p *Markdown, data []byte, offset int) (int, *Node) { - // Now a more expensive check to see if we're not inside an anchor element - anchorStart := offset - offsetFromAnchor := 0 - for anchorStart > 0 && data[anchorStart] != '<' { - anchorStart-- - offsetFromAnchor++ - } - - anchorStr := anchorRe.Find(data[anchorStart:]) - if anchorStr != nil { - anchorClose := NewNode(HTMLSpan) - anchorClose.Literal = anchorStr[offsetFromAnchor:] - return len(anchorStr) - offsetFromAnchor, anchorClose - } - - // scan backward for a word boundary - rewind := 0 - for offset-rewind > 0 && rewind <= 7 && isletter(data[offset-rewind-1]) { - rewind++ - } - if rewind > 6 { // longest supported protocol is "mailto" which has 6 letters - return 0, nil - } - - origData := data - data = data[offset-rewind:] - - if !isSafeLink(data) { - return 0, nil - } - - linkEnd := 0 - for linkEnd < len(data) && !isEndOfLink(data[linkEnd]) { - linkEnd++ - } - - // Skip punctuation at the end of the link - if (data[linkEnd-1] == '.' || data[linkEnd-1] == ',') && data[linkEnd-2] != '\\' { - linkEnd-- - } - - // But don't skip semicolon if it's a part of escaped entity: - if data[linkEnd-1] == ';' && data[linkEnd-2] != '\\' && !linkEndsWithEntity(data, linkEnd) { - linkEnd-- - } - - // See if the link finishes with a punctuation sign that can be closed. - var copen byte - switch data[linkEnd-1] { - case '"': - copen = '"' - case '\'': - copen = '\'' - case ')': - copen = '(' - case ']': - copen = '[' - case '}': - copen = '{' - default: - copen = 0 - } - - if copen != 0 { - bufEnd := offset - rewind + linkEnd - 2 - - openDelim := 1 - - /* Try to close the final punctuation sign in this same line; - * if we managed to close it outside of the URL, that means that it's - * not part of the URL. If it closes inside the URL, that means it - * is part of the URL. - * - * Examples: - * - * foo http://www.pokemon.com/Pikachu_(Electric) bar - * => http://www.pokemon.com/Pikachu_(Electric) - * - * foo (http://www.pokemon.com/Pikachu_(Electric)) bar - * => http://www.pokemon.com/Pikachu_(Electric) - * - * foo http://www.pokemon.com/Pikachu_(Electric)) bar - * => http://www.pokemon.com/Pikachu_(Electric)) - * - * (foo http://www.pokemon.com/Pikachu_(Electric)) bar - * => foo http://www.pokemon.com/Pikachu_(Electric) - */ - - for bufEnd >= 0 && origData[bufEnd] != '\n' && openDelim != 0 { - if origData[bufEnd] == data[linkEnd-1] { - openDelim++ - } - - if origData[bufEnd] == copen { - openDelim-- - } - - bufEnd-- - } - - if openDelim == 0 { - linkEnd-- - } - } - - var uLink bytes.Buffer - unescapeText(&uLink, data[:linkEnd]) - - if uLink.Len() > 0 { - node := NewNode(Link) - node.Destination = uLink.Bytes() - node.AppendChild(text(uLink.Bytes())) - return linkEnd, node - } - - return linkEnd, nil -} - -func isEndOfLink(char byte) bool { - return isspace(char) || char == '<' -} - -var validUris = [][]byte{[]byte("http://"), []byte("https://"), []byte("ftp://"), []byte("mailto://")} -var validPaths = [][]byte{[]byte("/"), []byte("./"), []byte("../")} - -func isSafeLink(link []byte) bool { - for _, path := range validPaths { - if len(link) >= len(path) && bytes.Equal(link[:len(path)], path) { - if len(link) == len(path) { - return true - } else if isalnum(link[len(path)]) { - return true - } - } - } - - for _, prefix := range validUris { - // TODO: handle unicode here - // case-insensitive prefix test - if len(link) > len(prefix) && bytes.Equal(bytes.ToLower(link[:len(prefix)]), prefix) && isalnum(link[len(prefix)]) { - return true - } - } - - return false -} - -// return the length of the given tag, or 0 is it's not valid -func tagLength(data []byte) (autolink autolinkType, end int) { - var i, j int - - // a valid tag can't be shorter than 3 chars - if len(data) < 3 { - return notAutolink, 0 - } - - // begins with a '<' optionally followed by '/', followed by letter or number - if data[0] != '<' { - return notAutolink, 0 - } - if data[1] == '/' { - i = 2 - } else { - i = 1 - } - - if !isalnum(data[i]) { - return notAutolink, 0 - } - - // scheme test - autolink = notAutolink - - // try to find the beginning of an URI - for i < len(data) && (isalnum(data[i]) || data[i] == '.' || data[i] == '+' || data[i] == '-') { - i++ - } - - if i > 1 && i < len(data) && data[i] == '@' { - if j = isMailtoAutoLink(data[i:]); j != 0 { - return emailAutolink, i + j - } - } - - if i > 2 && i < len(data) && data[i] == ':' { - autolink = normalAutolink - i++ - } - - // complete autolink test: no whitespace or ' or " - switch { - case i >= len(data): - autolink = notAutolink - case autolink != notAutolink: - j = i - - for i < len(data) { - if data[i] == '\\' { - i += 2 - } else if data[i] == '>' || data[i] == '\'' || data[i] == '"' || isspace(data[i]) { - break - } else { - i++ - } - - } - - if i >= len(data) { - return autolink, 0 - } - if i > j && data[i] == '>' { - return autolink, i + 1 - } - - // one of the forbidden chars has been found - autolink = notAutolink - } - i += bytes.IndexByte(data[i:], '>') - if i < 0 { - return autolink, 0 - } - return autolink, i + 1 -} - -// look for the address part of a mail autolink and '>' -// this is less strict than the original markdown e-mail address matching -func isMailtoAutoLink(data []byte) int { - nb := 0 - - // address is assumed to be: [-@._a-zA-Z0-9]+ with exactly one '@' - for i := 0; i < len(data); i++ { - if isalnum(data[i]) { - continue - } - - switch data[i] { - case '@': - nb++ - - case '-', '.', '_': - break - - case '>': - if nb == 1 { - return i + 1 - } - return 0 - default: - return 0 - } - } - - return 0 -} - -// look for the next emph char, skipping other constructs -func helperFindEmphChar(data []byte, c byte) int { - i := 0 - - for i < len(data) { - for i < len(data) && data[i] != c && data[i] != '`' && data[i] != '[' { - i++ - } - if i >= len(data) { - return 0 - } - // do not count escaped chars - if i != 0 && data[i-1] == '\\' { - i++ - continue - } - if data[i] == c { - return i - } - - if data[i] == '`' { - // skip a code span - tmpI := 0 - i++ - for i < len(data) && data[i] != '`' { - if tmpI == 0 && data[i] == c { - tmpI = i - } - i++ - } - if i >= len(data) { - return tmpI - } - i++ - } else if data[i] == '[' { - // skip a link - tmpI := 0 - i++ - for i < len(data) && data[i] != ']' { - if tmpI == 0 && data[i] == c { - tmpI = i - } - i++ - } - i++ - for i < len(data) && (data[i] == ' ' || data[i] == '\n') { - i++ - } - if i >= len(data) { - return tmpI - } - if data[i] != '[' && data[i] != '(' { // not a link - if tmpI > 0 { - return tmpI - } - continue - } - cc := data[i] - i++ - for i < len(data) && data[i] != cc { - if tmpI == 0 && data[i] == c { - return i - } - i++ - } - if i >= len(data) { - return tmpI - } - i++ - } - } - return 0 -} - -func helperEmphasis(p *Markdown, data []byte, c byte) (int, *Node) { - i := 0 - - // skip one symbol if coming from emph3 - if len(data) > 1 && data[0] == c && data[1] == c { - i = 1 - } - - for i < len(data) { - length := helperFindEmphChar(data[i:], c) - if length == 0 { - return 0, nil - } - i += length - if i >= len(data) { - return 0, nil - } - - if i+1 < len(data) && data[i+1] == c { - i++ - continue - } - - if data[i] == c && !isspace(data[i-1]) { - - if p.extensions&NoIntraEmphasis != 0 { - if !(i+1 == len(data) || isspace(data[i+1]) || ispunct(data[i+1])) { - continue - } - } - - emph := NewNode(Emph) - p.inline(emph, data[:i]) - return i + 1, emph - } - } - - return 0, nil -} - -func helperDoubleEmphasis(p *Markdown, data []byte, c byte) (int, *Node) { - i := 0 - - for i < len(data) { - length := helperFindEmphChar(data[i:], c) - if length == 0 { - return 0, nil - } - i += length - - if i+1 < len(data) && data[i] == c && data[i+1] == c && i > 0 && !isspace(data[i-1]) { - nodeType := Strong - if c == '~' { - nodeType = Del - } - node := NewNode(nodeType) - p.inline(node, data[:i]) - return i + 2, node - } - i++ - } - return 0, nil -} - -func helperTripleEmphasis(p *Markdown, data []byte, offset int, c byte) (int, *Node) { - i := 0 - origData := data - data = data[offset:] - - for i < len(data) { - length := helperFindEmphChar(data[i:], c) - if length == 0 { - return 0, nil - } - i += length - - // skip whitespace preceded symbols - if data[i] != c || isspace(data[i-1]) { - continue - } - - switch { - case i+2 < len(data) && data[i+1] == c && data[i+2] == c: - // triple symbol found - strong := NewNode(Strong) - em := NewNode(Emph) - strong.AppendChild(em) - p.inline(em, data[:i]) - return i + 3, strong - case (i+1 < len(data) && data[i+1] == c): - // double symbol found, hand over to emph1 - length, node := helperEmphasis(p, origData[offset-2:], c) - if length == 0 { - return 0, nil - } - return length - 2, node - default: - // single symbol found, hand over to emph2 - length, node := helperDoubleEmphasis(p, origData[offset-1:], c) - if length == 0 { - return 0, nil - } - return length - 1, node - } - } - return 0, nil -} - -func text(s []byte) *Node { - node := NewNode(Text) - node.Literal = s - return node -} - -func normalizeURI(s []byte) []byte { - return s // TODO: implement -} diff --git a/vendor/github.com/russross/blackfriday/v2/markdown.go b/vendor/github.com/russross/blackfriday/v2/markdown.go deleted file mode 100644 index 382db9e9..00000000 --- a/vendor/github.com/russross/blackfriday/v2/markdown.go +++ /dev/null @@ -1,954 +0,0 @@ -// Blackfriday Markdown Processor -// Available at http://github.com/russross/blackfriday -// -// Copyright © 2011 Russ Ross . -// Distributed under the Simplified BSD License. -// See README.md for details. - -package blackfriday - -import ( - "bytes" - "fmt" - "io" - "strings" - "unicode/utf8" -) - -// -// Markdown parsing and processing -// - -// Version string of the package. Appears in the rendered document when -// CompletePage flag is on. -const Version = "2.0" - -// Extensions is a bitwise or'ed collection of enabled Blackfriday's -// extensions. -type Extensions int - -// These are the supported markdown parsing extensions. -// OR these values together to select multiple extensions. -const ( - NoExtensions Extensions = 0 - NoIntraEmphasis Extensions = 1 << iota // Ignore emphasis markers inside words - Tables // Render tables - FencedCode // Render fenced code blocks - Autolink // Detect embedded URLs that are not explicitly marked - Strikethrough // Strikethrough text using ~~test~~ - LaxHTMLBlocks // Loosen up HTML block parsing rules - SpaceHeadings // Be strict about prefix heading rules - HardLineBreak // Translate newlines into line breaks - TabSizeEight // Expand tabs to eight spaces instead of four - Footnotes // Pandoc-style footnotes - NoEmptyLineBeforeBlock // No need to insert an empty line to start a (code, quote, ordered list, unordered list) block - HeadingIDs // specify heading IDs with {#id} - Titleblock // Titleblock ala pandoc - AutoHeadingIDs // Create the heading ID from the text - BackslashLineBreak // Translate trailing backslashes into line breaks - DefinitionLists // Render definition lists - - CommonHTMLFlags HTMLFlags = UseXHTML | Smartypants | - SmartypantsFractions | SmartypantsDashes | SmartypantsLatexDashes - - CommonExtensions Extensions = NoIntraEmphasis | Tables | FencedCode | - Autolink | Strikethrough | SpaceHeadings | HeadingIDs | - BackslashLineBreak | DefinitionLists -) - -// ListType contains bitwise or'ed flags for list and list item objects. -type ListType int - -// These are the possible flag values for the ListItem renderer. -// Multiple flag values may be ORed together. -// These are mostly of interest if you are writing a new output format. -const ( - ListTypeOrdered ListType = 1 << iota - ListTypeDefinition - ListTypeTerm - - ListItemContainsBlock - ListItemBeginningOfList // TODO: figure out if this is of any use now - ListItemEndOfList -) - -// CellAlignFlags holds a type of alignment in a table cell. -type CellAlignFlags int - -// These are the possible flag values for the table cell renderer. -// Only a single one of these values will be used; they are not ORed together. -// These are mostly of interest if you are writing a new output format. -const ( - TableAlignmentLeft CellAlignFlags = 1 << iota - TableAlignmentRight - TableAlignmentCenter = (TableAlignmentLeft | TableAlignmentRight) -) - -// The size of a tab stop. -const ( - TabSizeDefault = 4 - TabSizeDouble = 8 -) - -// blockTags is a set of tags that are recognized as HTML block tags. -// Any of these can be included in markdown text without special escaping. -var blockTags = map[string]struct{}{ - "blockquote": {}, - "del": {}, - "div": {}, - "dl": {}, - "fieldset": {}, - "form": {}, - "h1": {}, - "h2": {}, - "h3": {}, - "h4": {}, - "h5": {}, - "h6": {}, - "iframe": {}, - "ins": {}, - "math": {}, - "noscript": {}, - "ol": {}, - "pre": {}, - "p": {}, - "script": {}, - "style": {}, - "table": {}, - "ul": {}, - - // HTML5 - "address": {}, - "article": {}, - "aside": {}, - "canvas": {}, - "figcaption": {}, - "figure": {}, - "footer": {}, - "header": {}, - "hgroup": {}, - "main": {}, - "nav": {}, - "output": {}, - "progress": {}, - "section": {}, - "video": {}, -} - -// Renderer is the rendering interface. This is mostly of interest if you are -// implementing a new rendering format. -// -// Only an HTML implementation is provided in this repository, see the README -// for external implementations. -type Renderer interface { - // RenderNode is the main rendering method. It will be called once for - // every leaf node and twice for every non-leaf node (first with - // entering=true, then with entering=false). The method should write its - // rendition of the node to the supplied writer w. - RenderNode(w io.Writer, node *Node, entering bool) WalkStatus - - // RenderHeader is a method that allows the renderer to produce some - // content preceding the main body of the output document. The header is - // understood in the broad sense here. For example, the default HTML - // renderer will write not only the HTML document preamble, but also the - // table of contents if it was requested. - // - // The method will be passed an entire document tree, in case a particular - // implementation needs to inspect it to produce output. - // - // The output should be written to the supplied writer w. If your - // implementation has no header to write, supply an empty implementation. - RenderHeader(w io.Writer, ast *Node) - - // RenderFooter is a symmetric counterpart of RenderHeader. - RenderFooter(w io.Writer, ast *Node) -} - -// Callback functions for inline parsing. One such function is defined -// for each character that triggers a response when parsing inline data. -type inlineParser func(p *Markdown, data []byte, offset int) (int, *Node) - -// Markdown is a type that holds extensions and the runtime state used by -// Parse, and the renderer. You can not use it directly, construct it with New. -type Markdown struct { - renderer Renderer - referenceOverride ReferenceOverrideFunc - refs map[string]*reference - inlineCallback [256]inlineParser - extensions Extensions - nesting int - maxNesting int - insideLink bool - - // Footnotes need to be ordered as well as available to quickly check for - // presence. If a ref is also a footnote, it's stored both in refs and here - // in notes. Slice is nil if footnotes not enabled. - notes []*reference - - doc *Node - tip *Node // = doc - oldTip *Node - lastMatchedContainer *Node // = doc - allClosed bool -} - -func (p *Markdown) getRef(refid string) (ref *reference, found bool) { - if p.referenceOverride != nil { - r, overridden := p.referenceOverride(refid) - if overridden { - if r == nil { - return nil, false - } - return &reference{ - link: []byte(r.Link), - title: []byte(r.Title), - noteID: 0, - hasBlock: false, - text: []byte(r.Text)}, true - } - } - // refs are case insensitive - ref, found = p.refs[strings.ToLower(refid)] - return ref, found -} - -func (p *Markdown) finalize(block *Node) { - above := block.Parent - block.open = false - p.tip = above -} - -func (p *Markdown) addChild(node NodeType, offset uint32) *Node { - return p.addExistingChild(NewNode(node), offset) -} - -func (p *Markdown) addExistingChild(node *Node, offset uint32) *Node { - for !p.tip.canContain(node.Type) { - p.finalize(p.tip) - } - p.tip.AppendChild(node) - p.tip = node - return node -} - -func (p *Markdown) closeUnmatchedBlocks() { - if !p.allClosed { - for p.oldTip != p.lastMatchedContainer { - parent := p.oldTip.Parent - p.finalize(p.oldTip) - p.oldTip = parent - } - p.allClosed = true - } -} - -// -// -// Public interface -// -// - -// Reference represents the details of a link. -// See the documentation in Options for more details on use-case. -type Reference struct { - // Link is usually the URL the reference points to. - Link string - // Title is the alternate text describing the link in more detail. - Title string - // Text is the optional text to override the ref with if the syntax used was - // [refid][] - Text string -} - -// ReferenceOverrideFunc is expected to be called with a reference string and -// return either a valid Reference type that the reference string maps to or -// nil. If overridden is false, the default reference logic will be executed. -// See the documentation in Options for more details on use-case. -type ReferenceOverrideFunc func(reference string) (ref *Reference, overridden bool) - -// New constructs a Markdown processor. You can use the same With* functions as -// for Run() to customize parser's behavior and the renderer. -func New(opts ...Option) *Markdown { - var p Markdown - for _, opt := range opts { - opt(&p) - } - p.refs = make(map[string]*reference) - p.maxNesting = 16 - p.insideLink = false - docNode := NewNode(Document) - p.doc = docNode - p.tip = docNode - p.oldTip = docNode - p.lastMatchedContainer = docNode - p.allClosed = true - // register inline parsers - p.inlineCallback[' '] = maybeLineBreak - p.inlineCallback['*'] = emphasis - p.inlineCallback['_'] = emphasis - if p.extensions&Strikethrough != 0 { - p.inlineCallback['~'] = emphasis - } - p.inlineCallback['`'] = codeSpan - p.inlineCallback['\n'] = lineBreak - p.inlineCallback['['] = link - p.inlineCallback['<'] = leftAngle - p.inlineCallback['\\'] = escape - p.inlineCallback['&'] = entity - p.inlineCallback['!'] = maybeImage - p.inlineCallback['^'] = maybeInlineFootnote - if p.extensions&Autolink != 0 { - p.inlineCallback['h'] = maybeAutoLink - p.inlineCallback['m'] = maybeAutoLink - p.inlineCallback['f'] = maybeAutoLink - p.inlineCallback['H'] = maybeAutoLink - p.inlineCallback['M'] = maybeAutoLink - p.inlineCallback['F'] = maybeAutoLink - } - if p.extensions&Footnotes != 0 { - p.notes = make([]*reference, 0) - } - return &p -} - -// Option customizes the Markdown processor's default behavior. -type Option func(*Markdown) - -// WithRenderer allows you to override the default renderer. -func WithRenderer(r Renderer) Option { - return func(p *Markdown) { - p.renderer = r - } -} - -// WithExtensions allows you to pick some of the many extensions provided by -// Blackfriday. You can bitwise OR them. -func WithExtensions(e Extensions) Option { - return func(p *Markdown) { - p.extensions = e - } -} - -// WithNoExtensions turns off all extensions and custom behavior. -func WithNoExtensions() Option { - return func(p *Markdown) { - p.extensions = NoExtensions - p.renderer = NewHTMLRenderer(HTMLRendererParameters{ - Flags: HTMLFlagsNone, - }) - } -} - -// WithRefOverride sets an optional function callback that is called every -// time a reference is resolved. -// -// In Markdown, the link reference syntax can be made to resolve a link to -// a reference instead of an inline URL, in one of the following ways: -// -// - [link text][refid] -// - [refid][] -// -// Usually, the refid is defined at the bottom of the Markdown document. If -// this override function is provided, the refid is passed to the override -// function first, before consulting the defined refids at the bottom. If -// the override function indicates an override did not occur, the refids at -// the bottom will be used to fill in the link details. -func WithRefOverride(o ReferenceOverrideFunc) Option { - return func(p *Markdown) { - p.referenceOverride = o - } -} - -// Run is the main entry point to Blackfriday. It parses and renders a -// block of markdown-encoded text. -// -// The simplest invocation of Run takes one argument, input: -// -// output := Run(input) -// -// This will parse the input with CommonExtensions enabled and render it with -// the default HTMLRenderer (with CommonHTMLFlags). -// -// Variadic arguments opts can customize the default behavior. Since Markdown -// type does not contain exported fields, you can not use it directly. Instead, -// use the With* functions. For example, this will call the most basic -// functionality, with no extensions: -// -// output := Run(input, WithNoExtensions()) -// -// You can use any number of With* arguments, even contradicting ones. They -// will be applied in order of appearance and the latter will override the -// former: -// -// output := Run(input, WithNoExtensions(), WithExtensions(exts), -// WithRenderer(yourRenderer)) -func Run(input []byte, opts ...Option) []byte { - r := NewHTMLRenderer(HTMLRendererParameters{ - Flags: CommonHTMLFlags, - }) - optList := []Option{WithRenderer(r), WithExtensions(CommonExtensions)} - optList = append(optList, opts...) - parser := New(optList...) - ast := parser.Parse(input) - var buf bytes.Buffer - parser.renderer.RenderHeader(&buf, ast) - ast.Walk(func(node *Node, entering bool) WalkStatus { - return parser.renderer.RenderNode(&buf, node, entering) - }) - parser.renderer.RenderFooter(&buf, ast) - return buf.Bytes() -} - -// Parse is an entry point to the parsing part of Blackfriday. It takes an -// input markdown document and produces a syntax tree for its contents. This -// tree can then be rendered with a default or custom renderer, or -// analyzed/transformed by the caller to whatever non-standard needs they have. -// The return value is the root node of the syntax tree. -func (p *Markdown) Parse(input []byte) *Node { - p.block(input) - // Walk the tree and finish up some of unfinished blocks - for p.tip != nil { - p.finalize(p.tip) - } - // Walk the tree again and process inline markdown in each block - p.doc.Walk(func(node *Node, entering bool) WalkStatus { - if node.Type == Paragraph || node.Type == Heading || node.Type == TableCell { - p.inline(node, node.content) - node.content = nil - } - return GoToNext - }) - p.parseRefsToAST() - return p.doc -} - -func (p *Markdown) parseRefsToAST() { - if p.extensions&Footnotes == 0 || len(p.notes) == 0 { - return - } - p.tip = p.doc - block := p.addBlock(List, nil) - block.IsFootnotesList = true - block.ListFlags = ListTypeOrdered - flags := ListItemBeginningOfList - // Note: this loop is intentionally explicit, not range-form. This is - // because the body of the loop will append nested footnotes to p.notes and - // we need to process those late additions. Range form would only walk over - // the fixed initial set. - for i := 0; i < len(p.notes); i++ { - ref := p.notes[i] - p.addExistingChild(ref.footnote, 0) - block := ref.footnote - block.ListFlags = flags | ListTypeOrdered - block.RefLink = ref.link - if ref.hasBlock { - flags |= ListItemContainsBlock - p.block(ref.title) - } else { - p.inline(block, ref.title) - } - flags &^= ListItemBeginningOfList | ListItemContainsBlock - } - above := block.Parent - finalizeList(block) - p.tip = above - block.Walk(func(node *Node, entering bool) WalkStatus { - if node.Type == Paragraph || node.Type == Heading { - p.inline(node, node.content) - node.content = nil - } - return GoToNext - }) -} - -// -// Link references -// -// This section implements support for references that (usually) appear -// as footnotes in a document, and can be referenced anywhere in the document. -// The basic format is: -// -// [1]: http://www.google.com/ "Google" -// [2]: http://www.github.com/ "Github" -// -// Anywhere in the document, the reference can be linked by referring to its -// label, i.e., 1 and 2 in this example, as in: -// -// This library is hosted on [Github][2], a git hosting site. -// -// Actual footnotes as specified in Pandoc and supported by some other Markdown -// libraries such as php-markdown are also taken care of. They look like this: -// -// This sentence needs a bit of further explanation.[^note] -// -// [^note]: This is the explanation. -// -// Footnotes should be placed at the end of the document in an ordered list. -// Finally, there are inline footnotes such as: -// -// Inline footnotes^[Also supported.] provide a quick inline explanation, -// but are rendered at the bottom of the document. -// - -// reference holds all information necessary for a reference-style links or -// footnotes. -// -// Consider this markdown with reference-style links: -// -// [link][ref] -// -// [ref]: /url/ "tooltip title" -// -// It will be ultimately converted to this HTML: -// -//

    link

    -// -// And a reference structure will be populated as follows: -// -// p.refs["ref"] = &reference{ -// link: "/url/", -// title: "tooltip title", -// } -// -// Alternatively, reference can contain information about a footnote. Consider -// this markdown: -// -// Text needing a footnote.[^a] -// -// [^a]: This is the note -// -// A reference structure will be populated as follows: -// -// p.refs["a"] = &reference{ -// link: "a", -// title: "This is the note", -// noteID: , -// } -// -// TODO: As you can see, it begs for splitting into two dedicated structures -// for refs and for footnotes. -type reference struct { - link []byte - title []byte - noteID int // 0 if not a footnote ref - hasBlock bool - footnote *Node // a link to the Item node within a list of footnotes - - text []byte // only gets populated by refOverride feature with Reference.Text -} - -func (r *reference) String() string { - return fmt.Sprintf("{link: %q, title: %q, text: %q, noteID: %d, hasBlock: %v}", - r.link, r.title, r.text, r.noteID, r.hasBlock) -} - -// Check whether or not data starts with a reference link. -// If so, it is parsed and stored in the list of references -// (in the render struct). -// Returns the number of bytes to skip to move past it, -// or zero if the first line is not a reference. -func isReference(p *Markdown, data []byte, tabSize int) int { - // up to 3 optional leading spaces - if len(data) < 4 { - return 0 - } - i := 0 - for i < 3 && data[i] == ' ' { - i++ - } - - noteID := 0 - - // id part: anything but a newline between brackets - if data[i] != '[' { - return 0 - } - i++ - if p.extensions&Footnotes != 0 { - if i < len(data) && data[i] == '^' { - // we can set it to anything here because the proper noteIds will - // be assigned later during the second pass. It just has to be != 0 - noteID = 1 - i++ - } - } - idOffset := i - for i < len(data) && data[i] != '\n' && data[i] != '\r' && data[i] != ']' { - i++ - } - if i >= len(data) || data[i] != ']' { - return 0 - } - idEnd := i - // footnotes can have empty ID, like this: [^], but a reference can not be - // empty like this: []. Break early if it's not a footnote and there's no ID - if noteID == 0 && idOffset == idEnd { - return 0 - } - // spacer: colon (space | tab)* newline? (space | tab)* - i++ - if i >= len(data) || data[i] != ':' { - return 0 - } - i++ - for i < len(data) && (data[i] == ' ' || data[i] == '\t') { - i++ - } - if i < len(data) && (data[i] == '\n' || data[i] == '\r') { - i++ - if i < len(data) && data[i] == '\n' && data[i-1] == '\r' { - i++ - } - } - for i < len(data) && (data[i] == ' ' || data[i] == '\t') { - i++ - } - if i >= len(data) { - return 0 - } - - var ( - linkOffset, linkEnd int - titleOffset, titleEnd int - lineEnd int - raw []byte - hasBlock bool - ) - - if p.extensions&Footnotes != 0 && noteID != 0 { - linkOffset, linkEnd, raw, hasBlock = scanFootnote(p, data, i, tabSize) - lineEnd = linkEnd - } else { - linkOffset, linkEnd, titleOffset, titleEnd, lineEnd = scanLinkRef(p, data, i) - } - if lineEnd == 0 { - return 0 - } - - // a valid ref has been found - - ref := &reference{ - noteID: noteID, - hasBlock: hasBlock, - } - - if noteID > 0 { - // reusing the link field for the id since footnotes don't have links - ref.link = data[idOffset:idEnd] - // if footnote, it's not really a title, it's the contained text - ref.title = raw - } else { - ref.link = data[linkOffset:linkEnd] - ref.title = data[titleOffset:titleEnd] - } - - // id matches are case-insensitive - id := string(bytes.ToLower(data[idOffset:idEnd])) - - p.refs[id] = ref - - return lineEnd -} - -func scanLinkRef(p *Markdown, data []byte, i int) (linkOffset, linkEnd, titleOffset, titleEnd, lineEnd int) { - // link: whitespace-free sequence, optionally between angle brackets - if data[i] == '<' { - i++ - } - linkOffset = i - for i < len(data) && data[i] != ' ' && data[i] != '\t' && data[i] != '\n' && data[i] != '\r' { - i++ - } - linkEnd = i - if data[linkOffset] == '<' && data[linkEnd-1] == '>' { - linkOffset++ - linkEnd-- - } - - // optional spacer: (space | tab)* (newline | '\'' | '"' | '(' ) - for i < len(data) && (data[i] == ' ' || data[i] == '\t') { - i++ - } - if i < len(data) && data[i] != '\n' && data[i] != '\r' && data[i] != '\'' && data[i] != '"' && data[i] != '(' { - return - } - - // compute end-of-line - if i >= len(data) || data[i] == '\r' || data[i] == '\n' { - lineEnd = i - } - if i+1 < len(data) && data[i] == '\r' && data[i+1] == '\n' { - lineEnd++ - } - - // optional (space|tab)* spacer after a newline - if lineEnd > 0 { - i = lineEnd + 1 - for i < len(data) && (data[i] == ' ' || data[i] == '\t') { - i++ - } - } - - // optional title: any non-newline sequence enclosed in '"() alone on its line - if i+1 < len(data) && (data[i] == '\'' || data[i] == '"' || data[i] == '(') { - i++ - titleOffset = i - - // look for EOL - for i < len(data) && data[i] != '\n' && data[i] != '\r' { - i++ - } - if i+1 < len(data) && data[i] == '\n' && data[i+1] == '\r' { - titleEnd = i + 1 - } else { - titleEnd = i - } - - // step back - i-- - for i > titleOffset && (data[i] == ' ' || data[i] == '\t') { - i-- - } - if i > titleOffset && (data[i] == '\'' || data[i] == '"' || data[i] == ')') { - lineEnd = titleEnd - titleEnd = i - } - } - - return -} - -// The first bit of this logic is the same as Parser.listItem, but the rest -// is much simpler. This function simply finds the entire block and shifts it -// over by one tab if it is indeed a block (just returns the line if it's not). -// blockEnd is the end of the section in the input buffer, and contents is the -// extracted text that was shifted over one tab. It will need to be rendered at -// the end of the document. -func scanFootnote(p *Markdown, data []byte, i, indentSize int) (blockStart, blockEnd int, contents []byte, hasBlock bool) { - if i == 0 || len(data) == 0 { - return - } - - // skip leading whitespace on first line - for i < len(data) && data[i] == ' ' { - i++ - } - - blockStart = i - - // find the end of the line - blockEnd = i - for i < len(data) && data[i-1] != '\n' { - i++ - } - - // get working buffer - var raw bytes.Buffer - - // put the first line into the working buffer - raw.Write(data[blockEnd:i]) - blockEnd = i - - // process the following lines - containsBlankLine := false - -gatherLines: - for blockEnd < len(data) { - i++ - - // find the end of this line - for i < len(data) && data[i-1] != '\n' { - i++ - } - - // if it is an empty line, guess that it is part of this item - // and move on to the next line - if p.isEmpty(data[blockEnd:i]) > 0 { - containsBlankLine = true - blockEnd = i - continue - } - - n := 0 - if n = isIndented(data[blockEnd:i], indentSize); n == 0 { - // this is the end of the block. - // we don't want to include this last line in the index. - break gatherLines - } - - // if there were blank lines before this one, insert a new one now - if containsBlankLine { - raw.WriteByte('\n') - containsBlankLine = false - } - - // get rid of that first tab, write to buffer - raw.Write(data[blockEnd+n : i]) - hasBlock = true - - blockEnd = i - } - - if data[blockEnd-1] != '\n' { - raw.WriteByte('\n') - } - - contents = raw.Bytes() - - return -} - -// -// -// Miscellaneous helper functions -// -// - -// Test if a character is a punctuation symbol. -// Taken from a private function in regexp in the stdlib. -func ispunct(c byte) bool { - for _, r := range []byte("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") { - if c == r { - return true - } - } - return false -} - -// Test if a character is a whitespace character. -func isspace(c byte) bool { - return ishorizontalspace(c) || isverticalspace(c) -} - -// Test if a character is a horizontal whitespace character. -func ishorizontalspace(c byte) bool { - return c == ' ' || c == '\t' -} - -// Test if a character is a vertical character. -func isverticalspace(c byte) bool { - return c == '\n' || c == '\r' || c == '\f' || c == '\v' -} - -// Test if a character is letter. -func isletter(c byte) bool { - return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') -} - -// Test if a character is a letter or a digit. -// TODO: check when this is looking for ASCII alnum and when it should use unicode -func isalnum(c byte) bool { - return (c >= '0' && c <= '9') || isletter(c) -} - -// Replace tab characters with spaces, aligning to the next TAB_SIZE column. -// always ends output with a newline -func expandTabs(out *bytes.Buffer, line []byte, tabSize int) { - // first, check for common cases: no tabs, or only tabs at beginning of line - i, prefix := 0, 0 - slowcase := false - for i = 0; i < len(line); i++ { - if line[i] == '\t' { - if prefix == i { - prefix++ - } else { - slowcase = true - break - } - } - } - - // no need to decode runes if all tabs are at the beginning of the line - if !slowcase { - for i = 0; i < prefix*tabSize; i++ { - out.WriteByte(' ') - } - out.Write(line[prefix:]) - return - } - - // the slow case: we need to count runes to figure out how - // many spaces to insert for each tab - column := 0 - i = 0 - for i < len(line) { - start := i - for i < len(line) && line[i] != '\t' { - _, size := utf8.DecodeRune(line[i:]) - i += size - column++ - } - - if i > start { - out.Write(line[start:i]) - } - - if i >= len(line) { - break - } - - for { - out.WriteByte(' ') - column++ - if column%tabSize == 0 { - break - } - } - - i++ - } -} - -// Find if a line counts as indented or not. -// Returns number of characters the indent is (0 = not indented). -func isIndented(data []byte, indentSize int) int { - if len(data) == 0 { - return 0 - } - if data[0] == '\t' { - return 1 - } - if len(data) < indentSize { - return 0 - } - for i := 0; i < indentSize; i++ { - if data[i] != ' ' { - return 0 - } - } - return indentSize -} - -// Create a url-safe slug for fragments -func slugify(in []byte) []byte { - if len(in) == 0 { - return in - } - out := make([]byte, 0, len(in)) - sym := false - - for _, ch := range in { - if isalnum(ch) { - sym = false - out = append(out, ch) - } else if sym { - continue - } else { - out = append(out, '-') - sym = true - } - } - var a, b int - var ch byte - for a, ch = range out { - if ch != '-' { - break - } - } - for b = len(out) - 1; b > 0; b-- { - if out[b] != '-' { - break - } - } - return out[a : b+1] -} diff --git a/vendor/github.com/russross/blackfriday/v2/node.go b/vendor/github.com/russross/blackfriday/v2/node.go deleted file mode 100644 index 04e6050c..00000000 --- a/vendor/github.com/russross/blackfriday/v2/node.go +++ /dev/null @@ -1,360 +0,0 @@ -package blackfriday - -import ( - "bytes" - "fmt" -) - -// NodeType specifies a type of a single node of a syntax tree. Usually one -// node (and its type) corresponds to a single markdown feature, e.g. emphasis -// or code block. -type NodeType int - -// Constants for identifying different types of nodes. See NodeType. -const ( - Document NodeType = iota - BlockQuote - List - Item - Paragraph - Heading - HorizontalRule - Emph - Strong - Del - Link - Image - Text - HTMLBlock - CodeBlock - Softbreak - Hardbreak - Code - HTMLSpan - Table - TableCell - TableHead - TableBody - TableRow -) - -var nodeTypeNames = []string{ - Document: "Document", - BlockQuote: "BlockQuote", - List: "List", - Item: "Item", - Paragraph: "Paragraph", - Heading: "Heading", - HorizontalRule: "HorizontalRule", - Emph: "Emph", - Strong: "Strong", - Del: "Del", - Link: "Link", - Image: "Image", - Text: "Text", - HTMLBlock: "HTMLBlock", - CodeBlock: "CodeBlock", - Softbreak: "Softbreak", - Hardbreak: "Hardbreak", - Code: "Code", - HTMLSpan: "HTMLSpan", - Table: "Table", - TableCell: "TableCell", - TableHead: "TableHead", - TableBody: "TableBody", - TableRow: "TableRow", -} - -func (t NodeType) String() string { - return nodeTypeNames[t] -} - -// ListData contains fields relevant to a List and Item node type. -type ListData struct { - ListFlags ListType - Tight bool // Skip

    s around list item data if true - BulletChar byte // '*', '+' or '-' in bullet lists - Delimiter byte // '.' or ')' after the number in ordered lists - RefLink []byte // If not nil, turns this list item into a footnote item and triggers different rendering - IsFootnotesList bool // This is a list of footnotes -} - -// LinkData contains fields relevant to a Link node type. -type LinkData struct { - Destination []byte // Destination is what goes into a href - Title []byte // Title is the tooltip thing that goes in a title attribute - NoteID int // NoteID contains a serial number of a footnote, zero if it's not a footnote - Footnote *Node // If it's a footnote, this is a direct link to the footnote Node. Otherwise nil. -} - -// CodeBlockData contains fields relevant to a CodeBlock node type. -type CodeBlockData struct { - IsFenced bool // Specifies whether it's a fenced code block or an indented one - Info []byte // This holds the info string - FenceChar byte - FenceLength int - FenceOffset int -} - -// TableCellData contains fields relevant to a TableCell node type. -type TableCellData struct { - IsHeader bool // This tells if it's under the header row - Align CellAlignFlags // This holds the value for align attribute -} - -// HeadingData contains fields relevant to a Heading node type. -type HeadingData struct { - Level int // This holds the heading level number - HeadingID string // This might hold heading ID, if present - IsTitleblock bool // Specifies whether it's a title block -} - -// Node is a single element in the abstract syntax tree of the parsed document. -// It holds connections to the structurally neighboring nodes and, for certain -// types of nodes, additional information that might be needed when rendering. -type Node struct { - Type NodeType // Determines the type of the node - Parent *Node // Points to the parent - FirstChild *Node // Points to the first child, if any - LastChild *Node // Points to the last child, if any - Prev *Node // Previous sibling; nil if it's the first child - Next *Node // Next sibling; nil if it's the last child - - Literal []byte // Text contents of the leaf nodes - - HeadingData // Populated if Type is Heading - ListData // Populated if Type is List - CodeBlockData // Populated if Type is CodeBlock - LinkData // Populated if Type is Link - TableCellData // Populated if Type is TableCell - - content []byte // Markdown content of the block nodes - open bool // Specifies an open block node that has not been finished to process yet -} - -// NewNode allocates a node of a specified type. -func NewNode(typ NodeType) *Node { - return &Node{ - Type: typ, - open: true, - } -} - -func (n *Node) String() string { - ellipsis := "" - snippet := n.Literal - if len(snippet) > 16 { - snippet = snippet[:16] - ellipsis = "..." - } - return fmt.Sprintf("%s: '%s%s'", n.Type, snippet, ellipsis) -} - -// Unlink removes node 'n' from the tree. -// It panics if the node is nil. -func (n *Node) Unlink() { - if n.Prev != nil { - n.Prev.Next = n.Next - } else if n.Parent != nil { - n.Parent.FirstChild = n.Next - } - if n.Next != nil { - n.Next.Prev = n.Prev - } else if n.Parent != nil { - n.Parent.LastChild = n.Prev - } - n.Parent = nil - n.Next = nil - n.Prev = nil -} - -// AppendChild adds a node 'child' as a child of 'n'. -// It panics if either node is nil. -func (n *Node) AppendChild(child *Node) { - child.Unlink() - child.Parent = n - if n.LastChild != nil { - n.LastChild.Next = child - child.Prev = n.LastChild - n.LastChild = child - } else { - n.FirstChild = child - n.LastChild = child - } -} - -// InsertBefore inserts 'sibling' immediately before 'n'. -// It panics if either node is nil. -func (n *Node) InsertBefore(sibling *Node) { - sibling.Unlink() - sibling.Prev = n.Prev - if sibling.Prev != nil { - sibling.Prev.Next = sibling - } - sibling.Next = n - n.Prev = sibling - sibling.Parent = n.Parent - if sibling.Prev == nil { - sibling.Parent.FirstChild = sibling - } -} - -// IsContainer returns true if 'n' can contain children. -func (n *Node) IsContainer() bool { - switch n.Type { - case Document: - fallthrough - case BlockQuote: - fallthrough - case List: - fallthrough - case Item: - fallthrough - case Paragraph: - fallthrough - case Heading: - fallthrough - case Emph: - fallthrough - case Strong: - fallthrough - case Del: - fallthrough - case Link: - fallthrough - case Image: - fallthrough - case Table: - fallthrough - case TableHead: - fallthrough - case TableBody: - fallthrough - case TableRow: - fallthrough - case TableCell: - return true - default: - return false - } -} - -// IsLeaf returns true if 'n' is a leaf node. -func (n *Node) IsLeaf() bool { - return !n.IsContainer() -} - -func (n *Node) canContain(t NodeType) bool { - if n.Type == List { - return t == Item - } - if n.Type == Document || n.Type == BlockQuote || n.Type == Item { - return t != Item - } - if n.Type == Table { - return t == TableHead || t == TableBody - } - if n.Type == TableHead || n.Type == TableBody { - return t == TableRow - } - if n.Type == TableRow { - return t == TableCell - } - return false -} - -// WalkStatus allows NodeVisitor to have some control over the tree traversal. -// It is returned from NodeVisitor and different values allow Node.Walk to -// decide which node to go to next. -type WalkStatus int - -const ( - // GoToNext is the default traversal of every node. - GoToNext WalkStatus = iota - // SkipChildren tells walker to skip all children of current node. - SkipChildren - // Terminate tells walker to terminate the traversal. - Terminate -) - -// NodeVisitor is a callback to be called when traversing the syntax tree. -// Called twice for every node: once with entering=true when the branch is -// first visited, then with entering=false after all the children are done. -type NodeVisitor func(node *Node, entering bool) WalkStatus - -// Walk is a convenience method that instantiates a walker and starts a -// traversal of subtree rooted at n. -func (n *Node) Walk(visitor NodeVisitor) { - w := newNodeWalker(n) - for w.current != nil { - status := visitor(w.current, w.entering) - switch status { - case GoToNext: - w.next() - case SkipChildren: - w.entering = false - w.next() - case Terminate: - return - } - } -} - -type nodeWalker struct { - current *Node - root *Node - entering bool -} - -func newNodeWalker(root *Node) *nodeWalker { - return &nodeWalker{ - current: root, - root: root, - entering: true, - } -} - -func (nw *nodeWalker) next() { - if (!nw.current.IsContainer() || !nw.entering) && nw.current == nw.root { - nw.current = nil - return - } - if nw.entering && nw.current.IsContainer() { - if nw.current.FirstChild != nil { - nw.current = nw.current.FirstChild - nw.entering = true - } else { - nw.entering = false - } - } else if nw.current.Next == nil { - nw.current = nw.current.Parent - nw.entering = false - } else { - nw.current = nw.current.Next - nw.entering = true - } -} - -func dump(ast *Node) { - fmt.Println(dumpString(ast)) -} - -func dumpR(ast *Node, depth int) string { - if ast == nil { - return "" - } - indent := bytes.Repeat([]byte("\t"), depth) - content := ast.Literal - if content == nil { - content = ast.content - } - result := fmt.Sprintf("%s%s(%q)\n", indent, ast.Type, content) - for n := ast.FirstChild; n != nil; n = n.Next { - result += dumpR(n, depth+1) - } - return result -} - -func dumpString(ast *Node) string { - return dumpR(ast, 0) -} diff --git a/vendor/github.com/russross/blackfriday/v2/smartypants.go b/vendor/github.com/russross/blackfriday/v2/smartypants.go deleted file mode 100644 index 3a220e94..00000000 --- a/vendor/github.com/russross/blackfriday/v2/smartypants.go +++ /dev/null @@ -1,457 +0,0 @@ -// -// Blackfriday Markdown Processor -// Available at http://github.com/russross/blackfriday -// -// Copyright © 2011 Russ Ross . -// Distributed under the Simplified BSD License. -// See README.md for details. -// - -// -// -// SmartyPants rendering -// -// - -package blackfriday - -import ( - "bytes" - "io" -) - -// SPRenderer is a struct containing state of a Smartypants renderer. -type SPRenderer struct { - inSingleQuote bool - inDoubleQuote bool - callbacks [256]smartCallback -} - -func wordBoundary(c byte) bool { - return c == 0 || isspace(c) || ispunct(c) -} - -func tolower(c byte) byte { - if c >= 'A' && c <= 'Z' { - return c - 'A' + 'a' - } - return c -} - -func isdigit(c byte) bool { - return c >= '0' && c <= '9' -} - -func smartQuoteHelper(out *bytes.Buffer, previousChar byte, nextChar byte, quote byte, isOpen *bool, addNBSP bool) bool { - // edge of the buffer is likely to be a tag that we don't get to see, - // so we treat it like text sometimes - - // enumerate all sixteen possibilities for (previousChar, nextChar) - // each can be one of {0, space, punct, other} - switch { - case previousChar == 0 && nextChar == 0: - // context is not any help here, so toggle - *isOpen = !*isOpen - case isspace(previousChar) && nextChar == 0: - // [ "] might be [ "foo...] - *isOpen = true - case ispunct(previousChar) && nextChar == 0: - // [!"] hmm... could be [Run!"] or [("...] - *isOpen = false - case /* isnormal(previousChar) && */ nextChar == 0: - // [a"] is probably a close - *isOpen = false - case previousChar == 0 && isspace(nextChar): - // [" ] might be [...foo" ] - *isOpen = false - case isspace(previousChar) && isspace(nextChar): - // [ " ] context is not any help here, so toggle - *isOpen = !*isOpen - case ispunct(previousChar) && isspace(nextChar): - // [!" ] is probably a close - *isOpen = false - case /* isnormal(previousChar) && */ isspace(nextChar): - // [a" ] this is one of the easy cases - *isOpen = false - case previousChar == 0 && ispunct(nextChar): - // ["!] hmm... could be ["$1.95] or ["!...] - *isOpen = false - case isspace(previousChar) && ispunct(nextChar): - // [ "!] looks more like [ "$1.95] - *isOpen = true - case ispunct(previousChar) && ispunct(nextChar): - // [!"!] context is not any help here, so toggle - *isOpen = !*isOpen - case /* isnormal(previousChar) && */ ispunct(nextChar): - // [a"!] is probably a close - *isOpen = false - case previousChar == 0 /* && isnormal(nextChar) */ : - // ["a] is probably an open - *isOpen = true - case isspace(previousChar) /* && isnormal(nextChar) */ : - // [ "a] this is one of the easy cases - *isOpen = true - case ispunct(previousChar) /* && isnormal(nextChar) */ : - // [!"a] is probably an open - *isOpen = true - default: - // [a'b] maybe a contraction? - *isOpen = false - } - - // Note that with the limited lookahead, this non-breaking - // space will also be appended to single double quotes. - if addNBSP && !*isOpen { - out.WriteString(" ") - } - - out.WriteByte('&') - if *isOpen { - out.WriteByte('l') - } else { - out.WriteByte('r') - } - out.WriteByte(quote) - out.WriteString("quo;") - - if addNBSP && *isOpen { - out.WriteString(" ") - } - - return true -} - -func (r *SPRenderer) smartSingleQuote(out *bytes.Buffer, previousChar byte, text []byte) int { - if len(text) >= 2 { - t1 := tolower(text[1]) - - if t1 == '\'' { - nextChar := byte(0) - if len(text) >= 3 { - nextChar = text[2] - } - if smartQuoteHelper(out, previousChar, nextChar, 'd', &r.inDoubleQuote, false) { - return 1 - } - } - - if (t1 == 's' || t1 == 't' || t1 == 'm' || t1 == 'd') && (len(text) < 3 || wordBoundary(text[2])) { - out.WriteString("’") - return 0 - } - - if len(text) >= 3 { - t2 := tolower(text[2]) - - if ((t1 == 'r' && t2 == 'e') || (t1 == 'l' && t2 == 'l') || (t1 == 'v' && t2 == 'e')) && - (len(text) < 4 || wordBoundary(text[3])) { - out.WriteString("’") - return 0 - } - } - } - - nextChar := byte(0) - if len(text) > 1 { - nextChar = text[1] - } - if smartQuoteHelper(out, previousChar, nextChar, 's', &r.inSingleQuote, false) { - return 0 - } - - out.WriteByte(text[0]) - return 0 -} - -func (r *SPRenderer) smartParens(out *bytes.Buffer, previousChar byte, text []byte) int { - if len(text) >= 3 { - t1 := tolower(text[1]) - t2 := tolower(text[2]) - - if t1 == 'c' && t2 == ')' { - out.WriteString("©") - return 2 - } - - if t1 == 'r' && t2 == ')' { - out.WriteString("®") - return 2 - } - - if len(text) >= 4 && t1 == 't' && t2 == 'm' && text[3] == ')' { - out.WriteString("™") - return 3 - } - } - - out.WriteByte(text[0]) - return 0 -} - -func (r *SPRenderer) smartDash(out *bytes.Buffer, previousChar byte, text []byte) int { - if len(text) >= 2 { - if text[1] == '-' { - out.WriteString("—") - return 1 - } - - if wordBoundary(previousChar) && wordBoundary(text[1]) { - out.WriteString("–") - return 0 - } - } - - out.WriteByte(text[0]) - return 0 -} - -func (r *SPRenderer) smartDashLatex(out *bytes.Buffer, previousChar byte, text []byte) int { - if len(text) >= 3 && text[1] == '-' && text[2] == '-' { - out.WriteString("—") - return 2 - } - if len(text) >= 2 && text[1] == '-' { - out.WriteString("–") - return 1 - } - - out.WriteByte(text[0]) - return 0 -} - -func (r *SPRenderer) smartAmpVariant(out *bytes.Buffer, previousChar byte, text []byte, quote byte, addNBSP bool) int { - if bytes.HasPrefix(text, []byte(""")) { - nextChar := byte(0) - if len(text) >= 7 { - nextChar = text[6] - } - if smartQuoteHelper(out, previousChar, nextChar, quote, &r.inDoubleQuote, addNBSP) { - return 5 - } - } - - if bytes.HasPrefix(text, []byte("�")) { - return 3 - } - - out.WriteByte('&') - return 0 -} - -func (r *SPRenderer) smartAmp(angledQuotes, addNBSP bool) func(*bytes.Buffer, byte, []byte) int { - var quote byte = 'd' - if angledQuotes { - quote = 'a' - } - - return func(out *bytes.Buffer, previousChar byte, text []byte) int { - return r.smartAmpVariant(out, previousChar, text, quote, addNBSP) - } -} - -func (r *SPRenderer) smartPeriod(out *bytes.Buffer, previousChar byte, text []byte) int { - if len(text) >= 3 && text[1] == '.' && text[2] == '.' { - out.WriteString("…") - return 2 - } - - if len(text) >= 5 && text[1] == ' ' && text[2] == '.' && text[3] == ' ' && text[4] == '.' { - out.WriteString("…") - return 4 - } - - out.WriteByte(text[0]) - return 0 -} - -func (r *SPRenderer) smartBacktick(out *bytes.Buffer, previousChar byte, text []byte) int { - if len(text) >= 2 && text[1] == '`' { - nextChar := byte(0) - if len(text) >= 3 { - nextChar = text[2] - } - if smartQuoteHelper(out, previousChar, nextChar, 'd', &r.inDoubleQuote, false) { - return 1 - } - } - - out.WriteByte(text[0]) - return 0 -} - -func (r *SPRenderer) smartNumberGeneric(out *bytes.Buffer, previousChar byte, text []byte) int { - if wordBoundary(previousChar) && previousChar != '/' && len(text) >= 3 { - // is it of the form digits/digits(word boundary)?, i.e., \d+/\d+\b - // note: check for regular slash (/) or fraction slash (⁄, 0x2044, or 0xe2 81 84 in utf-8) - // and avoid changing dates like 1/23/2005 into fractions. - numEnd := 0 - for len(text) > numEnd && isdigit(text[numEnd]) { - numEnd++ - } - if numEnd == 0 { - out.WriteByte(text[0]) - return 0 - } - denStart := numEnd + 1 - if len(text) > numEnd+3 && text[numEnd] == 0xe2 && text[numEnd+1] == 0x81 && text[numEnd+2] == 0x84 { - denStart = numEnd + 3 - } else if len(text) < numEnd+2 || text[numEnd] != '/' { - out.WriteByte(text[0]) - return 0 - } - denEnd := denStart - for len(text) > denEnd && isdigit(text[denEnd]) { - denEnd++ - } - if denEnd == denStart { - out.WriteByte(text[0]) - return 0 - } - if len(text) == denEnd || wordBoundary(text[denEnd]) && text[denEnd] != '/' { - out.WriteString("") - out.Write(text[:numEnd]) - out.WriteString("") - out.Write(text[denStart:denEnd]) - out.WriteString("") - return denEnd - 1 - } - } - - out.WriteByte(text[0]) - return 0 -} - -func (r *SPRenderer) smartNumber(out *bytes.Buffer, previousChar byte, text []byte) int { - if wordBoundary(previousChar) && previousChar != '/' && len(text) >= 3 { - if text[0] == '1' && text[1] == '/' && text[2] == '2' { - if len(text) < 4 || wordBoundary(text[3]) && text[3] != '/' { - out.WriteString("½") - return 2 - } - } - - if text[0] == '1' && text[1] == '/' && text[2] == '4' { - if len(text) < 4 || wordBoundary(text[3]) && text[3] != '/' || (len(text) >= 5 && tolower(text[3]) == 't' && tolower(text[4]) == 'h') { - out.WriteString("¼") - return 2 - } - } - - if text[0] == '3' && text[1] == '/' && text[2] == '4' { - if len(text) < 4 || wordBoundary(text[3]) && text[3] != '/' || (len(text) >= 6 && tolower(text[3]) == 't' && tolower(text[4]) == 'h' && tolower(text[5]) == 's') { - out.WriteString("¾") - return 2 - } - } - } - - out.WriteByte(text[0]) - return 0 -} - -func (r *SPRenderer) smartDoubleQuoteVariant(out *bytes.Buffer, previousChar byte, text []byte, quote byte) int { - nextChar := byte(0) - if len(text) > 1 { - nextChar = text[1] - } - if !smartQuoteHelper(out, previousChar, nextChar, quote, &r.inDoubleQuote, false) { - out.WriteString(""") - } - - return 0 -} - -func (r *SPRenderer) smartDoubleQuote(out *bytes.Buffer, previousChar byte, text []byte) int { - return r.smartDoubleQuoteVariant(out, previousChar, text, 'd') -} - -func (r *SPRenderer) smartAngledDoubleQuote(out *bytes.Buffer, previousChar byte, text []byte) int { - return r.smartDoubleQuoteVariant(out, previousChar, text, 'a') -} - -func (r *SPRenderer) smartLeftAngle(out *bytes.Buffer, previousChar byte, text []byte) int { - i := 0 - - for i < len(text) && text[i] != '>' { - i++ - } - - out.Write(text[:i+1]) - return i -} - -type smartCallback func(out *bytes.Buffer, previousChar byte, text []byte) int - -// NewSmartypantsRenderer constructs a Smartypants renderer object. -func NewSmartypantsRenderer(flags HTMLFlags) *SPRenderer { - var ( - r SPRenderer - - smartAmpAngled = r.smartAmp(true, false) - smartAmpAngledNBSP = r.smartAmp(true, true) - smartAmpRegular = r.smartAmp(false, false) - smartAmpRegularNBSP = r.smartAmp(false, true) - - addNBSP = flags&SmartypantsQuotesNBSP != 0 - ) - - if flags&SmartypantsAngledQuotes == 0 { - r.callbacks['"'] = r.smartDoubleQuote - if !addNBSP { - r.callbacks['&'] = smartAmpRegular - } else { - r.callbacks['&'] = smartAmpRegularNBSP - } - } else { - r.callbacks['"'] = r.smartAngledDoubleQuote - if !addNBSP { - r.callbacks['&'] = smartAmpAngled - } else { - r.callbacks['&'] = smartAmpAngledNBSP - } - } - r.callbacks['\''] = r.smartSingleQuote - r.callbacks['('] = r.smartParens - if flags&SmartypantsDashes != 0 { - if flags&SmartypantsLatexDashes == 0 { - r.callbacks['-'] = r.smartDash - } else { - r.callbacks['-'] = r.smartDashLatex - } - } - r.callbacks['.'] = r.smartPeriod - if flags&SmartypantsFractions == 0 { - r.callbacks['1'] = r.smartNumber - r.callbacks['3'] = r.smartNumber - } else { - for ch := '1'; ch <= '9'; ch++ { - r.callbacks[ch] = r.smartNumberGeneric - } - } - r.callbacks['<'] = r.smartLeftAngle - r.callbacks['`'] = r.smartBacktick - return &r -} - -// Process is the entry point of the Smartypants renderer. -func (r *SPRenderer) Process(w io.Writer, text []byte) { - mark := 0 - for i := 0; i < len(text); i++ { - if action := r.callbacks[text[i]]; action != nil { - if i > mark { - w.Write(text[mark:i]) - } - previousChar := byte(0) - if i > 0 { - previousChar = text[i-1] - } - var tmp bytes.Buffer - i += action(&tmp, previousChar, text[i:]) - w.Write(tmp.Bytes()) - mark = i + 1 - } - } - if mark < len(text) { - w.Write(text[mark:]) - } -} diff --git a/vendor/github.com/sergi/go-diff/diffmatchpatch/diff.go b/vendor/github.com/sergi/go-diff/diffmatchpatch/diff.go index c3bea516..915d5090 100644 --- a/vendor/github.com/sergi/go-diff/diffmatchpatch/diff.go +++ b/vendor/github.com/sergi/go-diff/diffmatchpatch/diff.go @@ -157,9 +157,9 @@ func (dmp *DiffMatchPatch) diffCompute(text1, text2 []rune, checklines bool, dea } // Shorter text is inside the longer text (speedup). return []Diff{ - {op, string(longtext[:i])}, - {DiffEqual, string(shorttext)}, - {op, string(longtext[i+len(shorttext):])}, + Diff{op, string(longtext[:i])}, + Diff{DiffEqual, string(shorttext)}, + Diff{op, string(longtext[i+len(shorttext):])}, } } else if len(shorttext) == 1 { // Single character string. diff --git a/vendor/github.com/sergi/go-diff/diffmatchpatch/patch.go b/vendor/github.com/sergi/go-diff/diffmatchpatch/patch.go index f6eae832..0dbe3bdd 100644 --- a/vendor/github.com/sergi/go-diff/diffmatchpatch/patch.go +++ b/vendor/github.com/sergi/go-diff/diffmatchpatch/patch.go @@ -93,7 +93,7 @@ func (dmp *DiffMatchPatch) PatchAddContext(patch Patch, text string) Patch { // Add the prefix. prefix := text[max(0, patch.Start2-padding):patch.Start2] if len(prefix) != 0 { - patch.diffs = append([]Diff{{DiffEqual, prefix}}, patch.diffs...) + patch.diffs = append([]Diff{Diff{DiffEqual, prefix}}, patch.diffs...) } // Add the suffix. suffix := text[patch.Start2+patch.Length1 : min(len(text), patch.Start2+patch.Length1+padding)] @@ -336,7 +336,7 @@ func (dmp *DiffMatchPatch) PatchAddPadding(patches []Patch) string { // Add some padding on start of first diff. if len(patches[0].diffs) == 0 || patches[0].diffs[0].Type != DiffEqual { // Add nullPadding equality. - patches[0].diffs = append([]Diff{{DiffEqual, nullPadding}}, patches[0].diffs...) + patches[0].diffs = append([]Diff{Diff{DiffEqual, nullPadding}}, patches[0].diffs...) patches[0].Start1 -= paddingLength // Should be 0. patches[0].Start2 -= paddingLength // Should be 0. patches[0].Length1 += paddingLength diff --git a/vendor/github.com/sirupsen/logrus/doc.go b/vendor/github.com/sirupsen/logrus/doc.go index 51392be8..da67aba0 100644 --- a/vendor/github.com/sirupsen/logrus/doc.go +++ b/vendor/github.com/sirupsen/logrus/doc.go @@ -1,25 +1,25 @@ /* Package logrus is a structured logger for Go, completely API compatible with the standard library logger. + The simplest way to use Logrus is simply the package-level exported logger: - package main + package main - import ( - log "github.com/sirupsen/logrus" - ) + import ( + log "github.com/sirupsen/logrus" + ) - func main() { - log.WithFields(log.Fields{ - "animal": "walrus", - "number": 1, - "size": 10, - }).Info("A walrus appears") - } + func main() { + log.WithFields(log.Fields{ + "animal": "walrus", + "number": 1, + "size": 10, + }).Info("A walrus appears") + } Output: - - time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10 + time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10 For a full guide visit https://github.com/sirupsen/logrus */ diff --git a/vendor/github.com/sirupsen/logrus/formatter.go b/vendor/github.com/sirupsen/logrus/formatter.go index 8c761551..40888377 100644 --- a/vendor/github.com/sirupsen/logrus/formatter.go +++ b/vendor/github.com/sirupsen/logrus/formatter.go @@ -30,12 +30,12 @@ type Formatter interface { // This is to not silently overwrite `time`, `msg`, `func` and `level` fields when // dumping it. If this code wasn't there doing: // -// logrus.WithField("level", 1).Info("hello") +// logrus.WithField("level", 1).Info("hello") // // Would just silently drop the user provided level. Instead with this code // it'll logged as: // -// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."} +// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."} // // It's not exported because it's still using Data in an opinionated way. It's to // avoid code duplication between the two default formatters. diff --git a/vendor/github.com/sirupsen/logrus/logger.go b/vendor/github.com/sirupsen/logrus/logger.go index df059412..5ff0aef6 100644 --- a/vendor/github.com/sirupsen/logrus/logger.go +++ b/vendor/github.com/sirupsen/logrus/logger.go @@ -76,12 +76,12 @@ func (mw *MutexWrap) Disable() { // `Out` and `Hooks` directly on the default logger instance. You can also just // instantiate your own: // -// var log = &logrus.Logger{ -// Out: os.Stderr, -// Formatter: new(logrus.TextFormatter), -// Hooks: make(logrus.LevelHooks), -// Level: logrus.DebugLevel, -// } +// var log = &logrus.Logger{ +// Out: os.Stderr, +// Formatter: new(logrus.TextFormatter), +// Hooks: make(logrus.LevelHooks), +// Level: logrus.DebugLevel, +// } // // It's recommended to make this a global instance called `log`. func New() *Logger { @@ -347,9 +347,9 @@ func (logger *Logger) Exit(code int) { logger.ExitFunc(code) } -// When file is opened with appending mode, it's safe to -// write concurrently to a file (within 4k message on Linux). -// In these cases user can choose to disable the lock. +//When file is opened with appending mode, it's safe to +//write concurrently to a file (within 4k message on Linux). +//In these cases user can choose to disable the lock. func (logger *Logger) SetNoLock() { logger.mu.Disable() } diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go b/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go index 45de3e2b..2403de98 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go @@ -1,4 +1,3 @@ -//go:build appengine // +build appengine package logrus diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go b/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go index e3fa38b7..49978998 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go @@ -1,4 +1,3 @@ -//go:build (darwin || dragonfly || freebsd || netbsd || openbsd) && !js // +build darwin dragonfly freebsd netbsd openbsd // +build !js diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_js.go b/vendor/github.com/sirupsen/logrus/terminal_check_js.go index 9e951f1b..ebdae3ec 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_js.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_js.go @@ -1,4 +1,3 @@ -//go:build js // +build js package logrus diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go b/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go index 04232da1..97af92c6 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go @@ -1,4 +1,3 @@ -//go:build js || nacl || plan9 // +build js nacl plan9 package logrus diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go b/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go index 1b4a99e3..3293fb3c 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go @@ -1,4 +1,3 @@ -//go:build !appengine && !js && !windows && !nacl && !plan9 // +build !appengine,!js,!windows,!nacl,!plan9 package logrus diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_unix.go b/vendor/github.com/sirupsen/logrus/terminal_check_unix.go index f3154b17..04748b85 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_unix.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_unix.go @@ -1,4 +1,3 @@ -//go:build (linux || aix || zos) && !js // +build linux aix zos // +build !js diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_windows.go b/vendor/github.com/sirupsen/logrus/terminal_check_windows.go index 893c6241..2879eb50 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_windows.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_windows.go @@ -1,4 +1,3 @@ -//go:build !appengine && !js && windows // +build !appengine,!js,windows package logrus diff --git a/vendor/github.com/spf13/pflag/flag.go b/vendor/github.com/spf13/pflag/flag.go index e368aaf1..24a5036e 100644 --- a/vendor/github.com/spf13/pflag/flag.go +++ b/vendor/github.com/spf13/pflag/flag.go @@ -27,32 +27,23 @@ unaffected. 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. 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) @@ -63,26 +54,22 @@ 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(&flagvar, "boolname", "b", true, "help message") } flag.VarP(&flagval, "varname", "v", "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 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 @@ -940,9 +927,9 @@ func (f *FlagSet) usage() { } } -// --unknown (args will be empty) -// --unknown --next-flag ... (args will be --next-flag ...) -// --unknown arg ... (args will be arg ...) +//--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 diff --git a/vendor/github.com/spf13/pflag/string_slice.go b/vendor/github.com/spf13/pflag/string_slice.go index d421887e..3cb2e69d 100644 --- a/vendor/github.com/spf13/pflag/string_slice.go +++ b/vendor/github.com/spf13/pflag/string_slice.go @@ -98,12 +98,9 @@ func (f *FlagSet) GetStringSlice(name string) ([]string, error) { // 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" -// +// --ss="v1,v2" --ss="v3" // will result in -// -// []string{"v1", "v2", "v3"} +// []string{"v1", "v2", "v3"} func (f *FlagSet) StringSliceVar(p *[]string, name string, value []string, usage string) { f.VarP(newStringSliceValue(value, p), name, "", usage) } @@ -117,12 +114,9 @@ func (f *FlagSet) StringSliceVarP(p *[]string, name, shorthand string, value []s // 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" -// +// --ss="v1,v2" --ss="v3" // will result in -// -// []string{"v1", "v2", "v3"} +// []string{"v1", "v2", "v3"} func StringSliceVar(p *[]string, name string, value []string, usage string) { CommandLine.VarP(newStringSliceValue(value, p), name, "", usage) } @@ -136,12 +130,9 @@ func StringSliceVarP(p *[]string, name, shorthand string, value []string, usage // 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" -// +// --ss="v1,v2" --ss="v3" // will result in -// -// []string{"v1", "v2", "v3"} +// []string{"v1", "v2", "v3"} func (f *FlagSet) StringSlice(name string, value []string, usage string) *[]string { p := []string{} f.StringSliceVarP(&p, name, "", value, usage) @@ -159,12 +150,9 @@ func (f *FlagSet) StringSliceP(name, shorthand string, value []string, usage str // 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" -// +// --ss="v1,v2" --ss="v3" // will result in -// -// []string{"v1", "v2", "v3"} +// []string{"v1", "v2", "v3"} func StringSlice(name string, value []string, usage string) *[]string { return CommandLine.StringSliceP(name, "", value, usage) } diff --git a/vendor/github.com/theupdateframework/notary/client/client.go b/vendor/github.com/theupdateframework/notary/client/client.go index 0cdc252d..cfaa6146 100644 --- a/vendor/github.com/theupdateframework/notary/client/client.go +++ b/vendor/github.com/theupdateframework/notary/client/client.go @@ -1,4 +1,4 @@ -// Package client implements everything required for interacting with a Notary repository. +//Package client implements everything required for interacting with a Notary repository. package client import ( diff --git a/vendor/github.com/theupdateframework/notary/client/reader.go b/vendor/github.com/theupdateframework/notary/client/reader.go index c87118ef..df966ee3 100644 --- a/vendor/github.com/theupdateframework/notary/client/reader.go +++ b/vendor/github.com/theupdateframework/notary/client/reader.go @@ -33,7 +33,7 @@ type TargetSignedStruct struct { Signatures []data.Signature } -// ErrNoSuchTarget is returned when no valid trust data is found. +//ErrNoSuchTarget is returned when no valid trust data is found. type ErrNoSuchTarget string func (f ErrNoSuchTarget) Error() string { diff --git a/vendor/github.com/theupdateframework/notary/client/repo.go b/vendor/github.com/theupdateframework/notary/client/repo.go index 235b9186..cf2242b7 100644 --- a/vendor/github.com/theupdateframework/notary/client/repo.go +++ b/vendor/github.com/theupdateframework/notary/client/repo.go @@ -1,4 +1,3 @@ -//go:build !pkcs11 // +build !pkcs11 package client diff --git a/vendor/github.com/theupdateframework/notary/client/repo_pkcs11.go b/vendor/github.com/theupdateframework/notary/client/repo_pkcs11.go index e82f62d5..a24d3e60 100644 --- a/vendor/github.com/theupdateframework/notary/client/repo_pkcs11.go +++ b/vendor/github.com/theupdateframework/notary/client/repo_pkcs11.go @@ -1,4 +1,3 @@ -//go:build pkcs11 // +build pkcs11 package client diff --git a/vendor/github.com/theupdateframework/notary/const_nowindows.go b/vendor/github.com/theupdateframework/notary/const_nowindows.go index 557871be..67551717 100644 --- a/vendor/github.com/theupdateframework/notary/const_nowindows.go +++ b/vendor/github.com/theupdateframework/notary/const_nowindows.go @@ -1,4 +1,3 @@ -//go:build !windows // +build !windows package notary diff --git a/vendor/github.com/theupdateframework/notary/const_windows.go b/vendor/github.com/theupdateframework/notary/const_windows.go index b82472d3..e2dff0e4 100644 --- a/vendor/github.com/theupdateframework/notary/const_windows.go +++ b/vendor/github.com/theupdateframework/notary/const_windows.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package notary diff --git a/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/import.go b/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/import.go index e0b3b74b..680ded28 100644 --- a/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/import.go +++ b/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/import.go @@ -1,4 +1,3 @@ -//go:build pkcs11 // +build pkcs11 package yubikey diff --git a/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/pkcs11_darwin.go b/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/pkcs11_darwin.go index 1204cbd3..f399dff3 100644 --- a/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/pkcs11_darwin.go +++ b/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/pkcs11_darwin.go @@ -1,4 +1,3 @@ -//go:build pkcs11 && darwin // +build pkcs11,darwin package yubikey diff --git a/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/pkcs11_interface.go b/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/pkcs11_interface.go index a6319bb2..4a46e05f 100644 --- a/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/pkcs11_interface.go +++ b/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/pkcs11_interface.go @@ -1,4 +1,3 @@ -//go:build pkcs11 // +build pkcs11 // an interface around the pkcs11 library, so that things can be mocked out diff --git a/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/pkcs11_linux.go b/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/pkcs11_linux.go index 1f5f6c86..836018f0 100644 --- a/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/pkcs11_linux.go +++ b/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/pkcs11_linux.go @@ -1,4 +1,3 @@ -//go:build pkcs11 && linux // +build pkcs11,linux package yubikey diff --git a/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/yubikeystore.go b/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/yubikeystore.go index 305cdfda..1fd71eea 100644 --- a/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/yubikeystore.go +++ b/vendor/github.com/theupdateframework/notary/trustmanager/yubikey/yubikeystore.go @@ -1,4 +1,3 @@ -//go:build pkcs11 // +build pkcs11 package yubikey diff --git a/vendor/github.com/theupdateframework/notary/tuf/utils/pkcs8.go b/vendor/github.com/theupdateframework/notary/tuf/utils/pkcs8.go index 121cee57..ff01d281 100644 --- a/vendor/github.com/theupdateframework/notary/tuf/utils/pkcs8.go +++ b/vendor/github.com/theupdateframework/notary/tuf/utils/pkcs8.go @@ -11,7 +11,7 @@ // // The MIT License (MIT) // -// # Copyright (c) 2014 youmark +// Copyright (c) 2014 youmark // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/github.com/urfave/cli/.flake8 b/vendor/github.com/urfave/cli/.flake8 deleted file mode 100644 index 6deafc26..00000000 --- a/vendor/github.com/urfave/cli/.flake8 +++ /dev/null @@ -1,2 +0,0 @@ -[flake8] -max-line-length = 120 diff --git a/vendor/github.com/urfave/cli/.gitignore b/vendor/github.com/urfave/cli/.gitignore deleted file mode 100644 index 9d181200..00000000 --- a/vendor/github.com/urfave/cli/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -*.coverprofile -coverage.txt -node_modules/ -vendor -.idea -/.local/ -/internal/ -/site/ -package.json -package-lock.json diff --git a/vendor/github.com/urfave/cli/CODE_OF_CONDUCT.md b/vendor/github.com/urfave/cli/CODE_OF_CONDUCT.md deleted file mode 100644 index 41ba294f..00000000 --- a/vendor/github.com/urfave/cli/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -education, socio-economic status, nationality, personal appearance, race, -religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or - advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting Dan Buch at dan@meatballhat.com. All complaints will be -reviewed and investigated and will result in a response that is deemed necessary -and appropriate to the circumstances. The project team is obligated to maintain -confidentiality with regard to the reporter of an incident. Further details of -specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html - -[homepage]: https://www.contributor-covenant.org - diff --git a/vendor/github.com/urfave/cli/LICENSE b/vendor/github.com/urfave/cli/LICENSE deleted file mode 100644 index 99d8559d..00000000 --- a/vendor/github.com/urfave/cli/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2023 Jeremy Saenz & Contributors - -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/urfave/cli/README.md b/vendor/github.com/urfave/cli/README.md deleted file mode 100644 index c7dd62bc..00000000 --- a/vendor/github.com/urfave/cli/README.md +++ /dev/null @@ -1,51 +0,0 @@ -cli -=== - -[![Run Tests](https://github.com/urfave/cli/actions/workflows/cli.yml/badge.svg?branch=v1-maint)](https://github.com/urfave/cli/actions/workflows/cli.yml) -[![Go Reference](https://pkg.go.dev/badge/github.com/urfave/cli/.svg)](https://pkg.go.dev/github.com/urfave/cli/) -[![Go Report Card](https://goreportcard.com/badge/urfave/cli)](https://goreportcard.com/report/urfave/cli) -[![codecov](https://codecov.io/gh/urfave/cli/branch/v1-maint/graph/badge.svg)](https://codecov.io/gh/urfave/cli) - -cli is a simple, fast, and fun package for building command line apps in Go. The -goal is to enable developers to write fast and distributable command line -applications in an expressive way. - -## Usage Documentation - -Usage documentation for `v1` is available [at the docs -site](https://cli.urfave.org/v1/getting-started/) or in-tree at -[./docs/v1/manual.md](./docs/v1/manual.md) - -## Installation - -Make sure you have a working Go environment. Go version 1.18+ is supported. - -### Supported platforms - -cli is tested against multiple versions of Go on Linux, and against the latest released -version of Go on OS X and Windows. For full details, see -[./.github/workflows/cli.yml](./.github/workflows/cli.yml). - -### Build tags - -You can use the following build tags: - -#### `urfave_cli_no_docs` - -When set, this removes `ToMarkdown` and `ToMan` methods, so your application -won't be able to call those. This reduces the resulting binary size by about -300-400 KB (measured using Go 1.18.1 on Linux/amd64), due to less dependencies. - -### Using `v1` releases - -``` -$ go get github.com/urfave/cli -``` - -```go -... -import ( - "github.com/urfave/cli" -) -... -``` diff --git a/vendor/github.com/urfave/cli/app.go b/vendor/github.com/urfave/cli/app.go deleted file mode 100644 index df5a9a91..00000000 --- a/vendor/github.com/urfave/cli/app.go +++ /dev/null @@ -1,531 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "io" - "os" - "path/filepath" - "sort" - "time" -) - -var ( - changeLogURL = "https://github.com/urfave/cli/blob/master/CHANGELOG.md" - appActionDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-action-signature", changeLogURL) - // unused variable. commented for now. will remove in future if agreed upon by everyone - //runAndExitOnErrorDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-runandexitonerror", changeLogURL) - - contactSysadmin = "This is an error in the application. Please contact the distributor of this application if this is not you." - - errInvalidActionType = NewExitError("ERROR invalid Action type. "+ - fmt.Sprintf("Must be `func(*Context`)` or `func(*Context) error). %s", contactSysadmin)+ - fmt.Sprintf("See %s", appActionDeprecationURL), 2) -) - -// App is the main structure of a cli application. It is recommended that -// an app be created with the cli.NewApp() function -type App struct { - // The name of the program. Defaults to path.Base(os.Args[0]) - Name string - // Full name of command for help, defaults to Name - HelpName string - // Description of the program. - Usage string - // Text to override the USAGE section of help - UsageText string - // Description of the program argument format. - ArgsUsage string - // Version of the program - Version string - // Description of the program - Description string - // List of commands to execute - Commands []Command - // List of flags to parse - Flags []Flag - // Boolean to enable bash completion commands - EnableBashCompletion bool - // Boolean to hide built-in help command - HideHelp bool - // Boolean to hide built-in version flag and the VERSION section of help - HideVersion bool - // Populate on app startup, only gettable through method Categories() - categories CommandCategories - // An action to execute when the bash-completion flag is set - BashComplete BashCompleteFunc - // An action to execute before any subcommands are run, but after the context is ready - // If a non-nil error is returned, no subcommands are run - Before BeforeFunc - // An action to execute after any subcommands are run, but after the subcommand has finished - // It is run even if Action() panics - After AfterFunc - - // The action to execute when no subcommands are specified - // Expects a `cli.ActionFunc` but will accept the *deprecated* signature of `func(*cli.Context) {}` - // *Note*: support for the deprecated `Action` signature will be removed in a future version - Action interface{} - - // Execute this function if the proper command cannot be found - CommandNotFound CommandNotFoundFunc - // Execute this function if an usage error occurs - OnUsageError OnUsageErrorFunc - // Compilation date - Compiled time.Time - // List of all authors who contributed - Authors []Author - // Copyright of the binary if any - Copyright string - // Name of Author (Note: Use App.Authors, this is deprecated) - Author string - // Email of Author (Note: Use App.Authors, this is deprecated) - Email string - // Writer writer to write output to - Writer io.Writer - // ErrWriter writes error output - ErrWriter io.Writer - // Execute this function to handle ExitErrors. If not provided, HandleExitCoder is provided to - // function as a default, so this is optional. - ExitErrHandler ExitErrHandlerFunc - // Other custom info - Metadata map[string]interface{} - // Carries a function which returns app specific info. - ExtraInfo func() map[string]string - // CustomAppHelpTemplate the text template for app help topic. - // cli.go uses text/template to render templates. You can - // render custom help text by setting this variable. - CustomAppHelpTemplate string - // Boolean to enable short-option handling so user can combine several - // single-character bool arguements into one - // i.e. foobar -o -v -> foobar -ov - UseShortOptionHandling bool - - didSetup bool -} - -// Tries to find out when this binary was compiled. -// Returns the current time if it fails to find it. -func compileTime() time.Time { - info, err := os.Stat(os.Args[0]) - if err != nil { - return time.Now() - } - return info.ModTime() -} - -// NewApp creates a new cli Application with some reasonable defaults for Name, -// Usage, Version and Action. -func NewApp() *App { - return &App{ - Name: filepath.Base(os.Args[0]), - HelpName: filepath.Base(os.Args[0]), - Usage: "A new cli application", - UsageText: "", - BashComplete: DefaultAppComplete, - Action: helpCommand.Action, - Compiled: compileTime(), - Writer: os.Stdout, - } -} - -// Setup runs initialization code to ensure all data structures are ready for -// `Run` or inspection prior to `Run`. It is internally called by `Run`, but -// will return early if setup has already happened. -func (a *App) Setup() { - if a.didSetup { - return - } - - a.didSetup = true - - if a.Author != "" || a.Email != "" { - a.Authors = append(a.Authors, Author{Name: a.Author, Email: a.Email}) - } - - var newCmds []Command - for _, c := range a.Commands { - if c.HelpName == "" { - c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name) - } - newCmds = append(newCmds, c) - } - a.Commands = newCmds - - if a.Command(helpCommand.Name) == nil && !a.HideHelp { - a.Commands = append(a.Commands, helpCommand) - if (HelpFlag != BoolFlag{}) { - a.appendFlag(HelpFlag) - } - } - - if a.Version == "" { - a.HideVersion = true - } - - if !a.HideVersion { - a.appendFlag(VersionFlag) - } - - a.categories = CommandCategories{} - for _, command := range a.Commands { - a.categories = a.categories.AddCommand(command.Category, command) - } - sort.Sort(a.categories) - - if a.Metadata == nil { - a.Metadata = make(map[string]interface{}) - } - - if a.Writer == nil { - a.Writer = os.Stdout - } -} - -func (a *App) newFlagSet() (*flag.FlagSet, error) { - return flagSet(a.Name, a.Flags) -} - -func (a *App) useShortOptionHandling() bool { - return a.UseShortOptionHandling -} - -// Run is the entry point to the cli app. Parses the arguments slice and routes -// to the proper flag/args combination -func (a *App) Run(arguments []string) (err error) { - a.Setup() - - // handle the completion flag separately from the flagset since - // completion could be attempted after a flag, but before its value was put - // on the command line. this causes the flagset to interpret the completion - // flag name as the value of the flag before it which is undesirable - // note that we can only do this because the shell autocomplete function - // always appends the completion flag at the end of the command - shellComplete, arguments := checkShellCompleteFlag(a, arguments) - - set, err := a.newFlagSet() - if err != nil { - return err - } - - err = parseIter(set, a, arguments[1:], shellComplete) - nerr := normalizeFlags(a.Flags, set) - context := NewContext(a, set, nil) - if nerr != nil { - _, _ = fmt.Fprintln(a.Writer, nerr) - _ = ShowAppHelp(context) - return nerr - } - context.shellComplete = shellComplete - - if checkCompletions(context) { - return nil - } - - if err != nil { - if a.OnUsageError != nil { - err := a.OnUsageError(context, err, false) - a.handleExitCoder(context, err) - return err - } - _, _ = fmt.Fprintf(a.Writer, "%s %s\n\n", "Incorrect Usage.", err.Error()) - _ = ShowAppHelp(context) - return err - } - - if !a.HideHelp && checkHelp(context) { - _ = ShowAppHelp(context) - return nil - } - - if !a.HideVersion && checkVersion(context) { - ShowVersion(context) - return nil - } - - cerr := checkRequiredFlags(a.Flags, context) - if cerr != nil { - _ = ShowAppHelp(context) - return cerr - } - - if a.After != nil && !context.shellComplete { - defer func() { - if afterErr := a.After(context); afterErr != nil { - if err != nil { - err = NewMultiError(err, afterErr) - } else { - err = afterErr - } - } - }() - } - - if a.Before != nil && !context.shellComplete { - beforeErr := a.Before(context) - if beforeErr != nil { - a.handleExitCoder(context, beforeErr) - err = beforeErr - return err - } - } - - args := context.Args() - if args.Present() { - name := args.First() - c := a.Command(name) - if c != nil { - return c.Run(context) - } - } - - if a.Action == nil { - a.Action = helpCommand.Action - } - - // Run default Action - err = HandleAction(a.Action, context) - - a.handleExitCoder(context, err) - return err -} - -// RunAndExitOnError calls .Run() and exits non-zero if an error was returned -// -// Deprecated: instead you should return an error that fulfills cli.ExitCoder -// to cli.App.Run. This will cause the application to exit with the given eror -// code in the cli.ExitCoder -func (a *App) RunAndExitOnError() { - if err := a.Run(os.Args); err != nil { - _, _ = fmt.Fprintln(a.errWriter(), err) - OsExiter(1) - } -} - -// RunAsSubcommand invokes the subcommand given the context, parses ctx.Args() to -// generate command-specific flags -func (a *App) RunAsSubcommand(ctx *Context) (err error) { - // append help to commands - if len(a.Commands) > 0 { - if a.Command(helpCommand.Name) == nil && !a.HideHelp { - a.Commands = append(a.Commands, helpCommand) - if (HelpFlag != BoolFlag{}) { - a.appendFlag(HelpFlag) - } - } - } - - newCmds := []Command{} - for _, c := range a.Commands { - if c.HelpName == "" { - c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name) - } - newCmds = append(newCmds, c) - } - a.Commands = newCmds - - set, err := a.newFlagSet() - if err != nil { - return err - } - - err = parseIter(set, a, ctx.Args().Tail(), ctx.shellComplete) - nerr := normalizeFlags(a.Flags, set) - context := NewContext(a, set, ctx) - - if nerr != nil { - _, _ = fmt.Fprintln(a.Writer, nerr) - _, _ = fmt.Fprintln(a.Writer) - if len(a.Commands) > 0 { - _ = ShowSubcommandHelp(context) - } else { - _ = ShowCommandHelp(ctx, context.Args().First()) - } - return nerr - } - - if checkCompletions(context) { - return nil - } - - if err != nil { - if a.OnUsageError != nil { - err = a.OnUsageError(context, err, true) - a.handleExitCoder(context, err) - return err - } - _, _ = fmt.Fprintf(a.Writer, "%s %s\n\n", "Incorrect Usage.", err.Error()) - _ = ShowSubcommandHelp(context) - return err - } - - if len(a.Commands) > 0 { - if checkSubcommandHelp(context) { - return nil - } - } else { - if checkCommandHelp(ctx, context.Args().First()) { - return nil - } - } - - cerr := checkRequiredFlags(a.Flags, context) - if cerr != nil { - _ = ShowSubcommandHelp(context) - return cerr - } - - if a.After != nil && !context.shellComplete { - defer func() { - afterErr := a.After(context) - if afterErr != nil { - a.handleExitCoder(context, err) - if err != nil { - err = NewMultiError(err, afterErr) - } else { - err = afterErr - } - } - }() - } - - if a.Before != nil && !context.shellComplete { - beforeErr := a.Before(context) - if beforeErr != nil { - a.handleExitCoder(context, beforeErr) - err = beforeErr - return err - } - } - - args := context.Args() - if args.Present() { - name := args.First() - c := a.Command(name) - if c != nil { - return c.Run(context) - } - } - - // Run default Action - err = HandleAction(a.Action, context) - - a.handleExitCoder(context, err) - return err -} - -// Command returns the named command on App. Returns nil if the command does not exist -func (a *App) Command(name string) *Command { - for _, c := range a.Commands { - if c.HasName(name) { - return &c - } - } - - return nil -} - -// Categories returns a slice containing all the categories with the commands they contain -func (a *App) Categories() CommandCategories { - return a.categories -} - -// VisibleCategories returns a slice of categories and commands that are -// Hidden=false -func (a *App) VisibleCategories() []*CommandCategory { - ret := []*CommandCategory{} - for _, category := range a.categories { - if visible := func() *CommandCategory { - for _, command := range category.Commands { - if !command.Hidden { - return category - } - } - return nil - }(); visible != nil { - ret = append(ret, visible) - } - } - return ret -} - -// VisibleCommands returns a slice of the Commands with Hidden=false -func (a *App) VisibleCommands() []Command { - var ret []Command - for _, command := range a.Commands { - if !command.Hidden { - ret = append(ret, command) - } - } - return ret -} - -// VisibleFlags returns a slice of the Flags with Hidden=false -func (a *App) VisibleFlags() []Flag { - return visibleFlags(a.Flags) -} - -func (a *App) hasFlag(flag Flag) bool { - for _, f := range a.Flags { - if flag == f { - return true - } - } - - return false -} - -func (a *App) errWriter() io.Writer { - // When the app ErrWriter is nil use the package level one. - if a.ErrWriter == nil { - return ErrWriter - } - - return a.ErrWriter -} - -func (a *App) appendFlag(flag Flag) { - if !a.hasFlag(flag) { - a.Flags = append(a.Flags, flag) - } -} - -func (a *App) handleExitCoder(context *Context, err error) { - if a.ExitErrHandler != nil { - a.ExitErrHandler(context, err) - } else { - HandleExitCoder(err) - } -} - -// Author represents someone who has contributed to a cli project. -type Author struct { - Name string // The Authors name - Email string // The Authors email -} - -// String makes Author comply to the Stringer interface, to allow an easy print in the templating process -func (a Author) String() string { - e := "" - if a.Email != "" { - e = " <" + a.Email + ">" - } - - return fmt.Sprintf("%v%v", a.Name, e) -} - -// HandleAction attempts to figure out which Action signature was used. If -// it's an ActionFunc or a func with the legacy signature for Action, the func -// is run! -func HandleAction(action interface{}, context *Context) (err error) { - switch a := action.(type) { - case ActionFunc: - return a(context) - case func(*Context) error: - return a(context) - case func(*Context): // deprecated function signature - a(context) - return nil - } - - return errInvalidActionType -} diff --git a/vendor/github.com/urfave/cli/category.go b/vendor/github.com/urfave/cli/category.go deleted file mode 100644 index bf3c73c5..00000000 --- a/vendor/github.com/urfave/cli/category.go +++ /dev/null @@ -1,44 +0,0 @@ -package cli - -// CommandCategories is a slice of *CommandCategory. -type CommandCategories []*CommandCategory - -// CommandCategory is a category containing commands. -type CommandCategory struct { - Name string - Commands Commands -} - -func (c CommandCategories) Less(i, j int) bool { - return lexicographicLess(c[i].Name, c[j].Name) -} - -func (c CommandCategories) Len() int { - return len(c) -} - -func (c CommandCategories) Swap(i, j int) { - c[i], c[j] = c[j], c[i] -} - -// AddCommand adds a command to a category. -func (c CommandCategories) AddCommand(category string, command Command) CommandCategories { - for _, commandCategory := range c { - if commandCategory.Name == category { - commandCategory.Commands = append(commandCategory.Commands, command) - return c - } - } - return append(c, &CommandCategory{Name: category, Commands: []Command{command}}) -} - -// VisibleCommands returns a slice of the Commands with Hidden=false -func (c *CommandCategory) VisibleCommands() []Command { - ret := []Command{} - for _, command := range c.Commands { - if !command.Hidden { - ret = append(ret, command) - } - } - return ret -} diff --git a/vendor/github.com/urfave/cli/cli.go b/vendor/github.com/urfave/cli/cli.go deleted file mode 100644 index ab87079e..00000000 --- a/vendor/github.com/urfave/cli/cli.go +++ /dev/null @@ -1,24 +0,0 @@ -// Package cli provides a minimal framework for creating and organizing command line -// Go applications. cli is designed to be easy to understand and write, the most simple -// cli application can be written as follows: -// -// func main() { -// cli.NewApp().Run(os.Args) -// } -// -// Of course this application does not do much, so let's make this an actual application: -// -// func main() { -// app := cli.NewApp() -// app.Name = "greet" -// app.Usage = "say a greeting" -// app.Action = func(c *cli.Context) error { -// println("Greetings") -// return nil -// } -// -// app.Run(os.Args) -// } -package cli - -//go:generate go run flag-gen/main.go flag-gen/assets_vfsdata.go diff --git a/vendor/github.com/urfave/cli/command.go b/vendor/github.com/urfave/cli/command.go deleted file mode 100644 index 6c2f9cad..00000000 --- a/vendor/github.com/urfave/cli/command.go +++ /dev/null @@ -1,386 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "sort" - "strings" -) - -// Command is a subcommand for a cli.App. -type Command struct { - // The name of the command - Name string - // short name of the command. Typically one character (deprecated, use `Aliases`) - ShortName string - // A list of aliases for the command - Aliases []string - // A short description of the usage of this command - Usage string - // Custom text to show on USAGE section of help - UsageText string - // A longer explanation of how the command works - Description string - // A short description of the arguments of this command - ArgsUsage string - // The category the command is part of - Category string - // The function to call when checking for bash command completions - BashComplete BashCompleteFunc - // An action to execute before any sub-subcommands are run, but after the context is ready - // If a non-nil error is returned, no sub-subcommands are run - Before BeforeFunc - // An action to execute after any subcommands are run, but after the subcommand has finished - // It is run even if Action() panics - After AfterFunc - // The function to call when this command is invoked - Action interface{} - // TODO: replace `Action: interface{}` with `Action: ActionFunc` once some kind - // of deprecation period has passed, maybe? - - // Execute this function if a usage error occurs. - OnUsageError OnUsageErrorFunc - // List of child commands - Subcommands Commands - // List of flags to parse - Flags []Flag - // Treat all flags as normal arguments if true - SkipFlagParsing bool - // Skip argument reordering which attempts to move flags before arguments, - // but only works if all flags appear after all arguments. This behavior was - // removed n version 2 since it only works under specific conditions so we - // backport here by exposing it as an option for compatibility. - SkipArgReorder bool - // Boolean to hide built-in help command - HideHelp bool - // Boolean to hide this command from help or completion - Hidden bool - // Boolean to enable short-option handling so user can combine several - // single-character bool arguments into one - // i.e. foobar -o -v -> foobar -ov - UseShortOptionHandling bool - - // Full name of command for help, defaults to full command name, including parent commands. - HelpName string - commandNamePath []string - - // CustomHelpTemplate the text template for the command help topic. - // cli.go uses text/template to render templates. You can - // render custom help text by setting this variable. - CustomHelpTemplate string -} - -type CommandsByName []Command - -func (c CommandsByName) Len() int { - return len(c) -} - -func (c CommandsByName) Less(i, j int) bool { - return lexicographicLess(c[i].Name, c[j].Name) -} - -func (c CommandsByName) Swap(i, j int) { - c[i], c[j] = c[j], c[i] -} - -// FullName returns the full name of the command. -// For subcommands this ensures that parent commands are part of the command path -func (c Command) FullName() string { - if c.commandNamePath == nil { - return c.Name - } - return strings.Join(c.commandNamePath, " ") -} - -// Commands is a slice of Command -type Commands []Command - -// Run invokes the command given the context, parses ctx.Args() to generate command-specific flags -func (c Command) Run(ctx *Context) (err error) { - if !c.SkipFlagParsing { - if len(c.Subcommands) > 0 { - return c.startApp(ctx) - } - } - - if !c.HideHelp && (HelpFlag != BoolFlag{}) { - // append help to flags - c.Flags = append( - c.Flags, - HelpFlag, - ) - } - - if ctx.App.UseShortOptionHandling { - c.UseShortOptionHandling = true - } - - set, err := c.parseFlags(ctx.Args().Tail(), ctx.shellComplete) - - context := NewContext(ctx.App, set, ctx) - context.Command = c - if checkCommandCompletions(context, c.Name) { - return nil - } - - if err != nil { - if c.OnUsageError != nil { - err := c.OnUsageError(context, err, false) - context.App.handleExitCoder(context, err) - return err - } - _, _ = fmt.Fprintln(context.App.Writer, "Incorrect Usage:", err.Error()) - _, _ = fmt.Fprintln(context.App.Writer) - _ = ShowCommandHelp(context, c.Name) - return err - } - - if checkCommandHelp(context, c.Name) { - return nil - } - - cerr := checkRequiredFlags(c.Flags, context) - if cerr != nil { - _ = ShowCommandHelp(context, c.Name) - return cerr - } - - if c.After != nil { - defer func() { - afterErr := c.After(context) - if afterErr != nil { - context.App.handleExitCoder(context, err) - if err != nil { - err = NewMultiError(err, afterErr) - } else { - err = afterErr - } - } - }() - } - - if c.Before != nil { - err = c.Before(context) - if err != nil { - context.App.handleExitCoder(context, err) - return err - } - } - - if c.Action == nil { - c.Action = helpSubcommand.Action - } - - err = HandleAction(c.Action, context) - - if err != nil { - context.App.handleExitCoder(context, err) - } - return err -} - -func (c *Command) parseFlags(args Args, shellComplete bool) (*flag.FlagSet, error) { - if c.SkipFlagParsing { - set, err := c.newFlagSet() - if err != nil { - return nil, err - } - - return set, set.Parse(append([]string{"--"}, args...)) - } - - if !c.SkipArgReorder { - args = reorderArgs(c.Flags, args) - } - - set, err := c.newFlagSet() - if err != nil { - return nil, err - } - - err = parseIter(set, c, args, shellComplete) - if err != nil { - return nil, err - } - - err = normalizeFlags(c.Flags, set) - if err != nil { - return nil, err - } - - return set, nil -} - -func (c *Command) newFlagSet() (*flag.FlagSet, error) { - return flagSet(c.Name, c.Flags) -} - -func (c *Command) useShortOptionHandling() bool { - return c.UseShortOptionHandling -} - -// reorderArgs moves all flags (via reorderedArgs) before the rest of -// the arguments (remainingArgs) as this is what flag expects. -func reorderArgs(commandFlags []Flag, args []string) []string { - var remainingArgs, reorderedArgs []string - - nextIndexMayContainValue := false - for i, arg := range args { - - // if we're expecting an option-value, check if this arg is a value, in - // which case it should be re-ordered next to its associated flag - if nextIndexMayContainValue && !argIsFlag(commandFlags, arg) { - nextIndexMayContainValue = false - reorderedArgs = append(reorderedArgs, arg) - } else if arg == "--" { - // don't reorder any args after the -- delimiter As described in the POSIX spec: - // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html#tag_12_02 - // > Guideline 10: - // > The first -- argument that is not an option-argument should be accepted - // > as a delimiter indicating the end of options. Any following arguments - // > should be treated as operands, even if they begin with the '-' character. - - // make sure the "--" delimiter itself is at the start - remainingArgs = append([]string{"--"}, remainingArgs...) - remainingArgs = append(remainingArgs, args[i+1:]...) - break - // checks if this is an arg that should be re-ordered - } else if argIsFlag(commandFlags, arg) { - // we have determined that this is a flag that we should re-order - reorderedArgs = append(reorderedArgs, arg) - // if this arg does not contain a "=", then the next index may contain the value for this flag - nextIndexMayContainValue = !strings.Contains(arg, "=") - - // simply append any remaining args - } else { - remainingArgs = append(remainingArgs, arg) - } - } - - return append(reorderedArgs, remainingArgs...) -} - -// argIsFlag checks if an arg is one of our command flags -func argIsFlag(commandFlags []Flag, arg string) bool { - if arg == "-" || arg == "--" { - // `-` is never a flag - // `--` is an option-value when following a flag, and a delimiter indicating the end of options in other cases. - return false - } - // flags always start with a - - if !strings.HasPrefix(arg, "-") { - return false - } - // this line turns `--flag` into `flag` - if strings.HasPrefix(arg, "--") { - arg = strings.Replace(arg, "-", "", 2) - } - // this line turns `-flag` into `flag` - if strings.HasPrefix(arg, "-") { - arg = strings.Replace(arg, "-", "", 1) - } - // this line turns `flag=value` into `flag` - arg = strings.Split(arg, "=")[0] - // look through all the flags, to see if the `arg` is one of our flags - for _, flag := range commandFlags { - for _, key := range strings.Split(flag.GetName(), ",") { - key := strings.TrimSpace(key) - if key == arg { - return true - } - } - } - // return false if this arg was not one of our flags - return false -} - -// Names returns the names including short names and aliases. -func (c Command) Names() []string { - names := []string{c.Name} - - if c.ShortName != "" { - names = append(names, c.ShortName) - } - - return append(names, c.Aliases...) -} - -// HasName returns true if Command.Name or Command.ShortName matches given name -func (c Command) HasName(name string) bool { - for _, n := range c.Names() { - if n == name { - return true - } - } - return false -} - -func (c Command) startApp(ctx *Context) error { - app := NewApp() - app.Metadata = ctx.App.Metadata - app.ExitErrHandler = ctx.App.ExitErrHandler - // set the name and usage - app.Name = fmt.Sprintf("%s %s", ctx.App.Name, c.Name) - if c.HelpName == "" { - app.HelpName = c.HelpName - } else { - app.HelpName = app.Name - } - - app.Usage = c.Usage - app.Description = c.Description - app.ArgsUsage = c.ArgsUsage - - // set CommandNotFound - app.CommandNotFound = ctx.App.CommandNotFound - app.CustomAppHelpTemplate = c.CustomHelpTemplate - - // set the flags and commands - app.Commands = c.Subcommands - app.Flags = c.Flags - app.HideHelp = c.HideHelp - - app.Version = ctx.App.Version - app.HideVersion = ctx.App.HideVersion - app.Compiled = ctx.App.Compiled - app.Author = ctx.App.Author - app.Email = ctx.App.Email - app.Writer = ctx.App.Writer - app.ErrWriter = ctx.App.ErrWriter - app.UseShortOptionHandling = ctx.App.UseShortOptionHandling - - app.categories = CommandCategories{} - for _, command := range c.Subcommands { - app.categories = app.categories.AddCommand(command.Category, command) - } - - sort.Sort(app.categories) - - // bash completion - app.EnableBashCompletion = ctx.App.EnableBashCompletion - if c.BashComplete != nil { - app.BashComplete = c.BashComplete - } - - // set the actions - app.Before = c.Before - app.After = c.After - if c.Action != nil { - app.Action = c.Action - } else { - app.Action = helpSubcommand.Action - } - app.OnUsageError = c.OnUsageError - - for index, cc := range app.Commands { - app.Commands[index].commandNamePath = []string{c.Name, cc.Name} - } - - return app.RunAsSubcommand(ctx) -} - -// VisibleFlags returns a slice of the Flags with Hidden=false -func (c Command) VisibleFlags() []Flag { - return visibleFlags(c.Flags) -} diff --git a/vendor/github.com/urfave/cli/context.go b/vendor/github.com/urfave/cli/context.go deleted file mode 100644 index 3adf37e7..00000000 --- a/vendor/github.com/urfave/cli/context.go +++ /dev/null @@ -1,348 +0,0 @@ -package cli - -import ( - "errors" - "flag" - "fmt" - "os" - "reflect" - "strings" - "syscall" -) - -// Context is a type that is passed through to -// each Handler action in a cli application. Context -// can be used to retrieve context-specific Args and -// parsed command-line options. -type Context struct { - App *App - Command Command - shellComplete bool - flagSet *flag.FlagSet - setFlags map[string]bool - parentContext *Context -} - -// NewContext creates a new context. For use in when invoking an App or Command action. -func NewContext(app *App, set *flag.FlagSet, parentCtx *Context) *Context { - c := &Context{App: app, flagSet: set, parentContext: parentCtx} - - if parentCtx != nil { - c.shellComplete = parentCtx.shellComplete - } - - return c -} - -// NumFlags returns the number of flags set -func (c *Context) NumFlags() int { - return c.flagSet.NFlag() -} - -// Set sets a context flag to a value. -func (c *Context) Set(name, value string) error { - c.setFlags = nil - return c.flagSet.Set(name, value) -} - -// GlobalSet sets a context flag to a value on the global flagset -func (c *Context) GlobalSet(name, value string) error { - globalContext(c).setFlags = nil - return globalContext(c).flagSet.Set(name, value) -} - -// IsSet determines if the flag was actually set -func (c *Context) IsSet(name string) bool { - if c.setFlags == nil { - c.setFlags = make(map[string]bool) - - c.flagSet.Visit(func(f *flag.Flag) { - c.setFlags[f.Name] = true - }) - - c.flagSet.VisitAll(func(f *flag.Flag) { - if _, ok := c.setFlags[f.Name]; ok { - return - } - c.setFlags[f.Name] = false - }) - - // XXX hack to support IsSet for flags with EnvVar - // - // There isn't an easy way to do this with the current implementation since - // whether a flag was set via an environment variable is very difficult to - // determine here. Instead, we intend to introduce a backwards incompatible - // change in version 2 to add `IsSet` to the Flag interface to push the - // responsibility closer to where the information required to determine - // whether a flag is set by non-standard means such as environment - // variables is available. - // - // See https://github.com/urfave/cli/issues/294 for additional discussion - flags := c.Command.Flags - if c.Command.Name == "" { // cannot == Command{} since it contains slice types - if c.App != nil { - flags = c.App.Flags - } - } - for _, f := range flags { - eachName(f.GetName(), func(name string) { - if isSet, ok := c.setFlags[name]; isSet || !ok { - // Check if a flag is set - if isSet { - // If the flag is set, also set its other aliases - eachName(f.GetName(), func(name string) { - c.setFlags[name] = true - }) - } - - return - } - - val := reflect.ValueOf(f) - if val.Kind() == reflect.Ptr { - val = val.Elem() - } - - filePathValue := val.FieldByName("FilePath") - if filePathValue.IsValid() { - eachName(filePathValue.String(), func(filePath string) { - if _, err := os.Stat(filePath); err == nil { - c.setFlags[name] = true - return - } - }) - } - - envVarValue := val.FieldByName("EnvVar") - if envVarValue.IsValid() { - eachName(envVarValue.String(), func(envVar string) { - envVar = strings.TrimSpace(envVar) - if _, ok := syscall.Getenv(envVar); ok { - c.setFlags[name] = true - return - } - }) - } - }) - } - } - - return c.setFlags[name] -} - -// GlobalIsSet determines if the global flag was actually set -func (c *Context) GlobalIsSet(name string) bool { - ctx := c - if ctx.parentContext != nil { - ctx = ctx.parentContext - } - - for ; ctx != nil; ctx = ctx.parentContext { - if ctx.IsSet(name) { - return true - } - } - return false -} - -// FlagNames returns a slice of flag names used in this context. -func (c *Context) FlagNames() (names []string) { - for _, f := range c.Command.Flags { - name := strings.Split(f.GetName(), ",")[0] - if name == "help" { - continue - } - names = append(names, name) - } - return -} - -// GlobalFlagNames returns a slice of global flag names used by the app. -func (c *Context) GlobalFlagNames() (names []string) { - for _, f := range c.App.Flags { - name := strings.Split(f.GetName(), ",")[0] - if name == "help" || name == "version" { - continue - } - names = append(names, name) - } - return -} - -// Parent returns the parent context, if any -func (c *Context) Parent() *Context { - return c.parentContext -} - -// value returns the value of the flag coressponding to `name` -func (c *Context) value(name string) interface{} { - return c.flagSet.Lookup(name).Value.(flag.Getter).Get() -} - -// Args contains apps console arguments -type Args []string - -// Args returns the command line arguments associated with the context. -func (c *Context) Args() Args { - args := Args(c.flagSet.Args()) - return args -} - -// NArg returns the number of the command line arguments. -func (c *Context) NArg() int { - return len(c.Args()) -} - -// Get returns the nth argument, or else a blank string -func (a Args) Get(n int) string { - if len(a) > n { - return a[n] - } - return "" -} - -// First returns the first argument, or else a blank string -func (a Args) First() string { - return a.Get(0) -} - -// Tail returns the rest of the arguments (not the first one) -// or else an empty string slice -func (a Args) Tail() []string { - if len(a) >= 2 { - return []string(a)[1:] - } - return []string{} -} - -// Present checks if there are any arguments present -func (a Args) Present() bool { - return len(a) != 0 -} - -// Swap swaps arguments at the given indexes -func (a Args) Swap(from, to int) error { - if from >= len(a) || to >= len(a) { - return errors.New("index out of range") - } - a[from], a[to] = a[to], a[from] - return nil -} - -func globalContext(ctx *Context) *Context { - if ctx == nil { - return nil - } - - for { - if ctx.parentContext == nil { - return ctx - } - ctx = ctx.parentContext - } -} - -func lookupGlobalFlagSet(name string, ctx *Context) *flag.FlagSet { - if ctx.parentContext != nil { - ctx = ctx.parentContext - } - for ; ctx != nil; ctx = ctx.parentContext { - if f := ctx.flagSet.Lookup(name); f != nil { - return ctx.flagSet - } - } - return nil -} - -func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) { - switch ff.Value.(type) { - case *StringSlice: - default: - _ = set.Set(name, ff.Value.String()) - } -} - -func normalizeFlags(flags []Flag, set *flag.FlagSet) error { - visited := make(map[string]bool) - set.Visit(func(f *flag.Flag) { - visited[f.Name] = true - }) - for _, f := range flags { - parts := strings.Split(f.GetName(), ",") - if len(parts) == 1 { - continue - } - var ff *flag.Flag - for _, name := range parts { - name = strings.Trim(name, " ") - if visited[name] { - if ff != nil { - return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name) - } - ff = set.Lookup(name) - } - } - if ff == nil { - continue - } - for _, name := range parts { - name = strings.Trim(name, " ") - if !visited[name] { - copyFlag(name, ff, set) - } - } - } - return nil -} - -type requiredFlagsErr interface { - error - getMissingFlags() []string -} - -type errRequiredFlags struct { - missingFlags []string -} - -func (e *errRequiredFlags) Error() string { - numberOfMissingFlags := len(e.missingFlags) - if numberOfMissingFlags == 1 { - return fmt.Sprintf("Required flag %q not set", e.missingFlags[0]) - } - joinedMissingFlags := strings.Join(e.missingFlags, ", ") - return fmt.Sprintf("Required flags %q not set", joinedMissingFlags) -} - -func (e *errRequiredFlags) getMissingFlags() []string { - return e.missingFlags -} - -func checkRequiredFlags(flags []Flag, context *Context) requiredFlagsErr { - var missingFlags []string - for _, f := range flags { - if rf, ok := f.(RequiredFlag); ok && rf.IsRequired() { - var flagPresent bool - var flagName string - for _, key := range strings.Split(f.GetName(), ",") { - key = strings.TrimSpace(key) - if len(key) > 1 { - flagName = key - } - - if context.IsSet(key) { - flagPresent = true - } - } - - if !flagPresent && flagName != "" { - missingFlags = append(missingFlags, flagName) - } - } - } - - if len(missingFlags) != 0 { - return &errRequiredFlags{missingFlags: missingFlags} - } - - return nil -} diff --git a/vendor/github.com/urfave/cli/docs.go b/vendor/github.com/urfave/cli/docs.go deleted file mode 100644 index 725fa7ff..00000000 --- a/vendor/github.com/urfave/cli/docs.go +++ /dev/null @@ -1,151 +0,0 @@ -//go:build !urfave_cli_no_docs -// +build !urfave_cli_no_docs - -package cli - -import ( - "bytes" - "fmt" - "io" - "sort" - "strings" - "text/template" - - "github.com/cpuguy83/go-md2man/v2/md2man" -) - -// ToMarkdown creates a markdown string for the `*App` -// The function errors if either parsing or writing of the string fails. -func (a *App) ToMarkdown() (string, error) { - var w bytes.Buffer - if err := a.writeDocTemplate(&w); err != nil { - return "", err - } - return w.String(), nil -} - -// ToMan creates a man page string for the `*App` -// The function errors if either parsing or writing of the string fails. -func (a *App) ToMan() (string, error) { - var w bytes.Buffer - if err := a.writeDocTemplate(&w); err != nil { - return "", err - } - man := md2man.Render(w.Bytes()) - return string(man), nil -} - -type cliTemplate struct { - App *App - Commands []string - GlobalArgs []string - SynopsisArgs []string -} - -func (a *App) writeDocTemplate(w io.Writer) error { - const name = "cli" - t, err := template.New(name).Parse(MarkdownDocTemplate) - if err != nil { - return err - } - return t.ExecuteTemplate(w, name, &cliTemplate{ - App: a, - Commands: prepareCommands(a.Commands, 0), - GlobalArgs: prepareArgsWithValues(a.Flags), - SynopsisArgs: prepareArgsSynopsis(a.Flags), - }) -} - -func prepareCommands(commands []Command, level int) []string { - coms := []string{} - for i := range commands { - command := &commands[i] - if command.Hidden { - continue - } - usage := "" - if command.Usage != "" { - usage = command.Usage - } - - prepared := fmt.Sprintf("%s %s\n\n%s\n", - strings.Repeat("#", level+2), - strings.Join(command.Names(), ", "), - usage, - ) - - flags := prepareArgsWithValues(command.Flags) - if len(flags) > 0 { - prepared += fmt.Sprintf("\n%s", strings.Join(flags, "\n")) - } - - coms = append(coms, prepared) - - // recursevly iterate subcommands - if len(command.Subcommands) > 0 { - coms = append( - coms, - prepareCommands(command.Subcommands, level+1)..., - ) - } - } - - return coms -} - -func prepareArgsWithValues(flags []Flag) []string { - return prepareFlags(flags, ", ", "**", "**", `""`, true) -} - -func prepareArgsSynopsis(flags []Flag) []string { - return prepareFlags(flags, "|", "[", "]", "[value]", false) -} - -func prepareFlags( - flags []Flag, - sep, opener, closer, value string, - addDetails bool, -) []string { - args := []string{} - for _, f := range flags { - flag, ok := f.(DocGenerationFlag) - if !ok { - continue - } - modifiedArg := opener - for _, s := range strings.Split(flag.GetName(), ",") { - trimmed := strings.TrimSpace(s) - if len(modifiedArg) > len(opener) { - modifiedArg += sep - } - if len(trimmed) > 1 { - modifiedArg += fmt.Sprintf("--%s", trimmed) - } else { - modifiedArg += fmt.Sprintf("-%s", trimmed) - } - } - modifiedArg += closer - if flag.TakesValue() { - modifiedArg += fmt.Sprintf("=%s", value) - } - - if addDetails { - modifiedArg += flagDetails(flag) - } - - args = append(args, modifiedArg+"\n") - - } - sort.Strings(args) - return args -} - -// flagDetails returns a string containing the flags metadata -func flagDetails(flag DocGenerationFlag) string { - description := flag.GetUsage() - value := flag.GetValue() - if value != "" { - description += " (default: " + value + ")" - } - return ": " + description -} diff --git a/vendor/github.com/urfave/cli/errors.go b/vendor/github.com/urfave/cli/errors.go deleted file mode 100644 index 562b2953..00000000 --- a/vendor/github.com/urfave/cli/errors.go +++ /dev/null @@ -1,115 +0,0 @@ -package cli - -import ( - "fmt" - "io" - "os" - "strings" -) - -// OsExiter is the function used when the app exits. If not set defaults to os.Exit. -var OsExiter = os.Exit - -// ErrWriter is used to write errors to the user. This can be anything -// implementing the io.Writer interface and defaults to os.Stderr. -var ErrWriter io.Writer = os.Stderr - -// MultiError is an error that wraps multiple errors. -type MultiError struct { - Errors []error -} - -// NewMultiError creates a new MultiError. Pass in one or more errors. -func NewMultiError(err ...error) MultiError { - return MultiError{Errors: err} -} - -// Error implements the error interface. -func (m MultiError) Error() string { - errs := make([]string, len(m.Errors)) - for i, err := range m.Errors { - errs[i] = err.Error() - } - - return strings.Join(errs, "\n") -} - -type ErrorFormatter interface { - Format(s fmt.State, verb rune) -} - -// ExitCoder is the interface checked by `App` and `Command` for a custom exit -// code -type ExitCoder interface { - error - ExitCode() int -} - -// ExitError fulfills both the builtin `error` interface and `ExitCoder` -type ExitError struct { - exitCode int - message interface{} -} - -// NewExitError makes a new *ExitError -func NewExitError(message interface{}, exitCode int) *ExitError { - return &ExitError{ - exitCode: exitCode, - message: message, - } -} - -// Error returns the string message, fulfilling the interface required by -// `error` -func (ee *ExitError) Error() string { - return fmt.Sprintf("%v", ee.message) -} - -// ExitCode returns the exit code, fulfilling the interface required by -// `ExitCoder` -func (ee *ExitError) ExitCode() int { - return ee.exitCode -} - -// HandleExitCoder checks if the error fulfills the ExitCoder interface, and if -// so prints the error to stderr (if it is non-empty) and calls OsExiter with the -// given exit code. If the given error is a MultiError, then this func is -// called on all members of the Errors slice and calls OsExiter with the last exit code. -func HandleExitCoder(err error) { - if err == nil { - return - } - - if exitErr, ok := err.(ExitCoder); ok { - if err.Error() != "" { - if _, ok := exitErr.(ErrorFormatter); ok { - fmt.Fprintf(ErrWriter, "%+v\n", err) - } else { - fmt.Fprintln(ErrWriter, err) - } - } - OsExiter(exitErr.ExitCode()) - return - } - - if multiErr, ok := err.(MultiError); ok { - code := handleMultiError(multiErr) - OsExiter(code) - return - } -} - -func handleMultiError(multiErr MultiError) int { - code := 1 - for _, merr := range multiErr.Errors { - if multiErr2, ok := merr.(MultiError); ok { - code = handleMultiError(multiErr2) - } else { - fmt.Fprintln(ErrWriter, merr) - if exitErr, ok := merr.(ExitCoder); ok { - code = exitErr.ExitCode() - } - } - } - return code -} diff --git a/vendor/github.com/urfave/cli/fish.go b/vendor/github.com/urfave/cli/fish.go deleted file mode 100644 index cf183af6..00000000 --- a/vendor/github.com/urfave/cli/fish.go +++ /dev/null @@ -1,194 +0,0 @@ -package cli - -import ( - "bytes" - "fmt" - "io" - "strings" - "text/template" -) - -// ToFishCompletion creates a fish completion string for the `*App` -// The function errors if either parsing or writing of the string fails. -func (a *App) ToFishCompletion() (string, error) { - var w bytes.Buffer - if err := a.writeFishCompletionTemplate(&w); err != nil { - return "", err - } - return w.String(), nil -} - -type fishCompletionTemplate struct { - App *App - Completions []string - AllCommands []string -} - -func (a *App) writeFishCompletionTemplate(w io.Writer) error { - const name = "cli" - t, err := template.New(name).Parse(FishCompletionTemplate) - if err != nil { - return err - } - allCommands := []string{} - - // Add global flags - completions := a.prepareFishFlags(a.VisibleFlags(), allCommands) - - // Add help flag - if !a.HideHelp { - completions = append( - completions, - a.prepareFishFlags([]Flag{HelpFlag}, allCommands)..., - ) - } - - // Add version flag - if !a.HideVersion { - completions = append( - completions, - a.prepareFishFlags([]Flag{VersionFlag}, allCommands)..., - ) - } - - // Add commands and their flags - completions = append( - completions, - a.prepareFishCommands(a.VisibleCommands(), &allCommands, []string{})..., - ) - - return t.ExecuteTemplate(w, name, &fishCompletionTemplate{ - App: a, - Completions: completions, - AllCommands: allCommands, - }) -} - -func (a *App) prepareFishCommands(commands []Command, allCommands *[]string, previousCommands []string) []string { - completions := []string{} - for i := range commands { - command := &commands[i] - - if command.Hidden { - continue - } - - var completion strings.Builder - completion.WriteString(fmt.Sprintf( - "complete -r -c %s -n '%s' -a '%s'", - a.Name, - a.fishSubcommandHelper(previousCommands), - strings.Join(command.Names(), " "), - )) - - if command.Usage != "" { - completion.WriteString(fmt.Sprintf(" -d '%s'", - escapeSingleQuotes(command.Usage))) - } - - if !command.HideHelp { - completions = append( - completions, - a.prepareFishFlags([]Flag{HelpFlag}, command.Names())..., - ) - } - - *allCommands = append(*allCommands, command.Names()...) - completions = append(completions, completion.String()) - completions = append( - completions, - a.prepareFishFlags(command.Flags, command.Names())..., - ) - - // recursevly iterate subcommands - if len(command.Subcommands) > 0 { - completions = append( - completions, - a.prepareFishCommands( - command.Subcommands, allCommands, command.Names(), - )..., - ) - } - } - - return completions -} - -func (a *App) prepareFishFlags(flags []Flag, previousCommands []string) []string { - completions := []string{} - for _, f := range flags { - flag, ok := f.(DocGenerationFlag) - if !ok { - continue - } - - completion := &strings.Builder{} - completion.WriteString(fmt.Sprintf( - "complete -c %s -n '%s'", - a.Name, - a.fishSubcommandHelper(previousCommands), - )) - - fishAddFileFlag(f, completion) - - for idx, opt := range strings.Split(flag.GetName(), ",") { - if idx == 0 { - completion.WriteString(fmt.Sprintf( - " -l %s", strings.TrimSpace(opt), - )) - } else { - completion.WriteString(fmt.Sprintf( - " -s %s", strings.TrimSpace(opt), - )) - - } - } - - if flag.TakesValue() { - completion.WriteString(" -r") - } - - if flag.GetUsage() != "" { - completion.WriteString(fmt.Sprintf(" -d '%s'", - escapeSingleQuotes(flag.GetUsage()))) - } - - completions = append(completions, completion.String()) - } - - return completions -} - -func fishAddFileFlag(flag Flag, completion *strings.Builder) { - switch f := flag.(type) { - case GenericFlag: - if f.TakesFile { - return - } - case StringFlag: - if f.TakesFile { - return - } - case StringSliceFlag: - if f.TakesFile { - return - } - } - completion.WriteString(" -f") -} - -func (a *App) fishSubcommandHelper(allCommands []string) string { - fishHelper := fmt.Sprintf("__fish_%s_no_subcommand", a.Name) - if len(allCommands) > 0 { - fishHelper = fmt.Sprintf( - "__fish_seen_subcommand_from %s", - strings.Join(allCommands, " "), - ) - } - return fishHelper - -} - -func escapeSingleQuotes(input string) string { - return strings.Replace(input, `'`, `\'`, -1) -} diff --git a/vendor/github.com/urfave/cli/flag.go b/vendor/github.com/urfave/cli/flag.go deleted file mode 100644 index 5b7ae6c3..00000000 --- a/vendor/github.com/urfave/cli/flag.go +++ /dev/null @@ -1,348 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "io/ioutil" - "reflect" - "runtime" - "strconv" - "strings" - "syscall" -) - -const defaultPlaceholder = "value" - -// BashCompletionFlag enables bash-completion for all commands and subcommands -var BashCompletionFlag Flag = BoolFlag{ - Name: "generate-bash-completion", - Hidden: true, -} - -// VersionFlag prints the version for the application -var VersionFlag Flag = BoolFlag{ - Name: "version, v", - Usage: "print the version", -} - -// HelpFlag prints the help for all commands and subcommands -// Set to the zero value (BoolFlag{}) to disable flag -- keeps subcommand -// unless HideHelp is set to true) -var HelpFlag Flag = BoolFlag{ - Name: "help, h", - Usage: "show help", -} - -// FlagStringer converts a flag definition to a string. This is used by help -// to display a flag. -var FlagStringer FlagStringFunc = stringifyFlag - -// FlagNamePrefixer converts a full flag name and its placeholder into the help -// message flag prefix. This is used by the default FlagStringer. -var FlagNamePrefixer FlagNamePrefixFunc = prefixedNames - -// FlagEnvHinter annotates flag help message with the environment variable -// details. This is used by the default FlagStringer. -var FlagEnvHinter FlagEnvHintFunc = withEnvHint - -// FlagFileHinter annotates flag help message with the environment variable -// details. This is used by the default FlagStringer. -var FlagFileHinter FlagFileHintFunc = withFileHint - -// FlagsByName is a slice of Flag. -type FlagsByName []Flag - -func (f FlagsByName) Len() int { - return len(f) -} - -func (f FlagsByName) Less(i, j int) bool { - return lexicographicLess(f[i].GetName(), f[j].GetName()) -} - -func (f FlagsByName) Swap(i, j int) { - f[i], f[j] = f[j], f[i] -} - -// Flag is a common interface related to parsing flags in cli. -// For more advanced flag parsing techniques, it is recommended that -// this interface be implemented. -type Flag interface { - fmt.Stringer - // Apply Flag settings to the given flag set - Apply(*flag.FlagSet) - GetName() string -} - -// RequiredFlag is an interface that allows us to mark flags as required -// it allows flags required flags to be backwards compatible with the Flag interface -type RequiredFlag interface { - Flag - - IsRequired() bool -} - -// DocGenerationFlag is an interface that allows documentation generation for the flag -type DocGenerationFlag interface { - Flag - - // TakesValue returns true if the flag takes a value, otherwise false - TakesValue() bool - - // GetUsage returns the usage string for the flag - GetUsage() string - - // GetValue returns the flags value as string representation and an empty - // string if the flag takes no value at all. - GetValue() string -} - -// errorableFlag is an interface that allows us to return errors during apply -// it allows flags defined in this library to return errors in a fashion backwards compatible -// TODO remove in v2 and modify the existing Flag interface to return errors -type errorableFlag interface { - Flag - - ApplyWithError(*flag.FlagSet) error -} - -func flagSet(name string, flags []Flag) (*flag.FlagSet, error) { - set := flag.NewFlagSet(name, flag.ContinueOnError) - - for _, f := range flags { - //TODO remove in v2 when errorableFlag is removed - if ef, ok := f.(errorableFlag); ok { - if err := ef.ApplyWithError(set); err != nil { - return nil, err - } - } else { - f.Apply(set) - } - } - set.SetOutput(ioutil.Discard) - return set, nil -} - -func eachName(longName string, fn func(string)) { - parts := strings.Split(longName, ",") - for _, name := range parts { - name = strings.Trim(name, " ") - fn(name) - } -} - -func visibleFlags(fl []Flag) []Flag { - var visible []Flag - for _, f := range fl { - field := flagValue(f).FieldByName("Hidden") - if !field.IsValid() || !field.Bool() { - visible = append(visible, f) - } - } - return visible -} - -func prefixFor(name string) (prefix string) { - if len(name) == 1 { - prefix = "-" - } else { - prefix = "--" - } - - return -} - -// Returns the placeholder, if any, and the unquoted usage string. -func unquoteUsage(usage string) (string, string) { - 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 - } - } - return "", usage -} - -func prefixedNames(fullName, placeholder string) string { - var prefixed string - parts := strings.Split(fullName, ",") - for i, name := range parts { - name = strings.Trim(name, " ") - prefixed += prefixFor(name) + name - if placeholder != "" { - prefixed += " " + placeholder - } - if i < len(parts)-1 { - prefixed += ", " - } - } - return prefixed -} - -func withEnvHint(envVar, str string) string { - envText := "" - if envVar != "" { - prefix := "$" - suffix := "" - sep := ", $" - if runtime.GOOS == "windows" { - prefix = "%" - suffix = "%" - sep = "%, %" - } - envText = " [" + prefix + strings.Join(strings.Split(envVar, ","), sep) + suffix + "]" - } - return str + envText -} - -func withFileHint(filePath, str string) string { - fileText := "" - if filePath != "" { - fileText = fmt.Sprintf(" [%s]", filePath) - } - return str + fileText -} - -func flagValue(f Flag) reflect.Value { - fv := reflect.ValueOf(f) - for fv.Kind() == reflect.Ptr { - fv = reflect.Indirect(fv) - } - return fv -} - -func stringifyFlag(f Flag) string { - fv := flagValue(f) - - switch f.(type) { - case IntSliceFlag: - return FlagFileHinter( - fv.FieldByName("FilePath").String(), - FlagEnvHinter( - fv.FieldByName("EnvVar").String(), - stringifyIntSliceFlag(f.(IntSliceFlag)), - ), - ) - case Int64SliceFlag: - return FlagFileHinter( - fv.FieldByName("FilePath").String(), - FlagEnvHinter( - fv.FieldByName("EnvVar").String(), - stringifyInt64SliceFlag(f.(Int64SliceFlag)), - ), - ) - case StringSliceFlag: - return FlagFileHinter( - fv.FieldByName("FilePath").String(), - FlagEnvHinter( - fv.FieldByName("EnvVar").String(), - stringifyStringSliceFlag(f.(StringSliceFlag)), - ), - ) - } - - placeholder, usage := unquoteUsage(fv.FieldByName("Usage").String()) - - needsPlaceholder := false - defaultValueString := "" - - if val := fv.FieldByName("Value"); val.IsValid() { - needsPlaceholder = true - defaultValueString = fmt.Sprintf(" (default: %v)", val.Interface()) - - if val.Kind() == reflect.String && val.String() != "" { - defaultValueString = fmt.Sprintf(" (default: %q)", val.String()) - } - } - - if defaultValueString == " (default: )" { - defaultValueString = "" - } - - if needsPlaceholder && placeholder == "" { - placeholder = defaultPlaceholder - } - - usageWithDefault := strings.TrimSpace(usage + defaultValueString) - - return FlagFileHinter( - fv.FieldByName("FilePath").String(), - FlagEnvHinter( - fv.FieldByName("EnvVar").String(), - FlagNamePrefixer(fv.FieldByName("Name").String(), placeholder)+"\t"+usageWithDefault, - ), - ) -} - -func stringifyIntSliceFlag(f IntSliceFlag) string { - var defaultVals []string - if f.Value != nil && len(f.Value.Value()) > 0 { - for _, i := range f.Value.Value() { - defaultVals = append(defaultVals, strconv.Itoa(i)) - } - } - - return stringifySliceFlag(f.Usage, f.Name, defaultVals) -} - -func stringifyInt64SliceFlag(f Int64SliceFlag) string { - var defaultVals []string - if f.Value != nil && len(f.Value.Value()) > 0 { - for _, i := range f.Value.Value() { - defaultVals = append(defaultVals, strconv.FormatInt(i, 10)) - } - } - - return stringifySliceFlag(f.Usage, f.Name, defaultVals) -} - -func stringifyStringSliceFlag(f StringSliceFlag) string { - var defaultVals []string - if f.Value != nil && len(f.Value.Value()) > 0 { - for _, s := range f.Value.Value() { - if len(s) > 0 { - defaultVals = append(defaultVals, strconv.Quote(s)) - } - } - } - - return stringifySliceFlag(f.Usage, f.Name, defaultVals) -} - -func stringifySliceFlag(usage, name string, defaultVals []string) string { - placeholder, usage := unquoteUsage(usage) - if placeholder == "" { - placeholder = defaultPlaceholder - } - - defaultVal := "" - if len(defaultVals) > 0 { - defaultVal = fmt.Sprintf(" (default: %s)", strings.Join(defaultVals, ", ")) - } - - usageWithDefault := strings.TrimSpace(usage + defaultVal) - return FlagNamePrefixer(name, placeholder) + "\t" + usageWithDefault -} - -func flagFromFileEnv(filePath, envName string) (val string, ok bool) { - for _, envVar := range strings.Split(envName, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - return envVal, true - } - } - for _, fileVar := range strings.Split(filePath, ",") { - if fileVar != "" { - if data, err := ioutil.ReadFile(fileVar); err == nil { - return string(data), true - } - } - } - return "", false -} diff --git a/vendor/github.com/urfave/cli/flag_bool.go b/vendor/github.com/urfave/cli/flag_bool.go deleted file mode 100644 index 2499b0b5..00000000 --- a/vendor/github.com/urfave/cli/flag_bool.go +++ /dev/null @@ -1,109 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "strconv" -) - -// BoolFlag is a flag with type bool -type BoolFlag struct { - Name string - Usage string - EnvVar string - FilePath string - Required bool - Hidden bool - Destination *bool -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f BoolFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f BoolFlag) GetName() string { - return f.Name -} - -// IsRequired returns whether or not the flag is required -func (f BoolFlag) IsRequired() bool { - return f.Required -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f BoolFlag) TakesValue() bool { - return false -} - -// GetUsage returns the usage string for the flag -func (f BoolFlag) GetUsage() string { - return f.Usage -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f BoolFlag) GetValue() string { - return "" -} - -// Bool looks up the value of a local BoolFlag, returns -// false if not found -func (c *Context) Bool(name string) bool { - return lookupBool(name, c.flagSet) -} - -// GlobalBool looks up the value of a global BoolFlag, returns -// false if not found -func (c *Context) GlobalBool(name string) bool { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupBool(name, fs) - } - return false -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f BoolFlag) Apply(set *flag.FlagSet) { - _ = f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f BoolFlag) ApplyWithError(set *flag.FlagSet) error { - val := false - if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok { - if envVal == "" { - val = false - } else { - envValBool, err := strconv.ParseBool(envVal) - if err != nil { - return fmt.Errorf("could not parse %s as bool value for flag %s: %s", envVal, f.Name, err) - } - val = envValBool - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.BoolVar(f.Destination, name, val, f.Usage) - return - } - set.Bool(name, val, f.Usage) - }) - - return nil -} - -func lookupBool(name string, set *flag.FlagSet) bool { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseBool(f.Value.String()) - if err != nil { - return false - } - return parsed - } - return false -} diff --git a/vendor/github.com/urfave/cli/flag_bool_t.go b/vendor/github.com/urfave/cli/flag_bool_t.go deleted file mode 100644 index cd0888fa..00000000 --- a/vendor/github.com/urfave/cli/flag_bool_t.go +++ /dev/null @@ -1,110 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "strconv" -) - -// BoolTFlag is a flag with type bool that is true by default -type BoolTFlag struct { - Name string - Usage string - EnvVar string - FilePath string - Required bool - Hidden bool - Destination *bool -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f BoolTFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f BoolTFlag) GetName() string { - return f.Name -} - -// IsRequired returns whether or not the flag is required -func (f BoolTFlag) IsRequired() bool { - return f.Required -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f BoolTFlag) TakesValue() bool { - return false -} - -// GetUsage returns the usage string for the flag -func (f BoolTFlag) GetUsage() string { - return f.Usage -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f BoolTFlag) GetValue() string { - return "" -} - -// BoolT looks up the value of a local BoolTFlag, returns -// false if not found -func (c *Context) BoolT(name string) bool { - return lookupBoolT(name, c.flagSet) -} - -// GlobalBoolT looks up the value of a global BoolTFlag, returns -// false if not found -func (c *Context) GlobalBoolT(name string) bool { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupBoolT(name, fs) - } - return false -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f BoolTFlag) Apply(set *flag.FlagSet) { - _ = f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f BoolTFlag) ApplyWithError(set *flag.FlagSet) error { - val := true - - if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok { - if envVal == "" { - val = false - } else { - envValBool, err := strconv.ParseBool(envVal) - if err != nil { - return fmt.Errorf("could not parse %s as bool value for flag %s: %s", envVal, f.Name, err) - } - val = envValBool - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.BoolVar(f.Destination, name, val, f.Usage) - return - } - set.Bool(name, val, f.Usage) - }) - - return nil -} - -func lookupBoolT(name string, set *flag.FlagSet) bool { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseBool(f.Value.String()) - if err != nil { - return false - } - return parsed - } - return false -} diff --git a/vendor/github.com/urfave/cli/flag_duration.go b/vendor/github.com/urfave/cli/flag_duration.go deleted file mode 100644 index df4ade58..00000000 --- a/vendor/github.com/urfave/cli/flag_duration.go +++ /dev/null @@ -1,106 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "time" -) - -// DurationFlag is a flag with type time.Duration (see https://golang.org/pkg/time/#ParseDuration) -type DurationFlag struct { - Name string - Usage string - EnvVar string - FilePath string - Required bool - Hidden bool - Value time.Duration - Destination *time.Duration -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f DurationFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f DurationFlag) GetName() string { - return f.Name -} - -// IsRequired returns whether or not the flag is required -func (f DurationFlag) IsRequired() bool { - return f.Required -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f DurationFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f DurationFlag) GetUsage() string { - return f.Usage -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f DurationFlag) GetValue() string { - return f.Value.String() -} - -// Duration looks up the value of a local DurationFlag, returns -// 0 if not found -func (c *Context) Duration(name string) time.Duration { - return lookupDuration(name, c.flagSet) -} - -// GlobalDuration looks up the value of a global DurationFlag, returns -// 0 if not found -func (c *Context) GlobalDuration(name string) time.Duration { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupDuration(name, fs) - } - return 0 -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f DurationFlag) Apply(set *flag.FlagSet) { - _ = f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f DurationFlag) ApplyWithError(set *flag.FlagSet) error { - if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok { - envValDuration, err := time.ParseDuration(envVal) - if err != nil { - return fmt.Errorf("could not parse %s as duration for flag %s: %s", envVal, f.Name, err) - } - - f.Value = envValDuration - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.DurationVar(f.Destination, name, f.Value, f.Usage) - return - } - set.Duration(name, f.Value, f.Usage) - }) - - return nil -} - -func lookupDuration(name string, set *flag.FlagSet) time.Duration { - f := set.Lookup(name) - if f != nil { - parsed, err := time.ParseDuration(f.Value.String()) - if err != nil { - return 0 - } - return parsed - } - return 0 -} diff --git a/vendor/github.com/urfave/cli/flag_float64.go b/vendor/github.com/urfave/cli/flag_float64.go deleted file mode 100644 index 65398d3b..00000000 --- a/vendor/github.com/urfave/cli/flag_float64.go +++ /dev/null @@ -1,106 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "strconv" -) - -// Float64Flag is a flag with type float64 -type Float64Flag struct { - Name string - Usage string - EnvVar string - FilePath string - Required bool - Hidden bool - Value float64 - Destination *float64 -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f Float64Flag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f Float64Flag) GetName() string { - return f.Name -} - -// IsRequired returns whether or not the flag is required -func (f Float64Flag) IsRequired() bool { - return f.Required -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f Float64Flag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f Float64Flag) GetUsage() string { - return f.Usage -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f Float64Flag) GetValue() string { - return fmt.Sprintf("%f", f.Value) -} - -// Float64 looks up the value of a local Float64Flag, returns -// 0 if not found -func (c *Context) Float64(name string) float64 { - return lookupFloat64(name, c.flagSet) -} - -// GlobalFloat64 looks up the value of a global Float64Flag, returns -// 0 if not found -func (c *Context) GlobalFloat64(name string) float64 { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupFloat64(name, fs) - } - return 0 -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f Float64Flag) Apply(set *flag.FlagSet) { - _ = f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f Float64Flag) ApplyWithError(set *flag.FlagSet) error { - if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok { - envValFloat, err := strconv.ParseFloat(envVal, 10) - if err != nil { - return fmt.Errorf("could not parse %s as float64 value for flag %s: %s", envVal, f.Name, err) - } - - f.Value = envValFloat - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.Float64Var(f.Destination, name, f.Value, f.Usage) - return - } - set.Float64(name, f.Value, f.Usage) - }) - - return nil -} - -func lookupFloat64(name string, set *flag.FlagSet) float64 { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseFloat(f.Value.String(), 64) - if err != nil { - return 0 - } - return parsed - } - return 0 -} diff --git a/vendor/github.com/urfave/cli/flag_generic.go b/vendor/github.com/urfave/cli/flag_generic.go deleted file mode 100644 index c43dae7d..00000000 --- a/vendor/github.com/urfave/cli/flag_generic.go +++ /dev/null @@ -1,110 +0,0 @@ -package cli - -import ( - "flag" - "fmt" -) - -// Generic is a generic parseable type identified by a specific flag -type Generic interface { - Set(value string) error - String() string -} - -// GenericFlag is a flag with type Generic -type GenericFlag struct { - Name string - Usage string - EnvVar string - FilePath string - Required bool - Hidden bool - TakesFile bool - Value Generic -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f GenericFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f GenericFlag) GetName() string { - return f.Name -} - -// IsRequired returns whether or not the flag is required -func (f GenericFlag) IsRequired() bool { - return f.Required -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f GenericFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f GenericFlag) GetUsage() string { - return f.Usage -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f GenericFlag) GetValue() string { - if f.Value != nil { - return f.Value.String() - } - return "" -} - -// Apply takes the flagset and calls Set on the generic flag with the value -// provided by the user for parsing by the flag -// Ignores parsing errors -func (f GenericFlag) Apply(set *flag.FlagSet) { - _ = f.ApplyWithError(set) -} - -// ApplyWithError takes the flagset and calls Set on the generic flag with the value -// provided by the user for parsing by the flag -func (f GenericFlag) ApplyWithError(set *flag.FlagSet) error { - val := f.Value - if fileEnvVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok { - if err := val.Set(fileEnvVal); err != nil { - return fmt.Errorf("could not parse %s as value for flag %s: %s", fileEnvVal, f.Name, err) - } - } - - eachName(f.Name, func(name string) { - set.Var(f.Value, name, f.Usage) - }) - - return nil -} - -// Generic looks up the value of a local GenericFlag, returns -// nil if not found -func (c *Context) Generic(name string) interface{} { - return lookupGeneric(name, c.flagSet) -} - -// GlobalGeneric looks up the value of a global GenericFlag, returns -// nil if not found -func (c *Context) GlobalGeneric(name string) interface{} { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupGeneric(name, fs) - } - return nil -} - -func lookupGeneric(name string, set *flag.FlagSet) interface{} { - f := set.Lookup(name) - if f != nil { - parsed, err := f.Value, error(nil) - if err != nil { - return nil - } - return parsed - } - return nil -} diff --git a/vendor/github.com/urfave/cli/flag_int.go b/vendor/github.com/urfave/cli/flag_int.go deleted file mode 100644 index bae32e28..00000000 --- a/vendor/github.com/urfave/cli/flag_int.go +++ /dev/null @@ -1,105 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "strconv" -) - -// IntFlag is a flag with type int -type IntFlag struct { - Name string - Usage string - EnvVar string - FilePath string - Required bool - Hidden bool - Value int - Destination *int -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f IntFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f IntFlag) GetName() string { - return f.Name -} - -// IsRequired returns whether or not the flag is required -func (f IntFlag) IsRequired() bool { - return f.Required -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f IntFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f IntFlag) GetUsage() string { - return f.Usage -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f IntFlag) GetValue() string { - return fmt.Sprintf("%d", f.Value) -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f IntFlag) Apply(set *flag.FlagSet) { - _ = f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f IntFlag) ApplyWithError(set *flag.FlagSet) error { - if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok { - envValInt, err := strconv.ParseInt(envVal, 0, 64) - if err != nil { - return fmt.Errorf("could not parse %s as int value for flag %s: %s", envVal, f.Name, err) - } - f.Value = int(envValInt) - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.IntVar(f.Destination, name, f.Value, f.Usage) - return - } - set.Int(name, f.Value, f.Usage) - }) - - return nil -} - -// Int looks up the value of a local IntFlag, returns -// 0 if not found -func (c *Context) Int(name string) int { - return lookupInt(name, c.flagSet) -} - -// GlobalInt looks up the value of a global IntFlag, returns -// 0 if not found -func (c *Context) GlobalInt(name string) int { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupInt(name, fs) - } - return 0 -} - -func lookupInt(name string, set *flag.FlagSet) int { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseInt(f.Value.String(), 0, 64) - if err != nil { - return 0 - } - return int(parsed) - } - return 0 -} diff --git a/vendor/github.com/urfave/cli/flag_int64.go b/vendor/github.com/urfave/cli/flag_int64.go deleted file mode 100644 index aaafbe9d..00000000 --- a/vendor/github.com/urfave/cli/flag_int64.go +++ /dev/null @@ -1,106 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "strconv" -) - -// Int64Flag is a flag with type int64 -type Int64Flag struct { - Name string - Usage string - EnvVar string - FilePath string - Required bool - Hidden bool - Value int64 - Destination *int64 -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f Int64Flag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f Int64Flag) GetName() string { - return f.Name -} - -// IsRequired returns whether or not the flag is required -func (f Int64Flag) IsRequired() bool { - return f.Required -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f Int64Flag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f Int64Flag) GetUsage() string { - return f.Usage -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f Int64Flag) GetValue() string { - return fmt.Sprintf("%d", f.Value) -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f Int64Flag) Apply(set *flag.FlagSet) { - _ = f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f Int64Flag) ApplyWithError(set *flag.FlagSet) error { - if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok { - envValInt, err := strconv.ParseInt(envVal, 0, 64) - if err != nil { - return fmt.Errorf("could not parse %s as int value for flag %s: %s", envVal, f.Name, err) - } - - f.Value = envValInt - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.Int64Var(f.Destination, name, f.Value, f.Usage) - return - } - set.Int64(name, f.Value, f.Usage) - }) - - return nil -} - -// Int64 looks up the value of a local Int64Flag, returns -// 0 if not found -func (c *Context) Int64(name string) int64 { - return lookupInt64(name, c.flagSet) -} - -// GlobalInt64 looks up the value of a global Int64Flag, returns -// 0 if not found -func (c *Context) GlobalInt64(name string) int64 { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupInt64(name, fs) - } - return 0 -} - -func lookupInt64(name string, set *flag.FlagSet) int64 { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseInt(f.Value.String(), 0, 64) - if err != nil { - return 0 - } - return parsed - } - return 0 -} diff --git a/vendor/github.com/urfave/cli/flag_int64_slice.go b/vendor/github.com/urfave/cli/flag_int64_slice.go deleted file mode 100644 index 80772e7c..00000000 --- a/vendor/github.com/urfave/cli/flag_int64_slice.go +++ /dev/null @@ -1,199 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "strconv" - "strings" -) - -// Int64Slice is an opaque type for []int to satisfy flag.Value and flag.Getter -type Int64Slice []int64 - -// Set parses the value into an integer and appends it to the list of values -func (f *Int64Slice) Set(value string) error { - tmp, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - *f = append(*f, tmp) - return nil -} - -// String returns a readable representation of this value (for usage defaults) -func (f *Int64Slice) String() string { - slice := make([]string, len(*f)) - for i, v := range *f { - slice[i] = strconv.FormatInt(v, 10) - } - - return strings.Join(slice, ",") -} - -// Value returns the slice of ints set by this flag -func (f *Int64Slice) Value() []int64 { - return *f -} - -// Get returns the slice of ints set by this flag -func (f *Int64Slice) Get() interface{} { - return *f -} - -// Int64SliceFlag is a flag with type *Int64Slice -type Int64SliceFlag struct { - Name string - Usage string - EnvVar string - FilePath string - Required bool - Hidden bool - Value *Int64Slice -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f Int64SliceFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f Int64SliceFlag) GetName() string { - return f.Name -} - -// IsRequired returns whether or not the flag is required -func (f Int64SliceFlag) IsRequired() bool { - return f.Required -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f Int64SliceFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f Int64SliceFlag) GetUsage() string { - return f.Usage -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f Int64SliceFlag) GetValue() string { - if f.Value != nil { - return f.Value.String() - } - return "" -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f Int64SliceFlag) Apply(set *flag.FlagSet) { - _ = f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f Int64SliceFlag) ApplyWithError(set *flag.FlagSet) error { - if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok { - newVal := &Int64Slice{} - for _, s := range strings.Split(envVal, ",") { - s = strings.TrimSpace(s) - if err := newVal.Set(s); err != nil { - return fmt.Errorf("could not parse %s as int64 slice value for flag %s: %s", envVal, f.Name, err) - } - } - if f.Value == nil { - f.Value = newVal - } else { - *f.Value = *newVal - } - } - - eachName(f.Name, func(name string) { - if f.Value == nil { - f.Value = &Int64Slice{} - } - set.Var(f.Value, name, f.Usage) - }) - - return nil -} - -// Int64Slice looks up the value of a local Int64SliceFlag, returns -// nil if not found -func (c *Context) Int64Slice(name string) []int64 { - return lookupInt64Slice(name, c.flagSet) -} - -// GlobalInt64Slice looks up the value of a global Int64SliceFlag, returns -// nil if not found -func (c *Context) GlobalInt64Slice(name string) []int64 { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupInt64Slice(name, fs) - } - return nil -} - -func lookupInt64Slice(name string, set *flag.FlagSet) []int64 { - f := set.Lookup(name) - if f != nil { - value, ok := f.Value.(*Int64Slice) - if !ok { - return nil - } - - // extract the slice from asserted value - parsed := value.Value() - - // extract default value from the flag - var defaultVal []int64 - for _, v := range strings.Split(f.DefValue, ",") { - if v != "" { - int64Value, err := strconv.ParseInt(v, 10, 64) - if err != nil { - panic(err) - } - defaultVal = append(defaultVal, int64Value) - } - } - // if the current value is not equal to the default value - // remove the default values from the flag - if !isInt64SliceEqual(parsed, defaultVal) { - for _, v := range defaultVal { - parsed = removeFromInt64Slice(parsed, v) - } - } - return parsed - } - return nil -} - -func removeFromInt64Slice(slice []int64, val int64) []int64 { - for i, v := range slice { - if v == val { - ret := append([]int64{}, slice[:i]...) - ret = append(ret, slice[i+1:]...) - return ret - } - } - return slice -} - -func isInt64SliceEqual(newValue, defaultValue []int64) bool { - // If one is nil, the other must also be nil. - if (newValue == nil) != (defaultValue == nil) { - return false - } - - if len(newValue) != len(defaultValue) { - return false - } - - for i, v := range newValue { - if v != defaultValue[i] { - return false - } - } - - return true -} diff --git a/vendor/github.com/urfave/cli/flag_int_slice.go b/vendor/github.com/urfave/cli/flag_int_slice.go deleted file mode 100644 index af6d582d..00000000 --- a/vendor/github.com/urfave/cli/flag_int_slice.go +++ /dev/null @@ -1,198 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "strconv" - "strings" -) - -// IntSlice is an opaque type for []int to satisfy flag.Value and flag.Getter -type IntSlice []int - -// Set parses the value into an integer and appends it to the list of values -func (f *IntSlice) Set(value string) error { - tmp, err := strconv.Atoi(value) - if err != nil { - return err - } - *f = append(*f, tmp) - return nil -} - -// String returns a readable representation of this value (for usage defaults) -func (f *IntSlice) String() string { - slice := make([]string, len(*f)) - for i, v := range *f { - slice[i] = strconv.Itoa(v) - } - - return strings.Join(slice, ",") -} - -// Value returns the slice of ints set by this flag -func (f *IntSlice) Value() []int { - return *f -} - -// Get returns the slice of ints set by this flag -func (f *IntSlice) Get() interface{} { - return *f -} - -// IntSliceFlag is a flag with type *IntSlice -type IntSliceFlag struct { - Name string - Usage string - EnvVar string - FilePath string - Required bool - Hidden bool - Value *IntSlice -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f IntSliceFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f IntSliceFlag) GetName() string { - return f.Name -} - -// IsRequired returns whether or not the flag is required -func (f IntSliceFlag) IsRequired() bool { - return f.Required -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f IntSliceFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f IntSliceFlag) GetUsage() string { - return f.Usage -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f IntSliceFlag) GetValue() string { - if f.Value != nil { - return f.Value.String() - } - return "" -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f IntSliceFlag) Apply(set *flag.FlagSet) { - _ = f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f IntSliceFlag) ApplyWithError(set *flag.FlagSet) error { - if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok { - newVal := &IntSlice{} - for _, s := range strings.Split(envVal, ",") { - s = strings.TrimSpace(s) - if err := newVal.Set(s); err != nil { - return fmt.Errorf("could not parse %s as int slice value for flag %s: %s", envVal, f.Name, err) - } - } - if f.Value == nil { - f.Value = newVal - } else { - *f.Value = *newVal - } - } - - eachName(f.Name, func(name string) { - if f.Value == nil { - f.Value = &IntSlice{} - } - set.Var(f.Value, name, f.Usage) - }) - - return nil -} - -// IntSlice looks up the value of a local IntSliceFlag, returns -// nil if not found -func (c *Context) IntSlice(name string) []int { - return lookupIntSlice(name, c.flagSet) -} - -// GlobalIntSlice looks up the value of a global IntSliceFlag, returns -// nil if not found -func (c *Context) GlobalIntSlice(name string) []int { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupIntSlice(name, fs) - } - return nil -} - -func lookupIntSlice(name string, set *flag.FlagSet) []int { - f := set.Lookup(name) - if f != nil { - value, ok := f.Value.(*IntSlice) - if !ok { - return nil - } - // extract the slice from asserted value - slice := value.Value() - - // extract default value from the flag - var defaultVal []int - for _, v := range strings.Split(f.DefValue, ",") { - if v != "" { - intValue, err := strconv.Atoi(v) - if err != nil { - panic(err) - } - defaultVal = append(defaultVal, intValue) - } - } - // if the current value is not equal to the default value - // remove the default values from the flag - if !isIntSliceEqual(slice, defaultVal) { - for _, v := range defaultVal { - slice = removeFromIntSlice(slice, v) - } - } - return slice - } - return nil -} - -func removeFromIntSlice(slice []int, val int) []int { - for i, v := range slice { - if v == val { - ret := append([]int{}, slice[:i]...) - ret = append(ret, slice[i+1:]...) - return ret - } - } - return slice -} - -func isIntSliceEqual(newValue, defaultValue []int) bool { - // If one is nil, the other must also be nil. - if (newValue == nil) != (defaultValue == nil) { - return false - } - - if len(newValue) != len(defaultValue) { - return false - } - - for i, v := range newValue { - if v != defaultValue[i] { - return false - } - } - - return true -} diff --git a/vendor/github.com/urfave/cli/flag_string.go b/vendor/github.com/urfave/cli/flag_string.go deleted file mode 100644 index 9f29da40..00000000 --- a/vendor/github.com/urfave/cli/flag_string.go +++ /dev/null @@ -1,98 +0,0 @@ -package cli - -import "flag" - -// StringFlag is a flag with type string -type StringFlag struct { - Name string - Usage string - EnvVar string - FilePath string - Required bool - Hidden bool - TakesFile bool - Value string - Destination *string -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f StringFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f StringFlag) GetName() string { - return f.Name -} - -// IsRequired returns whether or not the flag is required -func (f StringFlag) IsRequired() bool { - return f.Required -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f StringFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f StringFlag) GetUsage() string { - return f.Usage -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f StringFlag) GetValue() string { - return f.Value -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f StringFlag) Apply(set *flag.FlagSet) { - _ = f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f StringFlag) ApplyWithError(set *flag.FlagSet) error { - if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok { - f.Value = envVal - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.StringVar(f.Destination, name, f.Value, f.Usage) - return - } - set.String(name, f.Value, f.Usage) - }) - - return nil -} - -// String looks up the value of a local StringFlag, returns -// "" if not found -func (c *Context) String(name string) string { - return lookupString(name, c.flagSet) -} - -// GlobalString looks up the value of a global StringFlag, returns -// "" if not found -func (c *Context) GlobalString(name string) string { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupString(name, fs) - } - return "" -} - -func lookupString(name string, set *flag.FlagSet) string { - f := set.Lookup(name) - if f != nil { - parsed, err := f.Value.String(), error(nil) - if err != nil { - return "" - } - return parsed - } - return "" -} diff --git a/vendor/github.com/urfave/cli/flag_string_slice.go b/vendor/github.com/urfave/cli/flag_string_slice.go deleted file mode 100644 index a7c71e9d..00000000 --- a/vendor/github.com/urfave/cli/flag_string_slice.go +++ /dev/null @@ -1,184 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "strings" -) - -// StringSlice is an opaque type for []string to satisfy flag.Value and flag.Getter -type StringSlice []string - -// Set appends the string value to the list of values -func (f *StringSlice) Set(value string) error { - *f = append(*f, value) - return nil -} - -// String returns a readable representation of this value (for usage defaults) -func (f *StringSlice) String() string { - return strings.Join(*f, ",") -} - -// Value returns the slice of strings set by this flag -func (f *StringSlice) Value() []string { - return *f -} - -// Get returns the slice of strings set by this flag -func (f *StringSlice) Get() interface{} { - return *f -} - -// StringSliceFlag is a flag with type *StringSlice -type StringSliceFlag struct { - Name string - Usage string - EnvVar string - FilePath string - Required bool - Hidden bool - TakesFile bool - Value *StringSlice -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f StringSliceFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f StringSliceFlag) GetName() string { - return f.Name -} - -// IsRequired returns whether or not the flag is required -func (f StringSliceFlag) IsRequired() bool { - return f.Required -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f StringSliceFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f StringSliceFlag) GetUsage() string { - return f.Usage -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f StringSliceFlag) GetValue() string { - if f.Value != nil { - return f.Value.String() - } - return "" -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f StringSliceFlag) Apply(set *flag.FlagSet) { - _ = f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f StringSliceFlag) ApplyWithError(set *flag.FlagSet) error { - if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok { - newVal := &StringSlice{} - for _, s := range strings.Split(envVal, ",") { - s = strings.TrimSpace(s) - if err := newVal.Set(s); err != nil { - return fmt.Errorf("could not parse %s as string value for flag %s: %s", envVal, f.Name, err) - } - } - if f.Value == nil { - f.Value = newVal - } else { - *f.Value = *newVal - } - } - - eachName(f.Name, func(name string) { - if f.Value == nil { - f.Value = &StringSlice{} - } - set.Var(f.Value, name, f.Usage) - }) - - return nil -} - -// StringSlice looks up the value of a local StringSliceFlag, returns -// nil if not found -func (c *Context) StringSlice(name string) []string { - return lookupStringSlice(name, c.flagSet) -} - -// GlobalStringSlice looks up the value of a global StringSliceFlag, returns -// nil if not found -func (c *Context) GlobalStringSlice(name string) []string { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupStringSlice(name, fs) - } - return nil -} - -func lookupStringSlice(name string, set *flag.FlagSet) []string { - f := set.Lookup(name) - if f != nil { - value, ok := f.Value.(*StringSlice) - if !ok { - return nil - } - // extract the slice from asserted value - slice := value.Value() - - // extract default value from the flag - var defaultVal []string - for _, v := range strings.Split(f.DefValue, ",") { - defaultVal = append(defaultVal, v) - } - - // if the current value is not equal to the default value - // remove the default values from the flag - if !isStringSliceEqual(slice, defaultVal) { - for _, v := range defaultVal { - slice = removeFromStringSlice(slice, v) - } - } - return slice - } - return nil -} - -func removeFromStringSlice(slice []string, val string) []string { - for i, v := range slice { - if v == val { - ret := append([]string{}, slice[:i]...) - ret = append(ret, slice[i+1:]...) - return ret - } - } - return slice -} - -func isStringSliceEqual(newValue, defaultValue []string) bool { - // If one is nil, the other must also be nil. - if (newValue == nil) != (defaultValue == nil) { - return false - } - - if len(newValue) != len(defaultValue) { - return false - } - - for i, v := range newValue { - if v != defaultValue[i] { - return false - } - } - - return true -} diff --git a/vendor/github.com/urfave/cli/flag_uint.go b/vendor/github.com/urfave/cli/flag_uint.go deleted file mode 100644 index d6a04f40..00000000 --- a/vendor/github.com/urfave/cli/flag_uint.go +++ /dev/null @@ -1,106 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "strconv" -) - -// UintFlag is a flag with type uint -type UintFlag struct { - Name string - Usage string - EnvVar string - FilePath string - Required bool - Hidden bool - Value uint - Destination *uint -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f UintFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f UintFlag) GetName() string { - return f.Name -} - -// IsRequired returns whether or not the flag is required -func (f UintFlag) IsRequired() bool { - return f.Required -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f UintFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f UintFlag) GetUsage() string { - return f.Usage -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f UintFlag) Apply(set *flag.FlagSet) { - _ = f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f UintFlag) ApplyWithError(set *flag.FlagSet) error { - if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok { - envValInt, err := strconv.ParseUint(envVal, 0, 64) - if err != nil { - return fmt.Errorf("could not parse %s as uint value for flag %s: %s", envVal, f.Name, err) - } - - f.Value = uint(envValInt) - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.UintVar(f.Destination, name, f.Value, f.Usage) - return - } - set.Uint(name, f.Value, f.Usage) - }) - - return nil -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f UintFlag) GetValue() string { - return fmt.Sprintf("%d", f.Value) -} - -// Uint looks up the value of a local UintFlag, returns -// 0 if not found -func (c *Context) Uint(name string) uint { - return lookupUint(name, c.flagSet) -} - -// GlobalUint looks up the value of a global UintFlag, returns -// 0 if not found -func (c *Context) GlobalUint(name string) uint { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupUint(name, fs) - } - return 0 -} - -func lookupUint(name string, set *flag.FlagSet) uint { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseUint(f.Value.String(), 0, 64) - if err != nil { - return 0 - } - return uint(parsed) - } - return 0 -} diff --git a/vendor/github.com/urfave/cli/flag_uint64.go b/vendor/github.com/urfave/cli/flag_uint64.go deleted file mode 100644 index ea6493a8..00000000 --- a/vendor/github.com/urfave/cli/flag_uint64.go +++ /dev/null @@ -1,106 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "strconv" -) - -// Uint64Flag is a flag with type uint64 -type Uint64Flag struct { - Name string - Usage string - EnvVar string - FilePath string - Required bool - Hidden bool - Value uint64 - Destination *uint64 -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f Uint64Flag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f Uint64Flag) GetName() string { - return f.Name -} - -// IsRequired returns whether or not the flag is required -func (f Uint64Flag) IsRequired() bool { - return f.Required -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f Uint64Flag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f Uint64Flag) GetUsage() string { - return f.Usage -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f Uint64Flag) GetValue() string { - return fmt.Sprintf("%d", f.Value) -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f Uint64Flag) Apply(set *flag.FlagSet) { - _ = f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f Uint64Flag) ApplyWithError(set *flag.FlagSet) error { - if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok { - envValInt, err := strconv.ParseUint(envVal, 0, 64) - if err != nil { - return fmt.Errorf("could not parse %s as uint64 value for flag %s: %s", envVal, f.Name, err) - } - - f.Value = envValInt - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.Uint64Var(f.Destination, name, f.Value, f.Usage) - return - } - set.Uint64(name, f.Value, f.Usage) - }) - - return nil -} - -// Uint64 looks up the value of a local Uint64Flag, returns -// 0 if not found -func (c *Context) Uint64(name string) uint64 { - return lookupUint64(name, c.flagSet) -} - -// GlobalUint64 looks up the value of a global Uint64Flag, returns -// 0 if not found -func (c *Context) GlobalUint64(name string) uint64 { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupUint64(name, fs) - } - return 0 -} - -func lookupUint64(name string, set *flag.FlagSet) uint64 { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseUint(f.Value.String(), 0, 64) - if err != nil { - return 0 - } - return parsed - } - return 0 -} diff --git a/vendor/github.com/urfave/cli/funcs.go b/vendor/github.com/urfave/cli/funcs.go deleted file mode 100644 index 0036b113..00000000 --- a/vendor/github.com/urfave/cli/funcs.go +++ /dev/null @@ -1,44 +0,0 @@ -package cli - -// BashCompleteFunc is an action to execute when the bash-completion flag is set -type BashCompleteFunc func(*Context) - -// BeforeFunc is an action to execute before any subcommands are run, but after -// the context is ready if a non-nil error is returned, no subcommands are run -type BeforeFunc func(*Context) error - -// AfterFunc is an action to execute after any subcommands are run, but after the -// subcommand has finished it is run even if Action() panics -type AfterFunc func(*Context) error - -// ActionFunc is the action to execute when no subcommands are specified -type ActionFunc func(*Context) error - -// CommandNotFoundFunc is executed if the proper command cannot be found -type CommandNotFoundFunc func(*Context, string) - -// OnUsageErrorFunc is executed if an usage error occurs. This is useful for displaying -// customized usage error messages. This function is able to replace the -// original error messages. If this function is not set, the "Incorrect usage" -// is displayed and the execution is interrupted. -type OnUsageErrorFunc func(context *Context, err error, isSubcommand bool) error - -// ExitErrHandlerFunc is executed if provided in order to handle ExitError values -// returned by Actions and Before/After functions. -type ExitErrHandlerFunc func(context *Context, err error) - -// FlagStringFunc is used by the help generation to display a flag, which is -// expected to be a single line. -type FlagStringFunc func(Flag) string - -// FlagNamePrefixFunc is used by the default FlagStringFunc to create prefix -// text for a flag's full name. -type FlagNamePrefixFunc func(fullName, placeholder string) string - -// FlagEnvHintFunc is used by the default FlagStringFunc to annotate flag help -// with the environment variable details. -type FlagEnvHintFunc func(envVar, str string) string - -// FlagFileHintFunc is used by the default FlagStringFunc to annotate flag help -// with the file path details. -type FlagFileHintFunc func(filePath, str string) string diff --git a/vendor/github.com/urfave/cli/help.go b/vendor/github.com/urfave/cli/help.go deleted file mode 100644 index 2280e338..00000000 --- a/vendor/github.com/urfave/cli/help.go +++ /dev/null @@ -1,363 +0,0 @@ -package cli - -import ( - "fmt" - "io" - "os" - "strings" - "text/tabwriter" - "text/template" - "unicode/utf8" -) - -var helpCommand = Command{ - Name: "help", - Aliases: []string{"h"}, - Usage: "Shows a list of commands or help for one command", - ArgsUsage: "[command]", - Action: func(c *Context) error { - args := c.Args() - if args.Present() { - return ShowCommandHelp(c, args.First()) - } - - _ = ShowAppHelp(c) - return nil - }, -} - -var helpSubcommand = Command{ - Name: "help", - Aliases: []string{"h"}, - Usage: "Shows a list of commands or help for one command", - ArgsUsage: "[command]", - Action: func(c *Context) error { - args := c.Args() - if args.Present() { - return ShowCommandHelp(c, args.First()) - } - - return ShowSubcommandHelp(c) - }, -} - -// Prints help for the App or Command -type helpPrinter func(w io.Writer, templ string, data interface{}) - -// Prints help for the App or Command with custom template function. -type helpPrinterCustom func(w io.Writer, templ string, data interface{}, customFunc map[string]interface{}) - -// HelpPrinter is a function that writes the help output. If not set explicitly, -// this calls HelpPrinterCustom using only the default template functions. -// -// If custom logic for printing help is required, this function can be -// overridden. If the ExtraInfo field is defined on an App, this function -// should not be modified, as HelpPrinterCustom will be used directly in order -// to capture the extra information. -var HelpPrinter helpPrinter = printHelp - -// HelpPrinterCustom is a function that writes the help output. It is used as -// the default implementation of HelpPrinter, and may be called directly if -// the ExtraInfo field is set on an App. -var HelpPrinterCustom helpPrinterCustom = printHelpCustom - -// VersionPrinter prints the version for the App -var VersionPrinter = printVersion - -// ShowAppHelpAndExit - Prints the list of subcommands for the app and exits with exit code. -func ShowAppHelpAndExit(c *Context, exitCode int) { - _ = ShowAppHelp(c) - os.Exit(exitCode) -} - -// ShowAppHelp is an action that displays the help. -func ShowAppHelp(c *Context) error { - template := c.App.CustomAppHelpTemplate - if template == "" { - template = AppHelpTemplate - } - - if c.App.ExtraInfo == nil { - HelpPrinter(c.App.Writer, template, c.App) - return nil - } - - customAppData := func() map[string]interface{} { - return map[string]interface{}{ - "ExtraInfo": c.App.ExtraInfo, - } - } - HelpPrinterCustom(c.App.Writer, template, c.App, customAppData()) - - return nil -} - -// DefaultAppComplete prints the list of subcommands as the default app completion method -func DefaultAppComplete(c *Context) { - DefaultCompleteWithFlags(nil)(c) -} - -func printCommandSuggestions(commands []Command, writer io.Writer) { - for _, command := range commands { - if command.Hidden { - continue - } - if os.Getenv("_CLI_ZSH_AUTOCOMPLETE_HACK") == "1" { - for _, name := range command.Names() { - _, _ = fmt.Fprintf(writer, "%s:%s\n", name, command.Usage) - } - } else { - for _, name := range command.Names() { - _, _ = fmt.Fprintf(writer, "%s\n", name) - } - } - } -} - -func cliArgContains(flagName string) bool { - for _, name := range strings.Split(flagName, ",") { - name = strings.TrimSpace(name) - count := utf8.RuneCountInString(name) - if count > 2 { - count = 2 - } - flag := fmt.Sprintf("%s%s", strings.Repeat("-", count), name) - for _, a := range os.Args { - if a == flag { - return true - } - } - } - return false -} - -func printFlagSuggestions(lastArg string, flags []Flag, writer io.Writer) { - cur := strings.TrimPrefix(lastArg, "-") - cur = strings.TrimPrefix(cur, "-") - for _, flag := range flags { - if bflag, ok := flag.(BoolFlag); ok && bflag.Hidden { - continue - } - for _, name := range strings.Split(flag.GetName(), ",") { - name = strings.TrimSpace(name) - // this will get total count utf8 letters in flag name - count := utf8.RuneCountInString(name) - if count > 2 { - count = 2 // resuse this count to generate single - or -- in flag completion - } - // if flag name has more than one utf8 letter and last argument in cli has -- prefix then - // skip flag completion for short flags example -v or -x - if strings.HasPrefix(lastArg, "--") && count == 1 { - continue - } - // match if last argument matches this flag and it is not repeated - if strings.HasPrefix(name, cur) && cur != name && !cliArgContains(flag.GetName()) { - flagCompletion := fmt.Sprintf("%s%s", strings.Repeat("-", count), name) - _, _ = fmt.Fprintln(writer, flagCompletion) - } - } - } -} - -func DefaultCompleteWithFlags(cmd *Command) func(c *Context) { - return func(c *Context) { - if len(os.Args) > 2 { - lastArg := os.Args[len(os.Args)-2] - if strings.HasPrefix(lastArg, "-") { - printFlagSuggestions(lastArg, c.App.Flags, c.App.Writer) - if cmd != nil { - printFlagSuggestions(lastArg, cmd.Flags, c.App.Writer) - } - return - } - } - if cmd != nil { - printCommandSuggestions(cmd.Subcommands, c.App.Writer) - } else { - printCommandSuggestions(c.App.Commands, c.App.Writer) - } - } -} - -// ShowCommandHelpAndExit - exits with code after showing help -func ShowCommandHelpAndExit(c *Context, command string, code int) { - _ = ShowCommandHelp(c, command) - os.Exit(code) -} - -// ShowCommandHelp prints help for the given command -func ShowCommandHelp(ctx *Context, command string) error { - // show the subcommand help for a command with subcommands - if command == "" { - HelpPrinter(ctx.App.Writer, SubcommandHelpTemplate, ctx.App) - return nil - } - - for _, c := range ctx.App.Commands { - if c.HasName(command) { - templ := c.CustomHelpTemplate - if templ == "" { - templ = CommandHelpTemplate - } - - HelpPrinter(ctx.App.Writer, templ, c) - - return nil - } - } - - if ctx.App.CommandNotFound == nil { - return NewExitError(fmt.Sprintf("No help topic for '%v'", command), 3) - } - - ctx.App.CommandNotFound(ctx, command) - return nil -} - -// ShowSubcommandHelp prints help for the given subcommand -func ShowSubcommandHelp(c *Context) error { - return ShowCommandHelp(c, c.Command.Name) -} - -// ShowVersion prints the version number of the App -func ShowVersion(c *Context) { - VersionPrinter(c) -} - -func printVersion(c *Context) { - _, _ = fmt.Fprintf(c.App.Writer, "%v version %v\n", c.App.Name, c.App.Version) -} - -// ShowCompletions prints the lists of commands within a given context -func ShowCompletions(c *Context) { - a := c.App - if a != nil && a.BashComplete != nil { - a.BashComplete(c) - } -} - -// ShowCommandCompletions prints the custom completions for a given command -func ShowCommandCompletions(ctx *Context, command string) { - c := ctx.App.Command(command) - if c != nil { - if c.BashComplete != nil { - c.BashComplete(ctx) - } else { - DefaultCompleteWithFlags(c)(ctx) - } - } - -} - -// printHelpCustom is the default implementation of HelpPrinterCustom. -// -// The customFuncs map will be combined with a default template.FuncMap to -// allow using arbitrary functions in template rendering. -func printHelpCustom(out io.Writer, templ string, data interface{}, customFuncs map[string]interface{}) { - funcMap := template.FuncMap{ - "join": strings.Join, - } - for key, value := range customFuncs { - funcMap[key] = value - } - - w := tabwriter.NewWriter(out, 1, 8, 2, ' ', 0) - t := template.Must(template.New("help").Funcs(funcMap).Parse(templ)) - err := t.Execute(w, data) - if err != nil { - // If the writer is closed, t.Execute will fail, and there's nothing - // we can do to recover. - if os.Getenv("CLI_TEMPLATE_ERROR_DEBUG") != "" { - _, _ = fmt.Fprintf(ErrWriter, "CLI TEMPLATE ERROR: %#v\n", err) - } - return - } - _ = w.Flush() -} - -func printHelp(out io.Writer, templ string, data interface{}) { - HelpPrinterCustom(out, templ, data, nil) -} - -func checkVersion(c *Context) bool { - found := false - if VersionFlag.GetName() != "" { - eachName(VersionFlag.GetName(), func(name string) { - if c.GlobalBool(name) || c.Bool(name) { - found = true - } - }) - } - return found -} - -func checkHelp(c *Context) bool { - found := false - if HelpFlag.GetName() != "" { - eachName(HelpFlag.GetName(), func(name string) { - if c.GlobalBool(name) || c.Bool(name) { - found = true - } - }) - } - return found -} - -func checkCommandHelp(c *Context, name string) bool { - if c.Bool("h") || c.Bool("help") { - _ = ShowCommandHelp(c, name) - return true - } - - return false -} - -func checkSubcommandHelp(c *Context) bool { - if c.Bool("h") || c.Bool("help") { - _ = ShowSubcommandHelp(c) - return true - } - - return false -} - -func checkShellCompleteFlag(a *App, arguments []string) (bool, []string) { - if !a.EnableBashCompletion { - return false, arguments - } - - pos := len(arguments) - 1 - lastArg := arguments[pos] - - if lastArg != "--"+BashCompletionFlag.GetName() { - return false, arguments - } - - return true, arguments[:pos] -} - -func checkCompletions(c *Context) bool { - if !c.shellComplete { - return false - } - - if args := c.Args(); args.Present() { - name := args.First() - if cmd := c.App.Command(name); cmd != nil { - // let the command handle the completion - return false - } - } - - ShowCompletions(c) - return true -} - -func checkCommandCompletions(c *Context, name string) bool { - if !c.shellComplete { - return false - } - - ShowCommandCompletions(c, name) - return true -} diff --git a/vendor/github.com/urfave/cli/parse.go b/vendor/github.com/urfave/cli/parse.go deleted file mode 100644 index 7df17296..00000000 --- a/vendor/github.com/urfave/cli/parse.go +++ /dev/null @@ -1,94 +0,0 @@ -package cli - -import ( - "flag" - "strings" -) - -type iterativeParser interface { - newFlagSet() (*flag.FlagSet, error) - useShortOptionHandling() bool -} - -// To enable short-option handling (e.g., "-it" vs "-i -t") we have to -// iteratively catch parsing errors. This way we achieve LR parsing without -// transforming any arguments. Otherwise, there is no way we can discriminate -// combined short options from common arguments that should be left untouched. -// Pass `shellComplete` to continue parsing options on failure during shell -// completion when, the user-supplied options may be incomplete. -func parseIter(set *flag.FlagSet, ip iterativeParser, args []string, shellComplete bool) error { - for { - err := set.Parse(args) - if !ip.useShortOptionHandling() || err == nil { - if shellComplete { - return nil - } - return err - } - - errStr := err.Error() - trimmed := strings.TrimPrefix(errStr, "flag provided but not defined: -") - if errStr == trimmed { - return err - } - - // regenerate the initial args with the split short opts - argsWereSplit := false - for i, arg := range args { - // skip args that are not part of the error message - if name := strings.TrimLeft(arg, "-"); name != trimmed { - continue - } - - // if we can't split, the error was accurate - shortOpts := splitShortOptions(set, arg) - if len(shortOpts) == 1 { - return err - } - - // swap current argument with the split version - args = append(args[:i], append(shortOpts, args[i+1:]...)...) - argsWereSplit = true - break - } - - // This should be an impossible to reach code path, but in case the arg - // splitting failed to happen, this will prevent infinite loops - if !argsWereSplit { - return err - } - - // Since custom parsing failed, replace the flag set before retrying - newSet, err := ip.newFlagSet() - if err != nil { - return err - } - *set = *newSet - } -} - -func splitShortOptions(set *flag.FlagSet, arg string) []string { - shortFlagsExist := func(s string) bool { - for _, c := range s[1:] { - if f := set.Lookup(string(c)); f == nil { - return false - } - } - return true - } - - if !isSplittable(arg) || !shortFlagsExist(arg) { - return []string{arg} - } - - separated := make([]string, 0, len(arg)-1) - for _, flagChar := range arg[1:] { - separated = append(separated, "-"+string(flagChar)) - } - - return separated -} - -func isSplittable(flagArg string) bool { - return strings.HasPrefix(flagArg, "-") && !strings.HasPrefix(flagArg, "--") && len(flagArg) > 2 -} diff --git a/vendor/github.com/urfave/cli/template.go b/vendor/github.com/urfave/cli/template.go deleted file mode 100644 index c631fb97..00000000 --- a/vendor/github.com/urfave/cli/template.go +++ /dev/null @@ -1,121 +0,0 @@ -package cli - -// AppHelpTemplate is the text template for the Default help topic. -// cli.go uses text/template to render templates. You can -// render custom help text by setting this variable. -var AppHelpTemplate = `NAME: - {{.Name}}{{if .Usage}} - {{.Usage}}{{end}} - -USAGE: - {{if .UsageText}}{{.UsageText}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Version}}{{if not .HideVersion}} - -VERSION: - {{.Version}}{{end}}{{end}}{{if .Description}} - -DESCRIPTION: - {{.Description}}{{end}}{{if len .Authors}} - -AUTHOR{{with $length := len .Authors}}{{if ne 1 $length}}S{{end}}{{end}}: - {{range $index, $author := .Authors}}{{if $index}} - {{end}}{{$author}}{{end}}{{end}}{{if .VisibleCommands}} - -COMMANDS:{{range .VisibleCategories}}{{if .Name}} - - {{.Name}}:{{range .VisibleCommands}} - {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{else}}{{range .VisibleCommands}} - {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{end}}{{end}}{{end}}{{if .VisibleFlags}} - -GLOBAL OPTIONS: - {{range $index, $option := .VisibleFlags}}{{if $index}} - {{end}}{{$option}}{{end}}{{end}}{{if .Copyright}} - -COPYRIGHT: - {{.Copyright}}{{end}} -` - -// CommandHelpTemplate is the text template for the command help topic. -// cli.go uses text/template to render templates. You can -// render custom help text by setting this variable. -var CommandHelpTemplate = `NAME: - {{.HelpName}} - {{.Usage}} - -USAGE: - {{if .UsageText}}{{.UsageText}}{{else}}{{.HelpName}}{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Category}} - -CATEGORY: - {{.Category}}{{end}}{{if .Description}} - -DESCRIPTION: - {{.Description}}{{end}}{{if .VisibleFlags}} - -OPTIONS: - {{range .VisibleFlags}}{{.}} - {{end}}{{end}} -` - -// SubcommandHelpTemplate is the text template for the subcommand help topic. -// cli.go uses text/template to render templates. You can -// render custom help text by setting this variable. -var SubcommandHelpTemplate = `NAME: - {{.HelpName}} - {{if .Description}}{{.Description}}{{else}}{{.Usage}}{{end}} - -USAGE: - {{if .UsageText}}{{.UsageText}}{{else}}{{.HelpName}} command{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}} - -COMMANDS:{{range .VisibleCategories}}{{if .Name}} - - {{.Name}}:{{range .VisibleCommands}} - {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{else}}{{range .VisibleCommands}} - {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{end}}{{end}}{{if .VisibleFlags}} - -OPTIONS: - {{range .VisibleFlags}}{{.}} - {{end}}{{end}} -` - -var MarkdownDocTemplate = `% {{ .App.Name }}(8) {{ .App.Description }} - -% {{ .App.Author }} - -# NAME - -{{ .App.Name }}{{ if .App.Usage }} - {{ .App.Usage }}{{ end }} - -# SYNOPSIS - -{{ .App.Name }} -{{ if .SynopsisArgs }} -` + "```" + ` -{{ range $v := .SynopsisArgs }}{{ $v }}{{ end }}` + "```" + ` -{{ end }}{{ if .App.UsageText }} -# DESCRIPTION - -{{ .App.UsageText }} -{{ end }} -**Usage**: - -` + "```" + ` -{{ .App.Name }} [GLOBAL OPTIONS] command [COMMAND OPTIONS] [ARGUMENTS...] -` + "```" + ` -{{ if .GlobalArgs }} -# GLOBAL OPTIONS -{{ range $v := .GlobalArgs }} -{{ $v }}{{ end }} -{{ end }}{{ if .Commands }} -# COMMANDS -{{ range $v := .Commands }} -{{ $v }}{{ end }}{{ end }}` - -var FishCompletionTemplate = `# {{ .App.Name }} fish shell completion - -function __fish_{{ .App.Name }}_no_subcommand --description 'Test if there has been any subcommand yet' - for i in (commandline -opc) - if contains -- $i{{ range $v := .AllCommands }} {{ $v }}{{ end }} - return 1 - end - end - return 0 -end - -{{ range $v := .Completions }}{{ $v }} -{{ end }}` diff --git a/vendor/github.com/urfave/cli/v2/.flake8 b/vendor/github.com/urfave/cli/v2/.flake8 deleted file mode 100644 index 6deafc26..00000000 --- a/vendor/github.com/urfave/cli/v2/.flake8 +++ /dev/null @@ -1,2 +0,0 @@ -[flake8] -max-line-length = 120 diff --git a/vendor/github.com/urfave/cli/v2/README.md b/vendor/github.com/urfave/cli/v2/README.md deleted file mode 100644 index 9080aee4..00000000 --- a/vendor/github.com/urfave/cli/v2/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# cli - -[![Run Tests](https://github.com/urfave/cli/actions/workflows/cli.yml/badge.svg?branch=v2-maint)](https://github.com/urfave/cli/actions/workflows/cli.yml) -[![Go Reference](https://pkg.go.dev/badge/github.com/urfave/cli/v2.svg)](https://pkg.go.dev/github.com/urfave/cli/v2) -[![Go Report Card](https://goreportcard.com/badge/github.com/urfave/cli/v2)](https://goreportcard.com/report/github.com/urfave/cli/v2) -[![codecov](https://codecov.io/gh/urfave/cli/branch/v2-maint/graph/badge.svg?token=t9YGWLh05g)](https://app.codecov.io/gh/urfave/cli/tree/v2-maint) - -cli is a simple, fast, and fun package for building command line apps in Go. The -goal is to enable developers to write fast and distributable command line -applications in an expressive way. - -## Documentation - -More documentation is available in [`./docs`](./docs) or the hosted -documentation site at . - -## License - -See [`LICENSE`](./LICENSE) diff --git a/vendor/github.com/urfave/cli/v2/app.go b/vendor/github.com/urfave/cli/v2/app.go deleted file mode 100644 index af072e76..00000000 --- a/vendor/github.com/urfave/cli/v2/app.go +++ /dev/null @@ -1,536 +0,0 @@ -package cli - -import ( - "context" - "flag" - "fmt" - "io" - "os" - "path/filepath" - "sort" - "strings" - "time" -) - -const suggestDidYouMeanTemplate = "Did you mean %q?" - -var ( - changeLogURL = "https://github.com/urfave/cli/blob/main/docs/CHANGELOG.md" - appActionDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-action-signature", changeLogURL) - contactSysadmin = "This is an error in the application. Please contact the distributor of this application if this is not you." - errInvalidActionType = NewExitError("ERROR invalid Action type. "+ - fmt.Sprintf("Must be `func(*Context`)` or `func(*Context) error). %s", contactSysadmin)+ - fmt.Sprintf("See %s", appActionDeprecationURL), 2) - ignoreFlagPrefix = "test." // this is to ignore test flags when adding flags from other packages - - SuggestFlag SuggestFlagFunc = nil // initialized in suggestions.go unless built with urfave_cli_no_suggest - SuggestCommand SuggestCommandFunc = nil // initialized in suggestions.go unless built with urfave_cli_no_suggest - SuggestDidYouMeanTemplate string = suggestDidYouMeanTemplate -) - -// App is the main structure of a cli application. It is recommended that -// an app be created with the cli.NewApp() function -type App struct { - // The name of the program. Defaults to path.Base(os.Args[0]) - Name string - // Full name of command for help, defaults to Name - HelpName string - // Description of the program. - Usage string - // Text to override the USAGE section of help - UsageText string - // Whether this command supports arguments - Args bool - // Description of the program argument format. - ArgsUsage string - // Version of the program - Version string - // Description of the program - Description string - // DefaultCommand is the (optional) name of a command - // to run if no command names are passed as CLI arguments. - DefaultCommand string - // List of commands to execute - Commands []*Command - // List of flags to parse - Flags []Flag - // Boolean to enable bash completion commands - EnableBashCompletion bool - // Boolean to hide built-in help command and help flag - HideHelp bool - // Boolean to hide built-in help command but keep help flag. - // Ignored if HideHelp is true. - HideHelpCommand bool - // Boolean to hide built-in version flag and the VERSION section of help - HideVersion bool - // categories contains the categorized commands and is populated on app startup - categories CommandCategories - // flagCategories contains the categorized flags and is populated on app startup - flagCategories FlagCategories - // An action to execute when the shell completion flag is set - BashComplete BashCompleteFunc - // An action to execute before any subcommands are run, but after the context is ready - // If a non-nil error is returned, no subcommands are run - Before BeforeFunc - // An action to execute after any subcommands are run, but after the subcommand has finished - // It is run even if Action() panics - After AfterFunc - // The action to execute when no subcommands are specified - Action ActionFunc - // Execute this function if the proper command cannot be found - CommandNotFound CommandNotFoundFunc - // Execute this function if a usage error occurs - OnUsageError OnUsageErrorFunc - // Execute this function when an invalid flag is accessed from the context - InvalidFlagAccessHandler InvalidFlagAccessFunc - // Compilation date - Compiled time.Time - // List of all authors who contributed - Authors []*Author - // Copyright of the binary if any - Copyright string - // Reader reader to write input to (useful for tests) - Reader io.Reader - // Writer writer to write output to - Writer io.Writer - // ErrWriter writes error output - ErrWriter io.Writer - // ExitErrHandler processes any error encountered while running an App before - // it is returned to the caller. If no function is provided, HandleExitCoder - // is used as the default behavior. - ExitErrHandler ExitErrHandlerFunc - // Other custom info - Metadata map[string]interface{} - // Carries a function which returns app specific info. - ExtraInfo func() map[string]string - // CustomAppHelpTemplate the text template for app help topic. - // cli.go uses text/template to render templates. You can - // render custom help text by setting this variable. - CustomAppHelpTemplate string - // SliceFlagSeparator is used to customize the separator for SliceFlag, the default is "," - SliceFlagSeparator string - // DisableSliceFlagSeparator is used to disable SliceFlagSeparator, the default is false - DisableSliceFlagSeparator bool - // Boolean to enable short-option handling so user can combine several - // single-character bool arguments into one - // i.e. foobar -o -v -> foobar -ov - UseShortOptionHandling bool - // Enable suggestions for commands and flags - Suggest bool - // Allows global flags set by libraries which use flag.XXXVar(...) directly - // to be parsed through this library - AllowExtFlags bool - // Treat all flags as normal arguments if true - SkipFlagParsing bool - - didSetup bool - separator separatorSpec - - rootCommand *Command -} - -type SuggestFlagFunc func(flags []Flag, provided string, hideHelp bool) string - -type SuggestCommandFunc func(commands []*Command, provided string) string - -// Tries to find out when this binary was compiled. -// Returns the current time if it fails to find it. -func compileTime() time.Time { - info, err := os.Stat(os.Args[0]) - if err != nil { - return time.Now() - } - return info.ModTime() -} - -// NewApp creates a new cli Application with some reasonable defaults for Name, -// Usage, Version and Action. -func NewApp() *App { - return &App{ - Name: filepath.Base(os.Args[0]), - Usage: "A new cli application", - UsageText: "", - BashComplete: DefaultAppComplete, - Action: helpCommand.Action, - Compiled: compileTime(), - Reader: os.Stdin, - Writer: os.Stdout, - ErrWriter: os.Stderr, - } -} - -// Setup runs initialization code to ensure all data structures are ready for -// `Run` or inspection prior to `Run`. It is internally called by `Run`, but -// will return early if setup has already happened. -func (a *App) Setup() { - if a.didSetup { - return - } - - a.didSetup = true - - if a.Name == "" { - a.Name = filepath.Base(os.Args[0]) - } - - if a.HelpName == "" { - a.HelpName = a.Name - } - - if a.Usage == "" { - a.Usage = "A new cli application" - } - - if a.Version == "" { - a.HideVersion = true - } - - if a.BashComplete == nil { - a.BashComplete = DefaultAppComplete - } - - if a.Action == nil { - a.Action = helpCommand.Action - } - - if a.Compiled == (time.Time{}) { - a.Compiled = compileTime() - } - - if a.Reader == nil { - a.Reader = os.Stdin - } - - if a.Writer == nil { - a.Writer = os.Stdout - } - - if a.ErrWriter == nil { - a.ErrWriter = os.Stderr - } - - if a.AllowExtFlags { - // add global flags added by other packages - flag.VisitAll(func(f *flag.Flag) { - // skip test flags - if !strings.HasPrefix(f.Name, ignoreFlagPrefix) { - a.Flags = append(a.Flags, &extFlag{f}) - } - }) - } - - if len(a.SliceFlagSeparator) != 0 { - a.separator.customized = true - a.separator.sep = a.SliceFlagSeparator - } - - if a.DisableSliceFlagSeparator { - a.separator.customized = true - a.separator.disabled = true - } - - for _, c := range a.Commands { - cname := c.Name - if c.HelpName != "" { - cname = c.HelpName - } - c.separator = a.separator - c.HelpName = fmt.Sprintf("%s %s", a.HelpName, cname) - c.flagCategories = newFlagCategoriesFromFlags(c.Flags) - } - - if a.Command(helpCommand.Name) == nil && !a.HideHelp { - if !a.HideHelpCommand { - a.appendCommand(helpCommand) - } - - if HelpFlag != nil { - a.appendFlag(HelpFlag) - } - } - - if !a.HideVersion { - a.appendFlag(VersionFlag) - } - - a.categories = newCommandCategories() - for _, command := range a.Commands { - a.categories.AddCommand(command.Category, command) - } - sort.Sort(a.categories.(*commandCategories)) - - a.flagCategories = newFlagCategoriesFromFlags(a.Flags) - - if a.Metadata == nil { - a.Metadata = make(map[string]interface{}) - } -} - -func (a *App) newRootCommand() *Command { - return &Command{ - Name: a.Name, - Usage: a.Usage, - UsageText: a.UsageText, - Description: a.Description, - ArgsUsage: a.ArgsUsage, - BashComplete: a.BashComplete, - Before: a.Before, - After: a.After, - Action: a.Action, - OnUsageError: a.OnUsageError, - Subcommands: a.Commands, - Flags: a.Flags, - flagCategories: a.flagCategories, - HideHelp: a.HideHelp, - HideHelpCommand: a.HideHelpCommand, - UseShortOptionHandling: a.UseShortOptionHandling, - HelpName: a.HelpName, - CustomHelpTemplate: a.CustomAppHelpTemplate, - categories: a.categories, - SkipFlagParsing: a.SkipFlagParsing, - isRoot: true, - separator: a.separator, - } -} - -func (a *App) newFlagSet() (*flag.FlagSet, error) { - return flagSet(a.Name, a.Flags, a.separator) -} - -func (a *App) useShortOptionHandling() bool { - return a.UseShortOptionHandling -} - -// Run is the entry point to the cli app. Parses the arguments slice and routes -// to the proper flag/args combination -func (a *App) Run(arguments []string) (err error) { - return a.RunContext(context.Background(), arguments) -} - -// RunContext is like Run except it takes a Context that will be -// passed to its commands and sub-commands. Through this, you can -// propagate timeouts and cancellation requests -func (a *App) RunContext(ctx context.Context, arguments []string) (err error) { - a.Setup() - - // handle the completion flag separately from the flagset since - // completion could be attempted after a flag, but before its value was put - // on the command line. this causes the flagset to interpret the completion - // flag name as the value of the flag before it which is undesirable - // note that we can only do this because the shell autocomplete function - // always appends the completion flag at the end of the command - shellComplete, arguments := checkShellCompleteFlag(a, arguments) - - cCtx := NewContext(a, nil, &Context{Context: ctx}) - cCtx.shellComplete = shellComplete - - a.rootCommand = a.newRootCommand() - cCtx.Command = a.rootCommand - - if err := checkDuplicatedCmds(a.rootCommand); err != nil { - return err - } - return a.rootCommand.Run(cCtx, arguments...) -} - -// RunAsSubcommand is for legacy/compatibility purposes only. New code should only -// use App.RunContext. This function is slated to be removed in v3. -func (a *App) RunAsSubcommand(ctx *Context) (err error) { - a.Setup() - - cCtx := NewContext(a, nil, ctx) - cCtx.shellComplete = ctx.shellComplete - - a.rootCommand = a.newRootCommand() - cCtx.Command = a.rootCommand - - return a.rootCommand.Run(cCtx, ctx.Args().Slice()...) -} - -func (a *App) suggestFlagFromError(err error, command string) (string, error) { - flag, parseErr := flagFromError(err) - if parseErr != nil { - return "", err - } - - flags := a.Flags - hideHelp := a.HideHelp - if command != "" { - cmd := a.Command(command) - if cmd == nil { - return "", err - } - flags = cmd.Flags - hideHelp = hideHelp || cmd.HideHelp - } - - if SuggestFlag == nil { - return "", err - } - suggestion := SuggestFlag(flags, flag, hideHelp) - if len(suggestion) == 0 { - return "", err - } - - return fmt.Sprintf(SuggestDidYouMeanTemplate+"\n\n", suggestion), nil -} - -// RunAndExitOnError calls .Run() and exits non-zero if an error was returned -// -// Deprecated: instead you should return an error that fulfills cli.ExitCoder -// to cli.App.Run. This will cause the application to exit with the given error -// code in the cli.ExitCoder -func (a *App) RunAndExitOnError() { - if err := a.Run(os.Args); err != nil { - _, _ = fmt.Fprintln(a.ErrWriter, err) - OsExiter(1) - } -} - -// Command returns the named command on App. Returns nil if the command does not exist -func (a *App) Command(name string) *Command { - for _, c := range a.Commands { - if c.HasName(name) { - return c - } - } - - return nil -} - -// VisibleCategories returns a slice of categories and commands that are -// Hidden=false -func (a *App) VisibleCategories() []CommandCategory { - ret := []CommandCategory{} - for _, category := range a.categories.Categories() { - if visible := func() CommandCategory { - if len(category.VisibleCommands()) > 0 { - return category - } - return nil - }(); visible != nil { - ret = append(ret, visible) - } - } - return ret -} - -// VisibleCommands returns a slice of the Commands with Hidden=false -func (a *App) VisibleCommands() []*Command { - var ret []*Command - for _, command := range a.Commands { - if !command.Hidden { - ret = append(ret, command) - } - } - return ret -} - -// VisibleFlagCategories returns a slice containing all the categories with the flags they contain -func (a *App) VisibleFlagCategories() []VisibleFlagCategory { - if a.flagCategories == nil { - return []VisibleFlagCategory{} - } - return a.flagCategories.VisibleCategories() -} - -// VisibleFlags returns a slice of the Flags with Hidden=false -func (a *App) VisibleFlags() []Flag { - return visibleFlags(a.Flags) -} - -func (a *App) appendFlag(fl Flag) { - if !hasFlag(a.Flags, fl) { - a.Flags = append(a.Flags, fl) - } -} - -func (a *App) appendCommand(c *Command) { - if !hasCommand(a.Commands, c) { - a.Commands = append(a.Commands, c) - } -} - -func (a *App) handleExitCoder(cCtx *Context, err error) { - if a.ExitErrHandler != nil { - a.ExitErrHandler(cCtx, err) - } else { - HandleExitCoder(err) - } -} - -func (a *App) argsWithDefaultCommand(oldArgs Args) Args { - if a.DefaultCommand != "" { - rawArgs := append([]string{a.DefaultCommand}, oldArgs.Slice()...) - newArgs := args(rawArgs) - - return &newArgs - } - - return oldArgs -} - -func runFlagActions(c *Context, fs []Flag) error { - for _, f := range fs { - isSet := false - for _, name := range f.Names() { - if c.IsSet(name) { - isSet = true - break - } - } - if isSet { - if af, ok := f.(ActionableFlag); ok { - if err := af.RunAction(c); err != nil { - return err - } - } - } - } - return nil -} - -// Author represents someone who has contributed to a cli project. -type Author struct { - Name string // The Authors name - Email string // The Authors email -} - -// String makes Author comply to the Stringer interface, to allow an easy print in the templating process -func (a *Author) String() string { - e := "" - if a.Email != "" { - e = " <" + a.Email + ">" - } - - return fmt.Sprintf("%v%v", a.Name, e) -} - -// HandleAction attempts to figure out which Action signature was used. If -// it's an ActionFunc or a func with the legacy signature for Action, the func -// is run! -func HandleAction(action interface{}, cCtx *Context) (err error) { - switch a := action.(type) { - case ActionFunc: - return a(cCtx) - case func(*Context) error: - return a(cCtx) - case func(*Context): // deprecated function signature - a(cCtx) - return nil - } - - return errInvalidActionType -} - -func checkStringSliceIncludes(want string, sSlice []string) bool { - found := false - for _, s := range sSlice { - if want == s { - found = true - break - } - } - - return found -} diff --git a/vendor/github.com/urfave/cli/v2/args.go b/vendor/github.com/urfave/cli/v2/args.go deleted file mode 100644 index bd65c17b..00000000 --- a/vendor/github.com/urfave/cli/v2/args.go +++ /dev/null @@ -1,54 +0,0 @@ -package cli - -type Args interface { - // Get returns the nth argument, or else a blank string - Get(n int) string - // First returns the first argument, or else a blank string - First() string - // Tail returns the rest of the arguments (not the first one) - // or else an empty string slice - Tail() []string - // Len returns the length of the wrapped slice - Len() int - // Present checks if there are any arguments present - Present() bool - // Slice returns a copy of the internal slice - Slice() []string -} - -type args []string - -func (a *args) Get(n int) string { - if len(*a) > n { - return (*a)[n] - } - return "" -} - -func (a *args) First() string { - return a.Get(0) -} - -func (a *args) Tail() []string { - if a.Len() >= 2 { - tail := []string((*a)[1:]) - ret := make([]string, len(tail)) - copy(ret, tail) - return ret - } - return []string{} -} - -func (a *args) Len() int { - return len(*a) -} - -func (a *args) Present() bool { - return a.Len() != 0 -} - -func (a *args) Slice() []string { - ret := make([]string, len(*a)) - copy(ret, *a) - return ret -} diff --git a/vendor/github.com/urfave/cli/v2/cli.go b/vendor/github.com/urfave/cli/v2/cli.go deleted file mode 100644 index 28ad0582..00000000 --- a/vendor/github.com/urfave/cli/v2/cli.go +++ /dev/null @@ -1,25 +0,0 @@ -// Package cli provides a minimal framework for creating and organizing command line -// Go applications. cli is designed to be easy to understand and write, the most simple -// cli application can be written as follows: -// -// func main() { -// (&cli.App{}).Run(os.Args) -// } -// -// Of course this application does not do much, so let's make this an actual application: -// -// func main() { -// app := &cli.App{ -// Name: "greet", -// Usage: "say a greeting", -// Action: func(c *cli.Context) error { -// fmt.Println("Greetings") -// return nil -// }, -// } -// -// app.Run(os.Args) -// } -package cli - -//go:generate make -C cmd/urfave-cli-genflags run diff --git a/vendor/github.com/urfave/cli/v2/command.go b/vendor/github.com/urfave/cli/v2/command.go deleted file mode 100644 index 472c1ff4..00000000 --- a/vendor/github.com/urfave/cli/v2/command.go +++ /dev/null @@ -1,421 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "reflect" - "sort" - "strings" -) - -// Command is a subcommand for a cli.App. -type Command struct { - // The name of the command - Name string - // A list of aliases for the command - Aliases []string - // A short description of the usage of this command - Usage string - // Custom text to show on USAGE section of help - UsageText string - // A longer explanation of how the command works - Description string - // Whether this command supports arguments - Args bool - // A short description of the arguments of this command - ArgsUsage string - // The category the command is part of - Category string - // The function to call when checking for bash command completions - BashComplete BashCompleteFunc - // An action to execute before any sub-subcommands are run, but after the context is ready - // If a non-nil error is returned, no sub-subcommands are run - Before BeforeFunc - // An action to execute after any subcommands are run, but after the subcommand has finished - // It is run even if Action() panics - After AfterFunc - // The function to call when this command is invoked - Action ActionFunc - // Execute this function if a usage error occurs. - OnUsageError OnUsageErrorFunc - // List of child commands - Subcommands []*Command - // List of flags to parse - Flags []Flag - flagCategories FlagCategories - // Treat all flags as normal arguments if true - SkipFlagParsing bool - // Boolean to hide built-in help command and help flag - HideHelp bool - // Boolean to hide built-in help command but keep help flag - // Ignored if HideHelp is true. - HideHelpCommand bool - // Boolean to hide this command from help or completion - Hidden bool - // Boolean to enable short-option handling so user can combine several - // single-character bool arguments into one - // i.e. foobar -o -v -> foobar -ov - UseShortOptionHandling bool - - // Full name of command for help, defaults to full command name, including parent commands. - HelpName string - commandNamePath []string - - // CustomHelpTemplate the text template for the command help topic. - // cli.go uses text/template to render templates. You can - // render custom help text by setting this variable. - CustomHelpTemplate string - - // categories contains the categorized commands and is populated on app startup - categories CommandCategories - - // if this is a root "special" command - isRoot bool - - separator separatorSpec -} - -type Commands []*Command - -type CommandsByName []*Command - -func (c CommandsByName) Len() int { - return len(c) -} - -func (c CommandsByName) Less(i, j int) bool { - return lexicographicLess(c[i].Name, c[j].Name) -} - -func (c CommandsByName) Swap(i, j int) { - c[i], c[j] = c[j], c[i] -} - -// FullName returns the full name of the command. -// For subcommands this ensures that parent commands are part of the command path -func (c *Command) FullName() string { - if c.commandNamePath == nil { - return c.Name - } - return strings.Join(c.commandNamePath, " ") -} - -func (cmd *Command) Command(name string) *Command { - for _, c := range cmd.Subcommands { - if c.HasName(name) { - return c - } - } - - return nil -} - -func (c *Command) setup(ctx *Context) { - if c.Command(helpCommand.Name) == nil && !c.HideHelp { - if !c.HideHelpCommand { - c.Subcommands = append(c.Subcommands, helpCommand) - } - } - - if !c.HideHelp && HelpFlag != nil { - // append help to flags - c.appendFlag(HelpFlag) - } - - if ctx.App.UseShortOptionHandling { - c.UseShortOptionHandling = true - } - - c.categories = newCommandCategories() - for _, command := range c.Subcommands { - c.categories.AddCommand(command.Category, command) - } - sort.Sort(c.categories.(*commandCategories)) - - for _, scmd := range c.Subcommands { - if scmd.HelpName == "" { - scmd.HelpName = fmt.Sprintf("%s %s", c.HelpName, scmd.Name) - } - scmd.separator = c.separator - } - - if c.BashComplete == nil { - c.BashComplete = DefaultCompleteWithFlags(c) - } -} - -func (c *Command) Run(cCtx *Context, arguments ...string) (err error) { - - if !c.isRoot { - c.setup(cCtx) - if err := checkDuplicatedCmds(c); err != nil { - return err - } - } - - a := args(arguments) - set, err := c.parseFlags(&a, cCtx.shellComplete) - cCtx.flagSet = set - - if checkCompletions(cCtx) { - return nil - } - - if err != nil { - if c.OnUsageError != nil { - err = c.OnUsageError(cCtx, err, !c.isRoot) - cCtx.App.handleExitCoder(cCtx, err) - return err - } - _, _ = fmt.Fprintf(cCtx.App.Writer, "%s %s\n\n", "Incorrect Usage:", err.Error()) - if cCtx.App.Suggest { - if suggestion, err := c.suggestFlagFromError(err, ""); err == nil { - fmt.Fprintf(cCtx.App.Writer, "%s", suggestion) - } - } - if !c.HideHelp { - if c.isRoot { - _ = ShowAppHelp(cCtx) - } else { - _ = ShowCommandHelp(cCtx.parentContext, c.Name) - } - } - return err - } - - if checkHelp(cCtx) { - return helpCommand.Action(cCtx) - } - - if c.isRoot && !cCtx.App.HideVersion && checkVersion(cCtx) { - ShowVersion(cCtx) - return nil - } - - if c.After != nil && !cCtx.shellComplete { - defer func() { - afterErr := c.After(cCtx) - if afterErr != nil { - cCtx.App.handleExitCoder(cCtx, err) - if err != nil { - err = newMultiError(err, afterErr) - } else { - err = afterErr - } - } - }() - } - - cerr := cCtx.checkRequiredFlags(c.Flags) - if cerr != nil { - _ = helpCommand.Action(cCtx) - return cerr - } - - if c.Before != nil && !cCtx.shellComplete { - beforeErr := c.Before(cCtx) - if beforeErr != nil { - cCtx.App.handleExitCoder(cCtx, beforeErr) - err = beforeErr - return err - } - } - - if err = runFlagActions(cCtx, c.Flags); err != nil { - return err - } - - var cmd *Command - args := cCtx.Args() - if args.Present() { - name := args.First() - cmd = c.Command(name) - if cmd == nil { - hasDefault := cCtx.App.DefaultCommand != "" - isFlagName := checkStringSliceIncludes(name, cCtx.FlagNames()) - - var ( - isDefaultSubcommand = false - defaultHasSubcommands = false - ) - - if hasDefault { - dc := cCtx.App.Command(cCtx.App.DefaultCommand) - defaultHasSubcommands = len(dc.Subcommands) > 0 - for _, dcSub := range dc.Subcommands { - if checkStringSliceIncludes(name, dcSub.Names()) { - isDefaultSubcommand = true - break - } - } - } - - if isFlagName || (hasDefault && (defaultHasSubcommands && isDefaultSubcommand)) { - argsWithDefault := cCtx.App.argsWithDefaultCommand(args) - if !reflect.DeepEqual(args, argsWithDefault) { - cmd = cCtx.App.rootCommand.Command(argsWithDefault.First()) - } - } - } - } else if c.isRoot && cCtx.App.DefaultCommand != "" { - if dc := cCtx.App.Command(cCtx.App.DefaultCommand); dc != c { - cmd = dc - } - } - - if cmd != nil { - newcCtx := NewContext(cCtx.App, nil, cCtx) - newcCtx.Command = cmd - return cmd.Run(newcCtx, cCtx.Args().Slice()...) - } - - if c.Action == nil { - c.Action = helpCommand.Action - } - - err = c.Action(cCtx) - - cCtx.App.handleExitCoder(cCtx, err) - return err -} - -func (c *Command) newFlagSet() (*flag.FlagSet, error) { - return flagSet(c.Name, c.Flags, c.separator) -} - -func (c *Command) useShortOptionHandling() bool { - return c.UseShortOptionHandling -} - -func (c *Command) suggestFlagFromError(err error, command string) (string, error) { - flag, parseErr := flagFromError(err) - if parseErr != nil { - return "", err - } - - flags := c.Flags - hideHelp := c.HideHelp - if command != "" { - cmd := c.Command(command) - if cmd == nil { - return "", err - } - flags = cmd.Flags - hideHelp = hideHelp || cmd.HideHelp - } - - suggestion := SuggestFlag(flags, flag, hideHelp) - if len(suggestion) == 0 { - return "", err - } - - return fmt.Sprintf(SuggestDidYouMeanTemplate, suggestion) + "\n\n", nil -} - -func (c *Command) parseFlags(args Args, shellComplete bool) (*flag.FlagSet, error) { - set, err := c.newFlagSet() - if err != nil { - return nil, err - } - - if c.SkipFlagParsing { - return set, set.Parse(append([]string{"--"}, args.Tail()...)) - } - - err = parseIter(set, c, args.Tail(), shellComplete) - if err != nil { - return nil, err - } - - err = normalizeFlags(c.Flags, set) - if err != nil { - return nil, err - } - - return set, nil -} - -// Names returns the names including short names and aliases. -func (c *Command) Names() []string { - return append([]string{c.Name}, c.Aliases...) -} - -// HasName returns true if Command.Name matches given name -func (c *Command) HasName(name string) bool { - for _, n := range c.Names() { - if n == name { - return true - } - } - return false -} - -// VisibleCategories returns a slice of categories and commands that are -// Hidden=false -func (c *Command) VisibleCategories() []CommandCategory { - ret := []CommandCategory{} - for _, category := range c.categories.Categories() { - if visible := func() CommandCategory { - if len(category.VisibleCommands()) > 0 { - return category - } - return nil - }(); visible != nil { - ret = append(ret, visible) - } - } - return ret -} - -// VisibleCommands returns a slice of the Commands with Hidden=false -func (c *Command) VisibleCommands() []*Command { - var ret []*Command - for _, command := range c.Subcommands { - if !command.Hidden { - ret = append(ret, command) - } - } - return ret -} - -// VisibleFlagCategories returns a slice containing all the visible flag categories with the flags they contain -func (c *Command) VisibleFlagCategories() []VisibleFlagCategory { - if c.flagCategories == nil { - c.flagCategories = newFlagCategoriesFromFlags(c.Flags) - } - return c.flagCategories.VisibleCategories() -} - -// VisibleFlags returns a slice of the Flags with Hidden=false -func (c *Command) VisibleFlags() []Flag { - return visibleFlags(c.Flags) -} - -func (c *Command) appendFlag(fl Flag) { - if !hasFlag(c.Flags, fl) { - c.Flags = append(c.Flags, fl) - } -} - -func hasCommand(commands []*Command, command *Command) bool { - for _, existing := range commands { - if command == existing { - return true - } - } - - return false -} - -func checkDuplicatedCmds(parent *Command) error { - seen := make(map[string]struct{}) - for _, c := range parent.Subcommands { - for _, name := range c.Names() { - if _, exists := seen[name]; exists { - return fmt.Errorf("parent command [%s] has duplicated subcommand name or alias: %s", parent.Name, name) - } - seen[name] = struct{}{} - } - } - return nil -} diff --git a/vendor/github.com/urfave/cli/v2/context.go b/vendor/github.com/urfave/cli/v2/context.go deleted file mode 100644 index 8dd47652..00000000 --- a/vendor/github.com/urfave/cli/v2/context.go +++ /dev/null @@ -1,272 +0,0 @@ -package cli - -import ( - "context" - "flag" - "fmt" - "strings" -) - -// Context is a type that is passed through to -// each Handler action in a cli application. Context -// can be used to retrieve context-specific args and -// parsed command-line options. -type Context struct { - context.Context - App *App - Command *Command - shellComplete bool - flagSet *flag.FlagSet - parentContext *Context -} - -// NewContext creates a new context. For use in when invoking an App or Command action. -func NewContext(app *App, set *flag.FlagSet, parentCtx *Context) *Context { - c := &Context{App: app, flagSet: set, parentContext: parentCtx} - if parentCtx != nil { - c.Context = parentCtx.Context - c.shellComplete = parentCtx.shellComplete - if parentCtx.flagSet == nil { - parentCtx.flagSet = &flag.FlagSet{} - } - } - - c.Command = &Command{} - - if c.Context == nil { - c.Context = context.Background() - } - - return c -} - -// NumFlags returns the number of flags set -func (cCtx *Context) NumFlags() int { - return cCtx.flagSet.NFlag() -} - -// Set sets a context flag to a value. -func (cCtx *Context) Set(name, value string) error { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return fs.Set(name, value) - } - - return fmt.Errorf("no such flag -%s", name) -} - -// IsSet determines if the flag was actually set -func (cCtx *Context) IsSet(name string) bool { - - if fs := cCtx.lookupFlagSet(name); fs != nil { - isSet := false - fs.Visit(func(f *flag.Flag) { - if f.Name == name { - isSet = true - } - }) - if isSet { - return true - } - - f := cCtx.lookupFlag(name) - if f == nil { - return false - } - - if f.IsSet() { - return true - } - - // now redo flagset search on aliases - aliases := f.Names() - fs.Visit(func(f *flag.Flag) { - for _, alias := range aliases { - if f.Name == alias { - isSet = true - } - } - }) - - if isSet { - return true - } - } - - return false -} - -// LocalFlagNames returns a slice of flag names used in this context. -func (cCtx *Context) LocalFlagNames() []string { - var names []string - cCtx.flagSet.Visit(makeFlagNameVisitor(&names)) - // Check the flags which have been set via env or file - if cCtx.Command != nil && cCtx.Command.Flags != nil { - for _, f := range cCtx.Command.Flags { - if f.IsSet() { - names = append(names, f.Names()...) - } - } - } - - // Sort out the duplicates since flag could be set via multiple - // paths - m := map[string]struct{}{} - var unames []string - for _, name := range names { - if _, ok := m[name]; !ok { - m[name] = struct{}{} - unames = append(unames, name) - } - } - - return unames -} - -// FlagNames returns a slice of flag names used by the this context and all of -// its parent contexts. -func (cCtx *Context) FlagNames() []string { - var names []string - for _, pCtx := range cCtx.Lineage() { - names = append(names, pCtx.LocalFlagNames()...) - } - return names -} - -// Lineage returns *this* context and all of its ancestor contexts in order from -// child to parent -func (cCtx *Context) Lineage() []*Context { - var lineage []*Context - - for cur := cCtx; cur != nil; cur = cur.parentContext { - lineage = append(lineage, cur) - } - - return lineage -} - -// Count returns the num of occurrences of this flag -func (cCtx *Context) Count(name string) int { - if fs := cCtx.lookupFlagSet(name); fs != nil { - if cf, ok := fs.Lookup(name).Value.(Countable); ok { - return cf.Count() - } - } - return 0 -} - -// Value returns the value of the flag corresponding to `name` -func (cCtx *Context) Value(name string) interface{} { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return fs.Lookup(name).Value.(flag.Getter).Get() - } - return nil -} - -// Args returns the command line arguments associated with the context. -func (cCtx *Context) Args() Args { - ret := args(cCtx.flagSet.Args()) - return &ret -} - -// NArg returns the number of the command line arguments. -func (cCtx *Context) NArg() int { - return cCtx.Args().Len() -} - -func (cCtx *Context) lookupFlag(name string) Flag { - for _, c := range cCtx.Lineage() { - if c.Command == nil { - continue - } - - for _, f := range c.Command.Flags { - for _, n := range f.Names() { - if n == name { - return f - } - } - } - } - - if cCtx.App != nil { - for _, f := range cCtx.App.Flags { - for _, n := range f.Names() { - if n == name { - return f - } - } - } - } - - return nil -} - -func (cCtx *Context) lookupFlagSet(name string) *flag.FlagSet { - for _, c := range cCtx.Lineage() { - if c.flagSet == nil { - continue - } - if f := c.flagSet.Lookup(name); f != nil { - return c.flagSet - } - } - cCtx.onInvalidFlag(name) - return nil -} - -func (cCtx *Context) checkRequiredFlags(flags []Flag) requiredFlagsErr { - var missingFlags []string - for _, f := range flags { - if rf, ok := f.(RequiredFlag); ok && rf.IsRequired() { - var flagPresent bool - var flagName string - - flagNames := f.Names() - flagName = flagNames[0] - - for _, key := range flagNames { - if cCtx.IsSet(strings.TrimSpace(key)) { - flagPresent = true - } - } - - if !flagPresent && flagName != "" { - missingFlags = append(missingFlags, flagName) - } - } - } - - if len(missingFlags) != 0 { - return &errRequiredFlags{missingFlags: missingFlags} - } - - return nil -} - -func (cCtx *Context) onInvalidFlag(name string) { - for cCtx != nil { - if cCtx.App != nil && cCtx.App.InvalidFlagAccessHandler != nil { - cCtx.App.InvalidFlagAccessHandler(cCtx, name) - break - } - cCtx = cCtx.parentContext - } -} - -func makeFlagNameVisitor(names *[]string) func(*flag.Flag) { - return func(f *flag.Flag) { - nameParts := strings.Split(f.Name, ",") - name := strings.TrimSpace(nameParts[0]) - - for _, part := range nameParts { - part = strings.TrimSpace(part) - if len(part) > len(name) { - name = part - } - } - - if name != "" { - *names = append(*names, name) - } - } -} diff --git a/vendor/github.com/urfave/cli/v2/docs.go b/vendor/github.com/urfave/cli/v2/docs.go deleted file mode 100644 index 6cd0624a..00000000 --- a/vendor/github.com/urfave/cli/v2/docs.go +++ /dev/null @@ -1,203 +0,0 @@ -//go:build !urfave_cli_no_docs -// +build !urfave_cli_no_docs - -package cli - -import ( - "bytes" - "fmt" - "io" - "sort" - "strings" - "text/template" - - "github.com/cpuguy83/go-md2man/v2/md2man" -) - -// ToMarkdown creates a markdown string for the `*App` -// The function errors if either parsing or writing of the string fails. -func (a *App) ToMarkdown() (string, error) { - var w bytes.Buffer - if err := a.writeDocTemplate(&w, 0); err != nil { - return "", err - } - return w.String(), nil -} - -// ToMan creates a man page string with section number for the `*App` -// The function errors if either parsing or writing of the string fails. -func (a *App) ToManWithSection(sectionNumber int) (string, error) { - var w bytes.Buffer - if err := a.writeDocTemplate(&w, sectionNumber); err != nil { - return "", err - } - man := md2man.Render(w.Bytes()) - return string(man), nil -} - -// ToMan creates a man page string for the `*App` -// The function errors if either parsing or writing of the string fails. -func (a *App) ToMan() (string, error) { - man, err := a.ToManWithSection(8) - return man, err -} - -type cliTemplate struct { - App *App - SectionNum int - Commands []string - GlobalArgs []string - SynopsisArgs []string -} - -func (a *App) writeDocTemplate(w io.Writer, sectionNum int) error { - const name = "cli" - t, err := template.New(name).Parse(MarkdownDocTemplate) - if err != nil { - return err - } - return t.ExecuteTemplate(w, name, &cliTemplate{ - App: a, - SectionNum: sectionNum, - Commands: prepareCommands(a.Commands, 0), - GlobalArgs: prepareArgsWithValues(a.VisibleFlags()), - SynopsisArgs: prepareArgsSynopsis(a.VisibleFlags()), - }) -} - -func prepareCommands(commands []*Command, level int) []string { - var coms []string - for _, command := range commands { - if command.Hidden { - continue - } - - usageText := prepareUsageText(command) - - usage := prepareUsage(command, usageText) - - prepared := fmt.Sprintf("%s %s\n\n%s%s", - strings.Repeat("#", level+2), - strings.Join(command.Names(), ", "), - usage, - usageText, - ) - - flags := prepareArgsWithValues(command.VisibleFlags()) - if len(flags) > 0 { - prepared += fmt.Sprintf("\n%s", strings.Join(flags, "\n")) - } - - coms = append(coms, prepared) - - // recursively iterate subcommands - if len(command.Subcommands) > 0 { - coms = append( - coms, - prepareCommands(command.Subcommands, level+1)..., - ) - } - } - - return coms -} - -func prepareArgsWithValues(flags []Flag) []string { - return prepareFlags(flags, ", ", "**", "**", `""`, true) -} - -func prepareArgsSynopsis(flags []Flag) []string { - return prepareFlags(flags, "|", "[", "]", "[value]", false) -} - -func prepareFlags( - flags []Flag, - sep, opener, closer, value string, - addDetails bool, -) []string { - args := []string{} - for _, f := range flags { - flag, ok := f.(DocGenerationFlag) - if !ok { - continue - } - modifiedArg := opener - - for _, s := range flag.Names() { - trimmed := strings.TrimSpace(s) - if len(modifiedArg) > len(opener) { - modifiedArg += sep - } - if len(trimmed) > 1 { - modifiedArg += fmt.Sprintf("--%s", trimmed) - } else { - modifiedArg += fmt.Sprintf("-%s", trimmed) - } - } - modifiedArg += closer - if flag.TakesValue() { - modifiedArg += fmt.Sprintf("=%s", value) - } - - if addDetails { - modifiedArg += flagDetails(flag) - } - - args = append(args, modifiedArg+"\n") - - } - sort.Strings(args) - return args -} - -// flagDetails returns a string containing the flags metadata -func flagDetails(flag DocGenerationFlag) string { - description := flag.GetUsage() - if flag.TakesValue() { - defaultText := flag.GetDefaultText() - if defaultText == "" { - defaultText = flag.GetValue() - } - if defaultText != "" { - description += " (default: " + defaultText + ")" - } - } - return ": " + description -} - -func prepareUsageText(command *Command) string { - if command.UsageText == "" { - return "" - } - - // Remove leading and trailing newlines - preparedUsageText := strings.Trim(command.UsageText, "\n") - - var usageText string - if strings.Contains(preparedUsageText, "\n") { - // Format multi-line string as a code block using the 4 space schema to allow for embedded markdown such - // that it will not break the continuous code block. - for _, ln := range strings.Split(preparedUsageText, "\n") { - usageText += fmt.Sprintf(" %s\n", ln) - } - } else { - // Style a single line as a note - usageText = fmt.Sprintf(">%s\n", preparedUsageText) - } - - return usageText -} - -func prepareUsage(command *Command, usageText string) string { - if command.Usage == "" { - return "" - } - - usage := command.Usage + "\n" - // Add a newline to the Usage IFF there is a UsageText - if usageText != "" { - usage += "\n" - } - - return usage -} diff --git a/vendor/github.com/urfave/cli/v2/flag-spec.yaml b/vendor/github.com/urfave/cli/v2/flag-spec.yaml deleted file mode 100644 index 03d82e70..00000000 --- a/vendor/github.com/urfave/cli/v2/flag-spec.yaml +++ /dev/null @@ -1,131 +0,0 @@ -# NOTE: this file is used by the tool defined in -# ./cmd/urfave-cli-genflags/main.go which uses the -# `Spec` type that maps to this file structure. -flag_types: - bool: - struct_fields: - - name: Count - type: int - pointer: true - - name: DisableDefaultText - type: bool - - name: Action - type: "func(*Context, bool) error" - float64: - struct_fields: - - name: Action - type: "func(*Context, float64) error" - Float64Slice: - value_pointer: true - skip_interfaces: - - fmt.Stringer - struct_fields: - - name: separator - type: separatorSpec - - name: Action - type: "func(*Context, []float64) error" - int: - struct_fields: - - name: Base - type: int - - name: Action - type: "func(*Context, int) error" - IntSlice: - value_pointer: true - skip_interfaces: - - fmt.Stringer - struct_fields: - - name: separator - type: separatorSpec - - name: Action - type: "func(*Context, []int) error" - int64: - struct_fields: - - name: Base - type: int - - name: Action - type: "func(*Context, int64) error" - Int64Slice: - value_pointer: true - skip_interfaces: - - fmt.Stringer - struct_fields: - - name: separator - type: separatorSpec - - name: Action - type: "func(*Context, []int64) error" - uint: - struct_fields: - - name: Base - type: int - - name: Action - type: "func(*Context, uint) error" - UintSlice: - value_pointer: true - skip_interfaces: - - fmt.Stringer - struct_fields: - - name: separator - type: separatorSpec - - name: Action - type: "func(*Context, []uint) error" - uint64: - struct_fields: - - name: Base - type: int - - name: Action - type: "func(*Context, uint64) error" - Uint64Slice: - value_pointer: true - skip_interfaces: - - fmt.Stringer - struct_fields: - - name: separator - type: separatorSpec - - name: Action - type: "func(*Context, []uint64) error" - string: - struct_fields: - - name: TakesFile - type: bool - - name: Action - type: "func(*Context, string) error" - StringSlice: - value_pointer: true - skip_interfaces: - - fmt.Stringer - struct_fields: - - name: separator - type: separatorSpec - - name: TakesFile - type: bool - - name: Action - type: "func(*Context, []string) error" - - name: KeepSpace - type: bool - time.Duration: - struct_fields: - - name: Action - type: "func(*Context, time.Duration) error" - Timestamp: - value_pointer: true - struct_fields: - - name: Layout - type: string - - name: Timezone - type: "*time.Location" - - name: Action - type: "func(*Context, *time.Time) error" - Generic: - no_destination_pointer: true - struct_fields: - - name: TakesFile - type: bool - - name: Action - type: "func(*Context, interface{}) error" - Path: - struct_fields: - - name: TakesFile - type: bool - - name: Action - type: "func(*Context, Path) error" diff --git a/vendor/github.com/urfave/cli/v2/flag_bool.go b/vendor/github.com/urfave/cli/v2/flag_bool.go deleted file mode 100644 index 01862ea7..00000000 --- a/vendor/github.com/urfave/cli/v2/flag_bool.go +++ /dev/null @@ -1,178 +0,0 @@ -package cli - -import ( - "errors" - "flag" - "fmt" - "strconv" -) - -// boolValue needs to implement the boolFlag internal interface in flag -// to be able to capture bool fields and values -// -// type boolFlag interface { -// Value -// IsBoolFlag() bool -// } -type boolValue struct { - destination *bool - count *int -} - -func newBoolValue(val bool, p *bool, count *int) *boolValue { - *p = val - return &boolValue{ - destination: p, - count: count, - } -} - -func (b *boolValue) Set(s string) error { - v, err := strconv.ParseBool(s) - if err != nil { - err = errors.New("parse error") - return err - } - *b.destination = v - if b.count != nil { - *b.count = *b.count + 1 - } - return err -} - -func (b *boolValue) Get() interface{} { return *b.destination } - -func (b *boolValue) String() string { - if b.destination != nil { - return strconv.FormatBool(*b.destination) - } - return strconv.FormatBool(false) -} - -func (b *boolValue) IsBoolFlag() bool { return true } - -func (b *boolValue) Count() int { - if b.count != nil && *b.count > 0 { - return *b.count - } - return 0 -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f *BoolFlag) TakesValue() bool { - return false -} - -// GetUsage returns the usage string for the flag -func (f *BoolFlag) GetUsage() string { - return f.Usage -} - -// GetCategory returns the category for the flag -func (f *BoolFlag) GetCategory() string { - return f.Category -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f *BoolFlag) GetValue() string { - return "" -} - -// GetDefaultText returns the default text for this flag -func (f *BoolFlag) GetDefaultText() string { - if f.DefaultText != "" { - return f.DefaultText - } - if f.defaultValueSet { - return fmt.Sprintf("%v", f.defaultValue) - } - return fmt.Sprintf("%v", f.Value) -} - -// GetEnvVars returns the env vars for this flag -func (f *BoolFlag) GetEnvVars() []string { - return f.EnvVars -} - -// RunAction executes flag action if set -func (f *BoolFlag) RunAction(c *Context) error { - if f.Action != nil { - return f.Action(c, c.Bool(f.Name)) - } - - return nil -} - -// Apply populates the flag given the flag set and environment -func (f *BoolFlag) Apply(set *flag.FlagSet) error { - // set default value so that environment wont be able to overwrite it - f.defaultValue = f.Value - f.defaultValueSet = true - - if val, source, found := flagFromEnvOrFile(f.EnvVars, f.FilePath); found { - if val != "" { - valBool, err := strconv.ParseBool(val) - - if err != nil { - return fmt.Errorf("could not parse %q as bool value from %s for flag %s: %s", val, source, f.Name, err) - } - - f.Value = valBool - } else { - // empty value implies that the env is defined but set to empty string, we have to assume that this is - // what the user wants. If user doesnt want this then the env needs to be deleted or the flag removed from - // file - f.Value = false - } - f.HasBeenSet = true - } - - count := f.Count - dest := f.Destination - - if count == nil { - count = new(int) - } - - // since count will be incremented for each alias as well - // subtract number of aliases from overall count - *count -= len(f.Aliases) - - if dest == nil { - dest = new(bool) - } - - for _, name := range f.Names() { - value := newBoolValue(f.Value, dest, count) - set.Var(value, name, f.Usage) - } - - return nil -} - -// Get returns the flag’s value in the given Context. -func (f *BoolFlag) Get(ctx *Context) bool { - return ctx.Bool(f.Name) -} - -// Bool looks up the value of a local BoolFlag, returns -// false if not found -func (cCtx *Context) Bool(name string) bool { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return lookupBool(name, fs) - } - return false -} - -func lookupBool(name string, set *flag.FlagSet) bool { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseBool(f.Value.String()) - if err != nil { - return false - } - return parsed - } - return false -} diff --git a/vendor/github.com/urfave/cli/v2/flag_duration.go b/vendor/github.com/urfave/cli/v2/flag_duration.go deleted file mode 100644 index e600cc30..00000000 --- a/vendor/github.com/urfave/cli/v2/flag_duration.go +++ /dev/null @@ -1,108 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "time" -) - -// TakesValue returns true of the flag takes a value, otherwise false -func (f *DurationFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f *DurationFlag) GetUsage() string { - return f.Usage -} - -// GetCategory returns the category for the flag -func (f *DurationFlag) GetCategory() string { - return f.Category -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f *DurationFlag) GetValue() string { - return f.Value.String() -} - -// GetDefaultText returns the default text for this flag -func (f *DurationFlag) GetDefaultText() string { - if f.DefaultText != "" { - return f.DefaultText - } - if f.defaultValueSet { - return f.defaultValue.String() - } - return f.Value.String() -} - -// GetEnvVars returns the env vars for this flag -func (f *DurationFlag) GetEnvVars() []string { - return f.EnvVars -} - -// Apply populates the flag given the flag set and environment -func (f *DurationFlag) Apply(set *flag.FlagSet) error { - // set default value so that environment wont be able to overwrite it - f.defaultValue = f.Value - f.defaultValueSet = true - - if val, source, found := flagFromEnvOrFile(f.EnvVars, f.FilePath); found { - if val != "" { - valDuration, err := time.ParseDuration(val) - - if err != nil { - return fmt.Errorf("could not parse %q as duration value from %s for flag %s: %s", val, source, f.Name, err) - } - - f.Value = valDuration - f.HasBeenSet = true - } - } - - for _, name := range f.Names() { - if f.Destination != nil { - set.DurationVar(f.Destination, name, f.Value, f.Usage) - continue - } - set.Duration(name, f.Value, f.Usage) - } - return nil -} - -// Get returns the flag’s value in the given Context. -func (f *DurationFlag) Get(ctx *Context) time.Duration { - return ctx.Duration(f.Name) -} - -// RunAction executes flag action if set -func (f *DurationFlag) RunAction(c *Context) error { - if f.Action != nil { - return f.Action(c, c.Duration(f.Name)) - } - - return nil -} - -// Duration looks up the value of a local DurationFlag, returns -// 0 if not found -func (cCtx *Context) Duration(name string) time.Duration { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return lookupDuration(name, fs) - } - return 0 -} - -func lookupDuration(name string, set *flag.FlagSet) time.Duration { - f := set.Lookup(name) - if f != nil { - parsed, err := time.ParseDuration(f.Value.String()) - if err != nil { - return 0 - } - return parsed - } - return 0 -} diff --git a/vendor/github.com/urfave/cli/v2/flag_float64.go b/vendor/github.com/urfave/cli/v2/flag_float64.go deleted file mode 100644 index 6a4de5c8..00000000 --- a/vendor/github.com/urfave/cli/v2/flag_float64.go +++ /dev/null @@ -1,107 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "strconv" -) - -// TakesValue returns true of the flag takes a value, otherwise false -func (f *Float64Flag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f *Float64Flag) GetUsage() string { - return f.Usage -} - -// GetCategory returns the category for the flag -func (f *Float64Flag) GetCategory() string { - return f.Category -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f *Float64Flag) GetValue() string { - return fmt.Sprintf("%v", f.Value) -} - -// GetDefaultText returns the default text for this flag -func (f *Float64Flag) GetDefaultText() string { - if f.DefaultText != "" { - return f.DefaultText - } - if f.defaultValueSet { - return fmt.Sprintf("%v", f.defaultValue) - } - return fmt.Sprintf("%v", f.Value) -} - -// GetEnvVars returns the env vars for this flag -func (f *Float64Flag) GetEnvVars() []string { - return f.EnvVars -} - -// Apply populates the flag given the flag set and environment -func (f *Float64Flag) Apply(set *flag.FlagSet) error { - f.defaultValue = f.Value - f.defaultValueSet = true - - if val, source, found := flagFromEnvOrFile(f.EnvVars, f.FilePath); found { - if val != "" { - valFloat, err := strconv.ParseFloat(val, 64) - if err != nil { - return fmt.Errorf("could not parse %q as float64 value from %s for flag %s: %s", val, source, f.Name, err) - } - - f.Value = valFloat - f.HasBeenSet = true - } - } - - for _, name := range f.Names() { - if f.Destination != nil { - set.Float64Var(f.Destination, name, f.Value, f.Usage) - continue - } - set.Float64(name, f.Value, f.Usage) - } - - return nil -} - -// Get returns the flag’s value in the given Context. -func (f *Float64Flag) Get(ctx *Context) float64 { - return ctx.Float64(f.Name) -} - -// RunAction executes flag action if set -func (f *Float64Flag) RunAction(c *Context) error { - if f.Action != nil { - return f.Action(c, c.Float64(f.Name)) - } - - return nil -} - -// Float64 looks up the value of a local Float64Flag, returns -// 0 if not found -func (cCtx *Context) Float64(name string) float64 { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return lookupFloat64(name, fs) - } - return 0 -} - -func lookupFloat64(name string, set *flag.FlagSet) float64 { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseFloat(f.Value.String(), 64) - if err != nil { - return 0 - } - return parsed - } - return 0 -} diff --git a/vendor/github.com/urfave/cli/v2/flag_float64_slice.go b/vendor/github.com/urfave/cli/v2/flag_float64_slice.go deleted file mode 100644 index 0bc4612c..00000000 --- a/vendor/github.com/urfave/cli/v2/flag_float64_slice.go +++ /dev/null @@ -1,216 +0,0 @@ -package cli - -import ( - "encoding/json" - "flag" - "fmt" - "strconv" - "strings" -) - -// Float64Slice wraps []float64 to satisfy flag.Value -type Float64Slice struct { - slice []float64 - separator separatorSpec - hasBeenSet bool -} - -// NewFloat64Slice makes a *Float64Slice with default values -func NewFloat64Slice(defaults ...float64) *Float64Slice { - return &Float64Slice{slice: append([]float64{}, defaults...)} -} - -// clone allocate a copy of self object -func (f *Float64Slice) clone() *Float64Slice { - n := &Float64Slice{ - slice: make([]float64, len(f.slice)), - hasBeenSet: f.hasBeenSet, - } - copy(n.slice, f.slice) - return n -} - -func (f *Float64Slice) WithSeparatorSpec(spec separatorSpec) { - f.separator = spec -} - -// Set parses the value into a float64 and appends it to the list of values -func (f *Float64Slice) Set(value string) error { - if !f.hasBeenSet { - f.slice = []float64{} - f.hasBeenSet = true - } - - if strings.HasPrefix(value, slPfx) { - // Deserializing assumes overwrite - _ = json.Unmarshal([]byte(strings.Replace(value, slPfx, "", 1)), &f.slice) - f.hasBeenSet = true - return nil - } - - for _, s := range f.separator.flagSplitMultiValues(value) { - tmp, err := strconv.ParseFloat(strings.TrimSpace(s), 64) - if err != nil { - return err - } - - f.slice = append(f.slice, tmp) - } - return nil -} - -// String returns a readable representation of this value (for usage defaults) -func (f *Float64Slice) String() string { - v := f.slice - if v == nil { - // treat nil the same as zero length non-nil - v = make([]float64, 0) - } - return fmt.Sprintf("%#v", v) -} - -// Serialize allows Float64Slice to fulfill Serializer -func (f *Float64Slice) Serialize() string { - jsonBytes, _ := json.Marshal(f.slice) - return fmt.Sprintf("%s%s", slPfx, string(jsonBytes)) -} - -// Value returns the slice of float64s set by this flag -func (f *Float64Slice) Value() []float64 { - return f.slice -} - -// Get returns the slice of float64s set by this flag -func (f *Float64Slice) Get() interface{} { - return *f -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f *Float64SliceFlag) String() string { - return FlagStringer(f) -} - -// TakesValue returns true if the flag takes a value, otherwise false -func (f *Float64SliceFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f *Float64SliceFlag) GetUsage() string { - return f.Usage -} - -// GetCategory returns the category for the flag -func (f *Float64SliceFlag) GetCategory() string { - return f.Category -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f *Float64SliceFlag) GetValue() string { - var defaultVals []string - if f.Value != nil && len(f.Value.Value()) > 0 { - for _, i := range f.Value.Value() { - defaultVals = append(defaultVals, strings.TrimRight(strings.TrimRight(fmt.Sprintf("%f", i), "0"), ".")) - } - } - return strings.Join(defaultVals, ", ") -} - -// GetDefaultText returns the default text for this flag -func (f *Float64SliceFlag) GetDefaultText() string { - if f.DefaultText != "" { - return f.DefaultText - } - return f.GetValue() -} - -// GetEnvVars returns the env vars for this flag -func (f *Float64SliceFlag) GetEnvVars() []string { - return f.EnvVars -} - -// IsSliceFlag implements DocGenerationSliceFlag. -func (f *Float64SliceFlag) IsSliceFlag() bool { - return true -} - -// Apply populates the flag given the flag set and environment -func (f *Float64SliceFlag) Apply(set *flag.FlagSet) error { - // apply any default - if f.Destination != nil && f.Value != nil { - f.Destination.slice = make([]float64, len(f.Value.slice)) - copy(f.Destination.slice, f.Value.slice) - } - - // resolve setValue (what we will assign to the set) - var setValue *Float64Slice - switch { - case f.Destination != nil: - setValue = f.Destination - case f.Value != nil: - setValue = f.Value.clone() - default: - setValue = new(Float64Slice) - setValue.WithSeparatorSpec(f.separator) - } - - if val, source, found := flagFromEnvOrFile(f.EnvVars, f.FilePath); found { - if val != "" { - for _, s := range f.separator.flagSplitMultiValues(val) { - if err := setValue.Set(strings.TrimSpace(s)); err != nil { - return fmt.Errorf("could not parse %q as float64 slice value from %s for flag %s: %s", val, source, f.Name, err) - } - } - - // Set this to false so that we reset the slice if we then set values from - // flags that have already been set by the environment. - setValue.hasBeenSet = false - f.HasBeenSet = true - } - } - - for _, name := range f.Names() { - set.Var(setValue, name, f.Usage) - } - - return nil -} - -func (f *Float64SliceFlag) WithSeparatorSpec(spec separatorSpec) { - f.separator = spec -} - -// Get returns the flag’s value in the given Context. -func (f *Float64SliceFlag) Get(ctx *Context) []float64 { - return ctx.Float64Slice(f.Name) -} - -// RunAction executes flag action if set -func (f *Float64SliceFlag) RunAction(c *Context) error { - if f.Action != nil { - return f.Action(c, c.Float64Slice(f.Name)) - } - - return nil -} - -// Float64Slice looks up the value of a local Float64SliceFlag, returns -// nil if not found -func (cCtx *Context) Float64Slice(name string) []float64 { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return lookupFloat64Slice(name, fs) - } - return nil -} - -func lookupFloat64Slice(name string, set *flag.FlagSet) []float64 { - f := set.Lookup(name) - if f != nil { - if slice, ok := unwrapFlagValue(f.Value).(*Float64Slice); ok { - return slice.Value() - } - } - return nil -} diff --git a/vendor/github.com/urfave/cli/v2/flag_generic.go b/vendor/github.com/urfave/cli/v2/flag_generic.go deleted file mode 100644 index 7528c934..00000000 --- a/vendor/github.com/urfave/cli/v2/flag_generic.go +++ /dev/null @@ -1,131 +0,0 @@ -package cli - -import ( - "flag" - "fmt" -) - -// Generic is a generic parseable type identified by a specific flag -type Generic interface { - Set(value string) error - String() string -} - -type stringGeneric struct { - value string -} - -func (s *stringGeneric) Set(value string) error { - s.value = value - return nil -} - -func (s *stringGeneric) String() string { - return s.value -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f *GenericFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f *GenericFlag) GetUsage() string { - return f.Usage -} - -// GetCategory returns the category for the flag -func (f *GenericFlag) GetCategory() string { - return f.Category -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f *GenericFlag) GetValue() string { - if f.Value != nil { - return f.Value.String() - } - return "" -} - -// GetDefaultText returns the default text for this flag -func (f *GenericFlag) GetDefaultText() string { - if f.DefaultText != "" { - return f.DefaultText - } - val := f.Value - if f.defaultValueSet { - val = f.defaultValue - } - - if val != nil { - return val.String() - } - - return "" -} - -// GetEnvVars returns the env vars for this flag -func (f *GenericFlag) GetEnvVars() []string { - return f.EnvVars -} - -// Apply takes the flagset and calls Set on the generic flag with the value -// provided by the user for parsing by the flag -func (f *GenericFlag) Apply(set *flag.FlagSet) error { - // set default value so that environment wont be able to overwrite it - if f.Value != nil { - f.defaultValue = &stringGeneric{value: f.Value.String()} - f.defaultValueSet = true - } - - if val, source, found := flagFromEnvOrFile(f.EnvVars, f.FilePath); found { - if val != "" { - if err := f.Value.Set(val); err != nil { - return fmt.Errorf("could not parse %q from %s as value for flag %s: %s", val, source, f.Name, err) - } - - f.HasBeenSet = true - } - } - - for _, name := range f.Names() { - if f.Destination != nil { - set.Var(f.Destination, name, f.Usage) - continue - } - set.Var(f.Value, name, f.Usage) - } - - return nil -} - -// Get returns the flag’s value in the given Context. -func (f *GenericFlag) Get(ctx *Context) interface{} { - return ctx.Generic(f.Name) -} - -// RunAction executes flag action if set -func (f *GenericFlag) RunAction(c *Context) error { - if f.Action != nil { - return f.Action(c, c.Generic(f.Name)) - } - - return nil -} - -// Generic looks up the value of a local GenericFlag, returns -// nil if not found -func (cCtx *Context) Generic(name string) interface{} { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return lookupGeneric(name, fs) - } - return nil -} - -func lookupGeneric(name string, set *flag.FlagSet) interface{} { - if f := set.Lookup(name); f != nil { - return f.Value - } - return nil -} diff --git a/vendor/github.com/urfave/cli/v2/flag_int.go b/vendor/github.com/urfave/cli/v2/flag_int.go deleted file mode 100644 index 750e7ebf..00000000 --- a/vendor/github.com/urfave/cli/v2/flag_int.go +++ /dev/null @@ -1,109 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "strconv" -) - -// TakesValue returns true of the flag takes a value, otherwise false -func (f *IntFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f *IntFlag) GetUsage() string { - return f.Usage -} - -// GetCategory returns the category for the flag -func (f *IntFlag) GetCategory() string { - return f.Category -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f *IntFlag) GetValue() string { - return fmt.Sprintf("%d", f.Value) -} - -// GetDefaultText returns the default text for this flag -func (f *IntFlag) GetDefaultText() string { - if f.DefaultText != "" { - return f.DefaultText - } - if f.defaultValueSet { - return fmt.Sprintf("%d", f.defaultValue) - } - return fmt.Sprintf("%d", f.Value) -} - -// GetEnvVars returns the env vars for this flag -func (f *IntFlag) GetEnvVars() []string { - return f.EnvVars -} - -// Apply populates the flag given the flag set and environment -func (f *IntFlag) Apply(set *flag.FlagSet) error { - // set default value so that environment wont be able to overwrite it - f.defaultValue = f.Value - f.defaultValueSet = true - - if val, source, found := flagFromEnvOrFile(f.EnvVars, f.FilePath); found { - if val != "" { - valInt, err := strconv.ParseInt(val, f.Base, 64) - - if err != nil { - return fmt.Errorf("could not parse %q as int value from %s for flag %s: %s", val, source, f.Name, err) - } - - f.Value = int(valInt) - f.HasBeenSet = true - } - } - - for _, name := range f.Names() { - if f.Destination != nil { - set.IntVar(f.Destination, name, f.Value, f.Usage) - continue - } - set.Int(name, f.Value, f.Usage) - } - - return nil -} - -// Get returns the flag’s value in the given Context. -func (f *IntFlag) Get(ctx *Context) int { - return ctx.Int(f.Name) -} - -// RunAction executes flag action if set -func (f *IntFlag) RunAction(c *Context) error { - if f.Action != nil { - return f.Action(c, c.Int(f.Name)) - } - - return nil -} - -// Int looks up the value of a local IntFlag, returns -// 0 if not found -func (cCtx *Context) Int(name string) int { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return lookupInt(name, fs) - } - return 0 -} - -func lookupInt(name string, set *flag.FlagSet) int { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseInt(f.Value.String(), 0, 64) - if err != nil { - return 0 - } - return int(parsed) - } - return 0 -} diff --git a/vendor/github.com/urfave/cli/v2/flag_int64.go b/vendor/github.com/urfave/cli/v2/flag_int64.go deleted file mode 100644 index 688c2671..00000000 --- a/vendor/github.com/urfave/cli/v2/flag_int64.go +++ /dev/null @@ -1,108 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "strconv" -) - -// TakesValue returns true of the flag takes a value, otherwise false -func (f *Int64Flag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f *Int64Flag) GetUsage() string { - return f.Usage -} - -// GetCategory returns the category for the flag -func (f *Int64Flag) GetCategory() string { - return f.Category -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f *Int64Flag) GetValue() string { - return fmt.Sprintf("%d", f.Value) -} - -// GetDefaultText returns the default text for this flag -func (f *Int64Flag) GetDefaultText() string { - if f.DefaultText != "" { - return f.DefaultText - } - if f.defaultValueSet { - return fmt.Sprintf("%d", f.defaultValue) - } - return fmt.Sprintf("%d", f.Value) -} - -// GetEnvVars returns the env vars for this flag -func (f *Int64Flag) GetEnvVars() []string { - return f.EnvVars -} - -// Apply populates the flag given the flag set and environment -func (f *Int64Flag) Apply(set *flag.FlagSet) error { - // set default value so that environment wont be able to overwrite it - f.defaultValue = f.Value - f.defaultValueSet = true - - if val, source, found := flagFromEnvOrFile(f.EnvVars, f.FilePath); found { - if val != "" { - valInt, err := strconv.ParseInt(val, f.Base, 64) - - if err != nil { - return fmt.Errorf("could not parse %q as int value from %s for flag %s: %s", val, source, f.Name, err) - } - - f.Value = valInt - f.HasBeenSet = true - } - } - - for _, name := range f.Names() { - if f.Destination != nil { - set.Int64Var(f.Destination, name, f.Value, f.Usage) - continue - } - set.Int64(name, f.Value, f.Usage) - } - return nil -} - -// Get returns the flag’s value in the given Context. -func (f *Int64Flag) Get(ctx *Context) int64 { - return ctx.Int64(f.Name) -} - -// RunAction executes flag action if set -func (f *Int64Flag) RunAction(c *Context) error { - if f.Action != nil { - return f.Action(c, c.Int64(f.Name)) - } - - return nil -} - -// Int64 looks up the value of a local Int64Flag, returns -// 0 if not found -func (cCtx *Context) Int64(name string) int64 { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return lookupInt64(name, fs) - } - return 0 -} - -func lookupInt64(name string, set *flag.FlagSet) int64 { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseInt(f.Value.String(), 0, 64) - if err != nil { - return 0 - } - return parsed - } - return 0 -} diff --git a/vendor/github.com/urfave/cli/v2/flag_int64_slice.go b/vendor/github.com/urfave/cli/v2/flag_int64_slice.go deleted file mode 100644 index d45c2dd4..00000000 --- a/vendor/github.com/urfave/cli/v2/flag_int64_slice.go +++ /dev/null @@ -1,215 +0,0 @@ -package cli - -import ( - "encoding/json" - "flag" - "fmt" - "strconv" - "strings" -) - -// Int64Slice wraps []int64 to satisfy flag.Value -type Int64Slice struct { - slice []int64 - separator separatorSpec - hasBeenSet bool -} - -// NewInt64Slice makes an *Int64Slice with default values -func NewInt64Slice(defaults ...int64) *Int64Slice { - return &Int64Slice{slice: append([]int64{}, defaults...)} -} - -// clone allocate a copy of self object -func (i *Int64Slice) clone() *Int64Slice { - n := &Int64Slice{ - slice: make([]int64, len(i.slice)), - hasBeenSet: i.hasBeenSet, - } - copy(n.slice, i.slice) - return n -} - -func (i *Int64Slice) WithSeparatorSpec(spec separatorSpec) { - i.separator = spec -} - -// Set parses the value into an integer and appends it to the list of values -func (i *Int64Slice) Set(value string) error { - if !i.hasBeenSet { - i.slice = []int64{} - i.hasBeenSet = true - } - - if strings.HasPrefix(value, slPfx) { - // Deserializing assumes overwrite - _ = json.Unmarshal([]byte(strings.Replace(value, slPfx, "", 1)), &i.slice) - i.hasBeenSet = true - return nil - } - - for _, s := range i.separator.flagSplitMultiValues(value) { - tmp, err := strconv.ParseInt(strings.TrimSpace(s), 0, 64) - if err != nil { - return err - } - - i.slice = append(i.slice, tmp) - } - - return nil -} - -// String returns a readable representation of this value (for usage defaults) -func (i *Int64Slice) String() string { - v := i.slice - if v == nil { - // treat nil the same as zero length non-nil - v = make([]int64, 0) - } - return fmt.Sprintf("%#v", v) -} - -// Serialize allows Int64Slice to fulfill Serializer -func (i *Int64Slice) Serialize() string { - jsonBytes, _ := json.Marshal(i.slice) - return fmt.Sprintf("%s%s", slPfx, string(jsonBytes)) -} - -// Value returns the slice of ints set by this flag -func (i *Int64Slice) Value() []int64 { - return i.slice -} - -// Get returns the slice of ints set by this flag -func (i *Int64Slice) Get() interface{} { - return *i -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f *Int64SliceFlag) String() string { - return FlagStringer(f) -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f *Int64SliceFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f *Int64SliceFlag) GetUsage() string { - return f.Usage -} - -// GetCategory returns the category for the flag -func (f *Int64SliceFlag) GetCategory() string { - return f.Category -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f *Int64SliceFlag) GetValue() string { - var defaultVals []string - if f.Value != nil && len(f.Value.Value()) > 0 { - for _, i := range f.Value.Value() { - defaultVals = append(defaultVals, strconv.FormatInt(i, 10)) - } - } - return strings.Join(defaultVals, ", ") -} - -// GetDefaultText returns the default text for this flag -func (f *Int64SliceFlag) GetDefaultText() string { - if f.DefaultText != "" { - return f.DefaultText - } - return f.GetValue() -} - -// GetEnvVars returns the env vars for this flag -func (f *Int64SliceFlag) GetEnvVars() []string { - return f.EnvVars -} - -// IsSliceFlag implements DocGenerationSliceFlag. -func (f *Int64SliceFlag) IsSliceFlag() bool { - return true -} - -// Apply populates the flag given the flag set and environment -func (f *Int64SliceFlag) Apply(set *flag.FlagSet) error { - // apply any default - if f.Destination != nil && f.Value != nil { - f.Destination.slice = make([]int64, len(f.Value.slice)) - copy(f.Destination.slice, f.Value.slice) - } - - // resolve setValue (what we will assign to the set) - var setValue *Int64Slice - switch { - case f.Destination != nil: - setValue = f.Destination - case f.Value != nil: - setValue = f.Value.clone() - default: - setValue = new(Int64Slice) - setValue.WithSeparatorSpec(f.separator) - } - - if val, source, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok && val != "" { - for _, s := range f.separator.flagSplitMultiValues(val) { - if err := setValue.Set(strings.TrimSpace(s)); err != nil { - return fmt.Errorf("could not parse %q as int64 slice value from %s for flag %s: %s", val, source, f.Name, err) - } - } - - // Set this to false so that we reset the slice if we then set values from - // flags that have already been set by the environment. - setValue.hasBeenSet = false - f.HasBeenSet = true - } - - for _, name := range f.Names() { - set.Var(setValue, name, f.Usage) - } - - return nil -} - -func (f *Int64SliceFlag) WithSeparatorSpec(spec separatorSpec) { - f.separator = spec -} - -// Get returns the flag’s value in the given Context. -func (f *Int64SliceFlag) Get(ctx *Context) []int64 { - return ctx.Int64Slice(f.Name) -} - -// RunAction executes flag action if set -func (f *Int64SliceFlag) RunAction(c *Context) error { - if f.Action != nil { - return f.Action(c, c.Int64Slice(f.Name)) - } - - return nil -} - -// Int64Slice looks up the value of a local Int64SliceFlag, returns -// nil if not found -func (cCtx *Context) Int64Slice(name string) []int64 { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return lookupInt64Slice(name, fs) - } - return nil -} - -func lookupInt64Slice(name string, set *flag.FlagSet) []int64 { - f := set.Lookup(name) - if f != nil { - if slice, ok := unwrapFlagValue(f.Value).(*Int64Slice); ok { - return slice.Value() - } - } - return nil -} diff --git a/vendor/github.com/urfave/cli/v2/flag_int_slice.go b/vendor/github.com/urfave/cli/v2/flag_int_slice.go deleted file mode 100644 index da9c09bc..00000000 --- a/vendor/github.com/urfave/cli/v2/flag_int_slice.go +++ /dev/null @@ -1,226 +0,0 @@ -package cli - -import ( - "encoding/json" - "flag" - "fmt" - "strconv" - "strings" -) - -// IntSlice wraps []int to satisfy flag.Value -type IntSlice struct { - slice []int - separator separatorSpec - hasBeenSet bool -} - -// NewIntSlice makes an *IntSlice with default values -func NewIntSlice(defaults ...int) *IntSlice { - return &IntSlice{slice: append([]int{}, defaults...)} -} - -// clone allocate a copy of self object -func (i *IntSlice) clone() *IntSlice { - n := &IntSlice{ - slice: make([]int, len(i.slice)), - hasBeenSet: i.hasBeenSet, - } - copy(n.slice, i.slice) - return n -} - -// TODO: Consistently have specific Set function for Int64 and Float64 ? -// SetInt directly adds an integer to the list of values -func (i *IntSlice) SetInt(value int) { - if !i.hasBeenSet { - i.slice = []int{} - i.hasBeenSet = true - } - - i.slice = append(i.slice, value) -} - -func (i *IntSlice) WithSeparatorSpec(spec separatorSpec) { - i.separator = spec -} - -// Set parses the value into an integer and appends it to the list of values -func (i *IntSlice) Set(value string) error { - if !i.hasBeenSet { - i.slice = []int{} - i.hasBeenSet = true - } - - if strings.HasPrefix(value, slPfx) { - // Deserializing assumes overwrite - _ = json.Unmarshal([]byte(strings.Replace(value, slPfx, "", 1)), &i.slice) - i.hasBeenSet = true - return nil - } - - for _, s := range i.separator.flagSplitMultiValues(value) { - tmp, err := strconv.ParseInt(strings.TrimSpace(s), 0, 64) - if err != nil { - return err - } - - i.slice = append(i.slice, int(tmp)) - } - - return nil -} - -// String returns a readable representation of this value (for usage defaults) -func (i *IntSlice) String() string { - v := i.slice - if v == nil { - // treat nil the same as zero length non-nil - v = make([]int, 0) - } - return fmt.Sprintf("%#v", v) -} - -// Serialize allows IntSlice to fulfill Serializer -func (i *IntSlice) Serialize() string { - jsonBytes, _ := json.Marshal(i.slice) - return fmt.Sprintf("%s%s", slPfx, string(jsonBytes)) -} - -// Value returns the slice of ints set by this flag -func (i *IntSlice) Value() []int { - return i.slice -} - -// Get returns the slice of ints set by this flag -func (i *IntSlice) Get() interface{} { - return *i -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f *IntSliceFlag) String() string { - return FlagStringer(f) -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f *IntSliceFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f *IntSliceFlag) GetUsage() string { - return f.Usage -} - -// GetCategory returns the category for the flag -func (f *IntSliceFlag) GetCategory() string { - return f.Category -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f *IntSliceFlag) GetValue() string { - var defaultVals []string - if f.Value != nil && len(f.Value.Value()) > 0 { - for _, i := range f.Value.Value() { - defaultVals = append(defaultVals, strconv.Itoa(i)) - } - } - return strings.Join(defaultVals, ", ") -} - -// GetDefaultText returns the default text for this flag -func (f *IntSliceFlag) GetDefaultText() string { - if f.DefaultText != "" { - return f.DefaultText - } - return f.GetValue() -} - -// GetEnvVars returns the env vars for this flag -func (f *IntSliceFlag) GetEnvVars() []string { - return f.EnvVars -} - -// IsSliceFlag implements DocGenerationSliceFlag. -func (f *IntSliceFlag) IsSliceFlag() bool { - return true -} - -// Apply populates the flag given the flag set and environment -func (f *IntSliceFlag) Apply(set *flag.FlagSet) error { - // apply any default - if f.Destination != nil && f.Value != nil { - f.Destination.slice = make([]int, len(f.Value.slice)) - copy(f.Destination.slice, f.Value.slice) - } - - // resolve setValue (what we will assign to the set) - var setValue *IntSlice - switch { - case f.Destination != nil: - setValue = f.Destination - case f.Value != nil: - setValue = f.Value.clone() - default: - setValue = new(IntSlice) - setValue.WithSeparatorSpec(f.separator) - } - - if val, source, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok && val != "" { - for _, s := range f.separator.flagSplitMultiValues(val) { - if err := setValue.Set(strings.TrimSpace(s)); err != nil { - return fmt.Errorf("could not parse %q as int slice value from %s for flag %s: %s", val, source, f.Name, err) - } - } - - // Set this to false so that we reset the slice if we then set values from - // flags that have already been set by the environment. - setValue.hasBeenSet = false - f.HasBeenSet = true - } - - for _, name := range f.Names() { - set.Var(setValue, name, f.Usage) - } - - return nil -} - -func (f *IntSliceFlag) WithSeparatorSpec(spec separatorSpec) { - f.separator = spec -} - -// Get returns the flag’s value in the given Context. -func (f *IntSliceFlag) Get(ctx *Context) []int { - return ctx.IntSlice(f.Name) -} - -// RunAction executes flag action if set -func (f *IntSliceFlag) RunAction(c *Context) error { - if f.Action != nil { - return f.Action(c, c.IntSlice(f.Name)) - } - - return nil -} - -// IntSlice looks up the value of a local IntSliceFlag, returns -// nil if not found -func (cCtx *Context) IntSlice(name string) []int { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return lookupIntSlice(name, fs) - } - return nil -} - -func lookupIntSlice(name string, set *flag.FlagSet) []int { - f := set.Lookup(name) - if f != nil { - if slice, ok := unwrapFlagValue(f.Value).(*IntSlice); ok { - return slice.Value() - } - } - return nil -} diff --git a/vendor/github.com/urfave/cli/v2/flag_path.go b/vendor/github.com/urfave/cli/v2/flag_path.go deleted file mode 100644 index 76cb3524..00000000 --- a/vendor/github.com/urfave/cli/v2/flag_path.go +++ /dev/null @@ -1,102 +0,0 @@ -package cli - -import ( - "flag" - "fmt" -) - -type Path = string - -// TakesValue returns true of the flag takes a value, otherwise false -func (f *PathFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f *PathFlag) GetUsage() string { - return f.Usage -} - -// GetCategory returns the category for the flag -func (f *PathFlag) GetCategory() string { - return f.Category -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f *PathFlag) GetValue() string { - return f.Value -} - -// GetDefaultText returns the default text for this flag -func (f *PathFlag) GetDefaultText() string { - if f.DefaultText != "" { - return f.DefaultText - } - val := f.Value - if f.defaultValueSet { - val = f.defaultValue - } - if val == "" { - return val - } - return fmt.Sprintf("%q", val) -} - -// GetEnvVars returns the env vars for this flag -func (f *PathFlag) GetEnvVars() []string { - return f.EnvVars -} - -// Apply populates the flag given the flag set and environment -func (f *PathFlag) Apply(set *flag.FlagSet) error { - // set default value so that environment wont be able to overwrite it - f.defaultValue = f.Value - f.defaultValueSet = true - - if val, _, found := flagFromEnvOrFile(f.EnvVars, f.FilePath); found { - f.Value = val - f.HasBeenSet = true - } - - for _, name := range f.Names() { - if f.Destination != nil { - set.StringVar(f.Destination, name, f.Value, f.Usage) - continue - } - set.String(name, f.Value, f.Usage) - } - - return nil -} - -// Get returns the flag’s value in the given Context. -func (f *PathFlag) Get(ctx *Context) string { - return ctx.Path(f.Name) -} - -// RunAction executes flag action if set -func (f *PathFlag) RunAction(c *Context) error { - if f.Action != nil { - return f.Action(c, c.Path(f.Name)) - } - - return nil -} - -// Path looks up the value of a local PathFlag, returns -// "" if not found -func (cCtx *Context) Path(name string) string { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return lookupPath(name, fs) - } - - return "" -} - -func lookupPath(name string, set *flag.FlagSet) string { - if f := set.Lookup(name); f != nil { - return f.Value.String() - } - return "" -} diff --git a/vendor/github.com/urfave/cli/v2/flag_string.go b/vendor/github.com/urfave/cli/v2/flag_string.go deleted file mode 100644 index 0f73e062..00000000 --- a/vendor/github.com/urfave/cli/v2/flag_string.go +++ /dev/null @@ -1,100 +0,0 @@ -package cli - -import ( - "flag" - "fmt" -) - -// TakesValue returns true of the flag takes a value, otherwise false -func (f *StringFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f *StringFlag) GetUsage() string { - return f.Usage -} - -// GetCategory returns the category for the flag -func (f *StringFlag) GetCategory() string { - return f.Category -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f *StringFlag) GetValue() string { - return f.Value -} - -// GetDefaultText returns the default text for this flag -func (f *StringFlag) GetDefaultText() string { - if f.DefaultText != "" { - return f.DefaultText - } - val := f.Value - if f.defaultValueSet { - val = f.defaultValue - } - - if val == "" { - return val - } - return fmt.Sprintf("%q", val) -} - -// GetEnvVars returns the env vars for this flag -func (f *StringFlag) GetEnvVars() []string { - return f.EnvVars -} - -// Apply populates the flag given the flag set and environment -func (f *StringFlag) Apply(set *flag.FlagSet) error { - // set default value so that environment wont be able to overwrite it - f.defaultValue = f.Value - f.defaultValueSet = true - - if val, _, found := flagFromEnvOrFile(f.EnvVars, f.FilePath); found { - f.Value = val - f.HasBeenSet = true - } - - for _, name := range f.Names() { - if f.Destination != nil { - set.StringVar(f.Destination, name, f.Value, f.Usage) - continue - } - set.String(name, f.Value, f.Usage) - } - - return nil -} - -// Get returns the flag’s value in the given Context. -func (f *StringFlag) Get(ctx *Context) string { - return ctx.String(f.Name) -} - -// RunAction executes flag action if set -func (f *StringFlag) RunAction(c *Context) error { - if f.Action != nil { - return f.Action(c, c.String(f.Name)) - } - - return nil -} - -// String looks up the value of a local StringFlag, returns -// "" if not found -func (cCtx *Context) String(name string) string { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return lookupString(name, fs) - } - return "" -} - -func lookupString(name string, set *flag.FlagSet) string { - if f := set.Lookup(name); f != nil { - return f.Value.String() - } - return "" -} diff --git a/vendor/github.com/urfave/cli/v2/flag_string_slice.go b/vendor/github.com/urfave/cli/v2/flag_string_slice.go deleted file mode 100644 index 28f4798f..00000000 --- a/vendor/github.com/urfave/cli/v2/flag_string_slice.go +++ /dev/null @@ -1,216 +0,0 @@ -package cli - -import ( - "encoding/json" - "flag" - "fmt" - "strconv" - "strings" -) - -// StringSlice wraps a []string to satisfy flag.Value -type StringSlice struct { - slice []string - separator separatorSpec - hasBeenSet bool - keepSpace bool -} - -// NewStringSlice creates a *StringSlice with default values -func NewStringSlice(defaults ...string) *StringSlice { - return &StringSlice{slice: append([]string{}, defaults...)} -} - -// clone allocate a copy of self object -func (s *StringSlice) clone() *StringSlice { - n := &StringSlice{ - slice: make([]string, len(s.slice)), - hasBeenSet: s.hasBeenSet, - } - copy(n.slice, s.slice) - return n -} - -// Set appends the string value to the list of values -func (s *StringSlice) Set(value string) error { - if !s.hasBeenSet { - s.slice = []string{} - s.hasBeenSet = true - } - - if strings.HasPrefix(value, slPfx) { - // Deserializing assumes overwrite - _ = json.Unmarshal([]byte(strings.Replace(value, slPfx, "", 1)), &s.slice) - s.hasBeenSet = true - return nil - } - - for _, t := range s.separator.flagSplitMultiValues(value) { - if !s.keepSpace { - t = strings.TrimSpace(t) - } - s.slice = append(s.slice, t) - } - - return nil -} - -func (s *StringSlice) WithSeparatorSpec(spec separatorSpec) { - s.separator = spec -} - -// String returns a readable representation of this value (for usage defaults) -func (s *StringSlice) String() string { - return fmt.Sprintf("%s", s.slice) -} - -// Serialize allows StringSlice to fulfill Serializer -func (s *StringSlice) Serialize() string { - jsonBytes, _ := json.Marshal(s.slice) - return fmt.Sprintf("%s%s", slPfx, string(jsonBytes)) -} - -// Value returns the slice of strings set by this flag -func (s *StringSlice) Value() []string { - return s.slice -} - -// Get returns the slice of strings set by this flag -func (s *StringSlice) Get() interface{} { - return *s -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f *StringSliceFlag) String() string { - return FlagStringer(f) -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f *StringSliceFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f *StringSliceFlag) GetUsage() string { - return f.Usage -} - -// GetCategory returns the category for the flag -func (f *StringSliceFlag) GetCategory() string { - return f.Category -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f *StringSliceFlag) GetValue() string { - var defaultVals []string - if f.Value != nil && len(f.Value.Value()) > 0 { - for _, s := range f.Value.Value() { - if len(s) > 0 { - defaultVals = append(defaultVals, strconv.Quote(s)) - } - } - } - return strings.Join(defaultVals, ", ") -} - -// GetDefaultText returns the default text for this flag -func (f *StringSliceFlag) GetDefaultText() string { - if f.DefaultText != "" { - return f.DefaultText - } - return f.GetValue() -} - -// GetEnvVars returns the env vars for this flag -func (f *StringSliceFlag) GetEnvVars() []string { - return f.EnvVars -} - -// IsSliceFlag implements DocGenerationSliceFlag. -func (f *StringSliceFlag) IsSliceFlag() bool { - return true -} - -// Apply populates the flag given the flag set and environment -func (f *StringSliceFlag) Apply(set *flag.FlagSet) error { - // apply any default - if f.Destination != nil && f.Value != nil { - f.Destination.slice = make([]string, len(f.Value.slice)) - copy(f.Destination.slice, f.Value.slice) - } - - // resolve setValue (what we will assign to the set) - var setValue *StringSlice - switch { - case f.Destination != nil: - setValue = f.Destination - case f.Value != nil: - setValue = f.Value.clone() - default: - setValue = new(StringSlice) - setValue.WithSeparatorSpec(f.separator) - } - - setValue.keepSpace = f.KeepSpace - - if val, source, found := flagFromEnvOrFile(f.EnvVars, f.FilePath); found { - for _, s := range f.separator.flagSplitMultiValues(val) { - if !f.KeepSpace { - s = strings.TrimSpace(s) - } - if err := setValue.Set(s); err != nil { - return fmt.Errorf("could not parse %q as string value from %s for flag %s: %s", val, source, f.Name, err) - } - } - - // Set this to false so that we reset the slice if we then set values from - // flags that have already been set by the environment. - setValue.hasBeenSet = false - f.HasBeenSet = true - } - - for _, name := range f.Names() { - set.Var(setValue, name, f.Usage) - } - - return nil -} - -func (f *StringSliceFlag) WithSeparatorSpec(spec separatorSpec) { - f.separator = spec -} - -// Get returns the flag’s value in the given Context. -func (f *StringSliceFlag) Get(ctx *Context) []string { - return ctx.StringSlice(f.Name) -} - -// RunAction executes flag action if set -func (f *StringSliceFlag) RunAction(c *Context) error { - if f.Action != nil { - return f.Action(c, c.StringSlice(f.Name)) - } - - return nil -} - -// StringSlice looks up the value of a local StringSliceFlag, returns -// nil if not found -func (cCtx *Context) StringSlice(name string) []string { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return lookupStringSlice(name, fs) - } - return nil -} - -func lookupStringSlice(name string, set *flag.FlagSet) []string { - f := set.Lookup(name) - if f != nil { - if slice, ok := unwrapFlagValue(f.Value).(*StringSlice); ok { - return slice.Value() - } - } - return nil -} diff --git a/vendor/github.com/urfave/cli/v2/flag_timestamp.go b/vendor/github.com/urfave/cli/v2/flag_timestamp.go deleted file mode 100644 index b9012308..00000000 --- a/vendor/github.com/urfave/cli/v2/flag_timestamp.go +++ /dev/null @@ -1,205 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "time" -) - -// Timestamp wrap to satisfy golang's flag interface. -type Timestamp struct { - timestamp *time.Time - hasBeenSet bool - layout string - location *time.Location -} - -// Timestamp constructor -func NewTimestamp(timestamp time.Time) *Timestamp { - return &Timestamp{timestamp: ×tamp} -} - -// Set the timestamp value directly -func (t *Timestamp) SetTimestamp(value time.Time) { - if !t.hasBeenSet { - t.timestamp = &value - t.hasBeenSet = true - } -} - -// Set the timestamp string layout for future parsing -func (t *Timestamp) SetLayout(layout string) { - t.layout = layout -} - -// Set perceived timezone of the to-be parsed time string -func (t *Timestamp) SetLocation(loc *time.Location) { - t.location = loc -} - -// Parses the string value to timestamp -func (t *Timestamp) Set(value string) error { - var timestamp time.Time - var err error - - if t.location != nil { - timestamp, err = time.ParseInLocation(t.layout, value, t.location) - } else { - timestamp, err = time.Parse(t.layout, value) - } - - if err != nil { - return err - } - - t.timestamp = ×tamp - t.hasBeenSet = true - return nil -} - -// String returns a readable representation of this value (for usage defaults) -func (t *Timestamp) String() string { - return fmt.Sprintf("%#v", t.timestamp) -} - -// Value returns the timestamp value stored in the flag -func (t *Timestamp) Value() *time.Time { - return t.timestamp -} - -// Get returns the flag structure -func (t *Timestamp) Get() interface{} { - return *t -} - -// clone timestamp -func (t *Timestamp) clone() *Timestamp { - tc := &Timestamp{ - timestamp: nil, - hasBeenSet: t.hasBeenSet, - layout: t.layout, - location: nil, - } - if t.timestamp != nil { - tts := *t.timestamp - tc.timestamp = &tts - } - if t.location != nil { - loc := *t.location - tc.location = &loc - } - return tc -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f *TimestampFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f *TimestampFlag) GetUsage() string { - return f.Usage -} - -// GetCategory returns the category for the flag -func (f *TimestampFlag) GetCategory() string { - return f.Category -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f *TimestampFlag) GetValue() string { - if f.Value != nil && f.Value.timestamp != nil { - return f.Value.timestamp.String() - } - return "" -} - -// GetDefaultText returns the default text for this flag -func (f *TimestampFlag) GetDefaultText() string { - if f.DefaultText != "" { - return f.DefaultText - } - val := f.Value - if f.defaultValueSet { - val = f.defaultValue - } - - if val != nil && val.timestamp != nil { - return val.timestamp.String() - } - - return "" -} - -// GetEnvVars returns the env vars for this flag -func (f *TimestampFlag) GetEnvVars() []string { - return f.EnvVars -} - -// Apply populates the flag given the flag set and environment -func (f *TimestampFlag) Apply(set *flag.FlagSet) error { - if f.Layout == "" { - return fmt.Errorf("timestamp Layout is required") - } - if f.Value == nil { - f.Value = &Timestamp{} - } - f.Value.SetLayout(f.Layout) - f.Value.SetLocation(f.Timezone) - - f.defaultValue = f.Value.clone() - f.defaultValueSet = true - - if val, source, found := flagFromEnvOrFile(f.EnvVars, f.FilePath); found { - if err := f.Value.Set(val); err != nil { - return fmt.Errorf("could not parse %q as timestamp value from %s for flag %s: %s", val, source, f.Name, err) - } - f.HasBeenSet = true - } - - if f.Destination != nil { - *f.Destination = *f.Value - } - - for _, name := range f.Names() { - if f.Destination != nil { - set.Var(f.Destination, name, f.Usage) - continue - } - - set.Var(f.Value, name, f.Usage) - } - return nil -} - -// Get returns the flag’s value in the given Context. -func (f *TimestampFlag) Get(ctx *Context) *time.Time { - return ctx.Timestamp(f.Name) -} - -// RunAction executes flag action if set -func (f *TimestampFlag) RunAction(c *Context) error { - if f.Action != nil { - return f.Action(c, c.Timestamp(f.Name)) - } - - return nil -} - -// Timestamp gets the timestamp from a flag name -func (cCtx *Context) Timestamp(name string) *time.Time { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return lookupTimestamp(name, fs) - } - return nil -} - -// Fetches the timestamp value from the local timestampWrap -func lookupTimestamp(name string, set *flag.FlagSet) *time.Time { - f := set.Lookup(name) - if f != nil { - return (f.Value.(*Timestamp)).Value() - } - return nil -} diff --git a/vendor/github.com/urfave/cli/v2/flag_uint.go b/vendor/github.com/urfave/cli/v2/flag_uint.go deleted file mode 100644 index 8d5b8545..00000000 --- a/vendor/github.com/urfave/cli/v2/flag_uint.go +++ /dev/null @@ -1,108 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "strconv" -) - -// TakesValue returns true of the flag takes a value, otherwise false -func (f *UintFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f *UintFlag) GetUsage() string { - return f.Usage -} - -// GetCategory returns the category for the flag -func (f *UintFlag) GetCategory() string { - return f.Category -} - -// Apply populates the flag given the flag set and environment -func (f *UintFlag) Apply(set *flag.FlagSet) error { - // set default value so that environment wont be able to overwrite it - f.defaultValue = f.Value - f.defaultValueSet = true - - if val, source, found := flagFromEnvOrFile(f.EnvVars, f.FilePath); found { - if val != "" { - valInt, err := strconv.ParseUint(val, f.Base, 64) - if err != nil { - return fmt.Errorf("could not parse %q as uint value from %s for flag %s: %s", val, source, f.Name, err) - } - - f.Value = uint(valInt) - f.HasBeenSet = true - } - } - - for _, name := range f.Names() { - if f.Destination != nil { - set.UintVar(f.Destination, name, f.Value, f.Usage) - continue - } - set.Uint(name, f.Value, f.Usage) - } - - return nil -} - -// RunAction executes flag action if set -func (f *UintFlag) RunAction(c *Context) error { - if f.Action != nil { - return f.Action(c, c.Uint(f.Name)) - } - - return nil -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f *UintFlag) GetValue() string { - return fmt.Sprintf("%d", f.Value) -} - -// GetDefaultText returns the default text for this flag -func (f *UintFlag) GetDefaultText() string { - if f.DefaultText != "" { - return f.DefaultText - } - if f.defaultValueSet { - return fmt.Sprintf("%d", f.defaultValue) - } - return fmt.Sprintf("%d", f.Value) -} - -// GetEnvVars returns the env vars for this flag -func (f *UintFlag) GetEnvVars() []string { - return f.EnvVars -} - -// Get returns the flag’s value in the given Context. -func (f *UintFlag) Get(ctx *Context) uint { - return ctx.Uint(f.Name) -} - -// Uint looks up the value of a local UintFlag, returns -// 0 if not found -func (cCtx *Context) Uint(name string) uint { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return lookupUint(name, fs) - } - return 0 -} - -func lookupUint(name string, set *flag.FlagSet) uint { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseUint(f.Value.String(), 0, 64) - if err != nil { - return 0 - } - return uint(parsed) - } - return 0 -} diff --git a/vendor/github.com/urfave/cli/v2/flag_uint64.go b/vendor/github.com/urfave/cli/v2/flag_uint64.go deleted file mode 100644 index c356e533..00000000 --- a/vendor/github.com/urfave/cli/v2/flag_uint64.go +++ /dev/null @@ -1,108 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "strconv" -) - -// TakesValue returns true of the flag takes a value, otherwise false -func (f *Uint64Flag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f *Uint64Flag) GetUsage() string { - return f.Usage -} - -// GetCategory returns the category for the flag -func (f *Uint64Flag) GetCategory() string { - return f.Category -} - -// Apply populates the flag given the flag set and environment -func (f *Uint64Flag) Apply(set *flag.FlagSet) error { - // set default value so that environment wont be able to overwrite it - f.defaultValue = f.Value - f.defaultValueSet = true - - if val, source, found := flagFromEnvOrFile(f.EnvVars, f.FilePath); found { - if val != "" { - valInt, err := strconv.ParseUint(val, f.Base, 64) - if err != nil { - return fmt.Errorf("could not parse %q as uint64 value from %s for flag %s: %s", val, source, f.Name, err) - } - - f.Value = valInt - f.HasBeenSet = true - } - } - - for _, name := range f.Names() { - if f.Destination != nil { - set.Uint64Var(f.Destination, name, f.Value, f.Usage) - continue - } - set.Uint64(name, f.Value, f.Usage) - } - - return nil -} - -// RunAction executes flag action if set -func (f *Uint64Flag) RunAction(c *Context) error { - if f.Action != nil { - return f.Action(c, c.Uint64(f.Name)) - } - - return nil -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f *Uint64Flag) GetValue() string { - return fmt.Sprintf("%d", f.Value) -} - -// GetDefaultText returns the default text for this flag -func (f *Uint64Flag) GetDefaultText() string { - if f.DefaultText != "" { - return f.DefaultText - } - if f.defaultValueSet { - return fmt.Sprintf("%d", f.defaultValue) - } - return fmt.Sprintf("%d", f.Value) -} - -// GetEnvVars returns the env vars for this flag -func (f *Uint64Flag) GetEnvVars() []string { - return f.EnvVars -} - -// Get returns the flag’s value in the given Context. -func (f *Uint64Flag) Get(ctx *Context) uint64 { - return ctx.Uint64(f.Name) -} - -// Uint64 looks up the value of a local Uint64Flag, returns -// 0 if not found -func (cCtx *Context) Uint64(name string) uint64 { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return lookupUint64(name, fs) - } - return 0 -} - -func lookupUint64(name string, set *flag.FlagSet) uint64 { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseUint(f.Value.String(), 0, 64) - if err != nil { - return 0 - } - return parsed - } - return 0 -} diff --git a/vendor/github.com/urfave/cli/v2/flag_uint64_slice.go b/vendor/github.com/urfave/cli/v2/flag_uint64_slice.go deleted file mode 100644 index d3420186..00000000 --- a/vendor/github.com/urfave/cli/v2/flag_uint64_slice.go +++ /dev/null @@ -1,219 +0,0 @@ -package cli - -import ( - "encoding/json" - "flag" - "fmt" - "strconv" - "strings" -) - -// Uint64Slice wraps []int64 to satisfy flag.Value -type Uint64Slice struct { - slice []uint64 - separator separatorSpec - hasBeenSet bool -} - -// NewUint64Slice makes an *Uint64Slice with default values -func NewUint64Slice(defaults ...uint64) *Uint64Slice { - return &Uint64Slice{slice: append([]uint64{}, defaults...)} -} - -// clone allocate a copy of self object -func (i *Uint64Slice) clone() *Uint64Slice { - n := &Uint64Slice{ - slice: make([]uint64, len(i.slice)), - hasBeenSet: i.hasBeenSet, - } - copy(n.slice, i.slice) - return n -} - -// Set parses the value into an integer and appends it to the list of values -func (i *Uint64Slice) Set(value string) error { - if !i.hasBeenSet { - i.slice = []uint64{} - i.hasBeenSet = true - } - - if strings.HasPrefix(value, slPfx) { - // Deserializing assumes overwrite - _ = json.Unmarshal([]byte(strings.Replace(value, slPfx, "", 1)), &i.slice) - i.hasBeenSet = true - return nil - } - - for _, s := range i.separator.flagSplitMultiValues(value) { - tmp, err := strconv.ParseUint(strings.TrimSpace(s), 0, 64) - if err != nil { - return err - } - - i.slice = append(i.slice, tmp) - } - - return nil -} - -func (i *Uint64Slice) WithSeparatorSpec(spec separatorSpec) { - i.separator = spec -} - -// String returns a readable representation of this value (for usage defaults) -func (i *Uint64Slice) String() string { - v := i.slice - if v == nil { - // treat nil the same as zero length non-nil - v = make([]uint64, 0) - } - str := fmt.Sprintf("%d", v) - str = strings.Replace(str, " ", ", ", -1) - str = strings.Replace(str, "[", "{", -1) - str = strings.Replace(str, "]", "}", -1) - return fmt.Sprintf("[]uint64%s", str) -} - -// Serialize allows Uint64Slice to fulfill Serializer -func (i *Uint64Slice) Serialize() string { - jsonBytes, _ := json.Marshal(i.slice) - return fmt.Sprintf("%s%s", slPfx, string(jsonBytes)) -} - -// Value returns the slice of ints set by this flag -func (i *Uint64Slice) Value() []uint64 { - return i.slice -} - -// Get returns the slice of ints set by this flag -func (i *Uint64Slice) Get() interface{} { - return *i -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f *Uint64SliceFlag) String() string { - return FlagStringer(f) -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f *Uint64SliceFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f *Uint64SliceFlag) GetUsage() string { - return f.Usage -} - -// GetCategory returns the category for the flag -func (f *Uint64SliceFlag) GetCategory() string { - return f.Category -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f *Uint64SliceFlag) GetValue() string { - var defaultVals []string - if f.Value != nil && len(f.Value.Value()) > 0 { - for _, i := range f.Value.Value() { - defaultVals = append(defaultVals, strconv.FormatUint(i, 10)) - } - } - return strings.Join(defaultVals, ", ") -} - -// GetDefaultText returns the default text for this flag -func (f *Uint64SliceFlag) GetDefaultText() string { - if f.DefaultText != "" { - return f.DefaultText - } - return f.GetValue() -} - -// GetEnvVars returns the env vars for this flag -func (f *Uint64SliceFlag) GetEnvVars() []string { - return f.EnvVars -} - -// IsSliceFlag implements DocGenerationSliceFlag. -func (f *Uint64SliceFlag) IsSliceFlag() bool { - return true -} - -// Apply populates the flag given the flag set and environment -func (f *Uint64SliceFlag) Apply(set *flag.FlagSet) error { - // apply any default - if f.Destination != nil && f.Value != nil { - f.Destination.slice = make([]uint64, len(f.Value.slice)) - copy(f.Destination.slice, f.Value.slice) - } - - // resolve setValue (what we will assign to the set) - var setValue *Uint64Slice - switch { - case f.Destination != nil: - setValue = f.Destination - case f.Value != nil: - setValue = f.Value.clone() - default: - setValue = new(Uint64Slice) - setValue.WithSeparatorSpec(f.separator) - } - - if val, source, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok && val != "" { - for _, s := range f.separator.flagSplitMultiValues(val) { - if err := setValue.Set(strings.TrimSpace(s)); err != nil { - return fmt.Errorf("could not parse %q as uint64 slice value from %s for flag %s: %s", val, source, f.Name, err) - } - } - - // Set this to false so that we reset the slice if we then set values from - // flags that have already been set by the environment. - setValue.hasBeenSet = false - f.HasBeenSet = true - } - - for _, name := range f.Names() { - set.Var(setValue, name, f.Usage) - } - - return nil -} - -func (f *Uint64SliceFlag) WithSeparatorSpec(spec separatorSpec) { - f.separator = spec -} - -// Get returns the flag’s value in the given Context. -func (f *Uint64SliceFlag) Get(ctx *Context) []uint64 { - return ctx.Uint64Slice(f.Name) -} - -// RunAction executes flag action if set -func (f *Uint64SliceFlag) RunAction(c *Context) error { - if f.Action != nil { - return f.Action(c, c.Uint64Slice(f.Name)) - } - - return nil -} - -// Uint64Slice looks up the value of a local Uint64SliceFlag, returns -// nil if not found -func (cCtx *Context) Uint64Slice(name string) []uint64 { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return lookupUint64Slice(name, fs) - } - return nil -} - -func lookupUint64Slice(name string, set *flag.FlagSet) []uint64 { - f := set.Lookup(name) - if f != nil { - if slice, ok := unwrapFlagValue(f.Value).(*Uint64Slice); ok { - return slice.Value() - } - } - return nil -} diff --git a/vendor/github.com/urfave/cli/v2/flag_uint_slice.go b/vendor/github.com/urfave/cli/v2/flag_uint_slice.go deleted file mode 100644 index 4dc13e12..00000000 --- a/vendor/github.com/urfave/cli/v2/flag_uint_slice.go +++ /dev/null @@ -1,230 +0,0 @@ -package cli - -import ( - "encoding/json" - "flag" - "fmt" - "strconv" - "strings" -) - -// UintSlice wraps []int to satisfy flag.Value -type UintSlice struct { - slice []uint - separator separatorSpec - hasBeenSet bool -} - -// NewUintSlice makes an *UintSlice with default values -func NewUintSlice(defaults ...uint) *UintSlice { - return &UintSlice{slice: append([]uint{}, defaults...)} -} - -// clone allocate a copy of self object -func (i *UintSlice) clone() *UintSlice { - n := &UintSlice{ - slice: make([]uint, len(i.slice)), - hasBeenSet: i.hasBeenSet, - } - copy(n.slice, i.slice) - return n -} - -// TODO: Consistently have specific Set function for Int64 and Float64 ? -// SetInt directly adds an integer to the list of values -func (i *UintSlice) SetUint(value uint) { - if !i.hasBeenSet { - i.slice = []uint{} - i.hasBeenSet = true - } - - i.slice = append(i.slice, value) -} - -// Set parses the value into an integer and appends it to the list of values -func (i *UintSlice) Set(value string) error { - if !i.hasBeenSet { - i.slice = []uint{} - i.hasBeenSet = true - } - - if strings.HasPrefix(value, slPfx) { - // Deserializing assumes overwrite - _ = json.Unmarshal([]byte(strings.Replace(value, slPfx, "", 1)), &i.slice) - i.hasBeenSet = true - return nil - } - - for _, s := range i.separator.flagSplitMultiValues(value) { - tmp, err := strconv.ParseUint(strings.TrimSpace(s), 0, 32) - if err != nil { - return err - } - - i.slice = append(i.slice, uint(tmp)) - } - - return nil -} - -func (i *UintSlice) WithSeparatorSpec(spec separatorSpec) { - i.separator = spec -} - -// String returns a readable representation of this value (for usage defaults) -func (i *UintSlice) String() string { - v := i.slice - if v == nil { - // treat nil the same as zero length non-nil - v = make([]uint, 0) - } - str := fmt.Sprintf("%d", v) - str = strings.Replace(str, " ", ", ", -1) - str = strings.Replace(str, "[", "{", -1) - str = strings.Replace(str, "]", "}", -1) - return fmt.Sprintf("[]uint%s", str) -} - -// Serialize allows UintSlice to fulfill Serializer -func (i *UintSlice) Serialize() string { - jsonBytes, _ := json.Marshal(i.slice) - return fmt.Sprintf("%s%s", slPfx, string(jsonBytes)) -} - -// Value returns the slice of ints set by this flag -func (i *UintSlice) Value() []uint { - return i.slice -} - -// Get returns the slice of ints set by this flag -func (i *UintSlice) Get() interface{} { - return *i -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f *UintSliceFlag) String() string { - return FlagStringer(f) -} - -// TakesValue returns true of the flag takes a value, otherwise false -func (f *UintSliceFlag) TakesValue() bool { - return true -} - -// GetUsage returns the usage string for the flag -func (f *UintSliceFlag) GetUsage() string { - return f.Usage -} - -// GetCategory returns the category for the flag -func (f *UintSliceFlag) GetCategory() string { - return f.Category -} - -// GetValue returns the flags value as string representation and an empty -// string if the flag takes no value at all. -func (f *UintSliceFlag) GetValue() string { - var defaultVals []string - if f.Value != nil && len(f.Value.Value()) > 0 { - for _, i := range f.Value.Value() { - defaultVals = append(defaultVals, strconv.FormatUint(uint64(i), 10)) - } - } - return strings.Join(defaultVals, ", ") -} - -// GetDefaultText returns the default text for this flag -func (f *UintSliceFlag) GetDefaultText() string { - if f.DefaultText != "" { - return f.DefaultText - } - return f.GetValue() -} - -// GetEnvVars returns the env vars for this flag -func (f *UintSliceFlag) GetEnvVars() []string { - return f.EnvVars -} - -// IsSliceFlag implements DocGenerationSliceFlag. -func (f *UintSliceFlag) IsSliceFlag() bool { - return true -} - -// Apply populates the flag given the flag set and environment -func (f *UintSliceFlag) Apply(set *flag.FlagSet) error { - // apply any default - if f.Destination != nil && f.Value != nil { - f.Destination.slice = make([]uint, len(f.Value.slice)) - copy(f.Destination.slice, f.Value.slice) - } - - // resolve setValue (what we will assign to the set) - var setValue *UintSlice - switch { - case f.Destination != nil: - setValue = f.Destination - case f.Value != nil: - setValue = f.Value.clone() - default: - setValue = new(UintSlice) - setValue.WithSeparatorSpec(f.separator) - } - - if val, source, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok && val != "" { - for _, s := range f.separator.flagSplitMultiValues(val) { - if err := setValue.Set(strings.TrimSpace(s)); err != nil { - return fmt.Errorf("could not parse %q as uint slice value from %s for flag %s: %s", val, source, f.Name, err) - } - } - - // Set this to false so that we reset the slice if we then set values from - // flags that have already been set by the environment. - setValue.hasBeenSet = false - f.HasBeenSet = true - } - - for _, name := range f.Names() { - set.Var(setValue, name, f.Usage) - } - - return nil -} - -func (f *UintSliceFlag) WithSeparatorSpec(spec separatorSpec) { - f.separator = spec -} - -// Get returns the flag’s value in the given Context. -func (f *UintSliceFlag) Get(ctx *Context) []uint { - return ctx.UintSlice(f.Name) -} - -// RunAction executes flag action if set -func (f *UintSliceFlag) RunAction(c *Context) error { - if f.Action != nil { - return f.Action(c, c.UintSlice(f.Name)) - } - - return nil -} - -// UintSlice looks up the value of a local UintSliceFlag, returns -// nil if not found -func (cCtx *Context) UintSlice(name string) []uint { - if fs := cCtx.lookupFlagSet(name); fs != nil { - return lookupUintSlice(name, fs) - } - return nil -} - -func lookupUintSlice(name string, set *flag.FlagSet) []uint { - f := set.Lookup(name) - if f != nil { - if slice, ok := unwrapFlagValue(f.Value).(*UintSlice); ok { - return slice.Value() - } - } - return nil -} diff --git a/vendor/github.com/urfave/cli/v2/godoc-current.txt b/vendor/github.com/urfave/cli/v2/godoc-current.txt deleted file mode 100644 index 4b620fee..00000000 --- a/vendor/github.com/urfave/cli/v2/godoc-current.txt +++ /dev/null @@ -1,2724 +0,0 @@ -package cli // import "github.com/urfave/cli/v2" - -Package cli provides a minimal framework for creating and organizing command -line Go applications. cli is designed to be easy to understand and write, -the most simple cli application can be written as follows: - - func main() { - (&cli.App{}).Run(os.Args) - } - -Of course this application does not do much, so let's make this an actual -application: - - func main() { - app := &cli.App{ - Name: "greet", - Usage: "say a greeting", - Action: func(c *cli.Context) error { - fmt.Println("Greetings") - return nil - }, - } - - app.Run(os.Args) - } - -VARIABLES - -var ( - SuggestFlag SuggestFlagFunc = nil // initialized in suggestions.go unless built with urfave_cli_no_suggest - SuggestCommand SuggestCommandFunc = nil // initialized in suggestions.go unless built with urfave_cli_no_suggest - SuggestDidYouMeanTemplate string = suggestDidYouMeanTemplate -) -var AppHelpTemplate = `NAME: - {{template "helpNameTemplate" .}} - -USAGE: - {{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}{{if .Args}}[arguments...]{{end}}{{end}}{{end}}{{if .Version}}{{if not .HideVersion}} - -VERSION: - {{.Version}}{{end}}{{end}}{{if .Description}} - -DESCRIPTION: - {{template "descriptionTemplate" .}}{{end}} -{{- if len .Authors}} - -AUTHOR{{template "authorsTemplate" .}}{{end}}{{if .VisibleCommands}} - -COMMANDS:{{template "visibleCommandCategoryTemplate" .}}{{end}}{{if .VisibleFlagCategories}} - -GLOBAL OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}} - -GLOBAL OPTIONS:{{template "visibleFlagTemplate" .}}{{end}}{{if .Copyright}} - -COPYRIGHT: - {{template "copyrightTemplate" .}}{{end}} -` - AppHelpTemplate is the text template for the Default help topic. cli.go - uses text/template to render templates. You can render custom help text by - setting this variable. - -var CommandHelpTemplate = `NAME: - {{template "helpNameTemplate" .}} - -USAGE: - {{template "usageTemplate" .}}{{if .Category}} - -CATEGORY: - {{.Category}}{{end}}{{if .Description}} - -DESCRIPTION: - {{template "descriptionTemplate" .}}{{end}}{{if .VisibleFlagCategories}} - -OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}} - -OPTIONS:{{template "visibleFlagTemplate" .}}{{end}} -` - CommandHelpTemplate is the text template for the command help topic. cli.go - uses text/template to render templates. You can render custom help text by - setting this variable. - -var ErrWriter io.Writer = os.Stderr - ErrWriter is used to write errors to the user. This can be anything - implementing the io.Writer interface and defaults to os.Stderr. - -var FishCompletionTemplate = `# {{ .App.Name }} fish shell completion - -function __fish_{{ .App.Name }}_no_subcommand --description 'Test if there has been any subcommand yet' - for i in (commandline -opc) - if contains -- $i{{ range $v := .AllCommands }} {{ $v }}{{ end }} - return 1 - end - end - return 0 -end - -{{ range $v := .Completions }}{{ $v }} -{{ end }}` -var MarkdownDocTemplate = `{{if gt .SectionNum 0}}% {{ .App.Name }} {{ .SectionNum }} - -{{end}}# NAME - -{{ .App.Name }}{{ if .App.Usage }} - {{ .App.Usage }}{{ end }} - -# SYNOPSIS - -{{ .App.Name }} -{{ if .SynopsisArgs }} -` + "```" + ` -{{ range $v := .SynopsisArgs }}{{ $v }}{{ end }}` + "```" + ` -{{ end }}{{ if .App.Description }} -# DESCRIPTION - -{{ .App.Description }} -{{ end }} -**Usage**: - -` + "```" + `{{ if .App.UsageText }} -{{ .App.UsageText }} -{{ else }} -{{ .App.Name }} [GLOBAL OPTIONS] command [COMMAND OPTIONS] [ARGUMENTS...] -{{ end }}` + "```" + ` -{{ if .GlobalArgs }} -# GLOBAL OPTIONS -{{ range $v := .GlobalArgs }} -{{ $v }}{{ end }} -{{ end }}{{ if .Commands }} -# COMMANDS -{{ range $v := .Commands }} -{{ $v }}{{ end }}{{ end }}` -var OsExiter = os.Exit - OsExiter is the function used when the app exits. If not set defaults to - os.Exit. - -var SubcommandHelpTemplate = `NAME: - {{template "helpNameTemplate" .}} - -USAGE: - {{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.HelpName}} {{if .VisibleFlags}}command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}{{if .Args}}[arguments...]{{end}}{{end}}{{end}}{{if .Description}} - -DESCRIPTION: - {{template "descriptionTemplate" .}}{{end}}{{if .VisibleCommands}} - -COMMANDS:{{template "visibleCommandCategoryTemplate" .}}{{end}}{{if .VisibleFlagCategories}} - -OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}} - -OPTIONS:{{template "visibleFlagTemplate" .}}{{end}} -` - SubcommandHelpTemplate is the text template for the subcommand help topic. - cli.go uses text/template to render templates. You can render custom help - text by setting this variable. - -var VersionPrinter = printVersion - VersionPrinter prints the version for the App - -var HelpPrinter helpPrinter = printHelp - HelpPrinter is a function that writes the help output. If not set - explicitly, this calls HelpPrinterCustom using only the default template - functions. - - If custom logic for printing help is required, this function can be - overridden. If the ExtraInfo field is defined on an App, this function - should not be modified, as HelpPrinterCustom will be used directly in order - to capture the extra information. - -var HelpPrinterCustom helpPrinterCustom = printHelpCustom - HelpPrinterCustom is a function that writes the help output. It is used as - the default implementation of HelpPrinter, and may be called directly if the - ExtraInfo field is set on an App. - - In the default implementation, if the customFuncs argument contains a - "wrapAt" key, which is a function which takes no arguments and returns an - int, this int value will be used to produce a "wrap" function used by the - default template to wrap long lines. - - -FUNCTIONS - -func DefaultAppComplete(cCtx *Context) - DefaultAppComplete prints the list of subcommands as the default app - completion method - -func DefaultCompleteWithFlags(cmd *Command) func(cCtx *Context) -func FlagNames(name string, aliases []string) []string -func HandleAction(action interface{}, cCtx *Context) (err error) - HandleAction attempts to figure out which Action signature was used. - If it's an ActionFunc or a func with the legacy signature for Action, - the func is run! - -func HandleExitCoder(err error) - HandleExitCoder handles errors implementing ExitCoder by printing their - message and calling OsExiter with the given exit code. - - If the given error instead implements MultiError, each error will be checked - for the ExitCoder interface, and OsExiter will be called with the last exit - code found, or exit code 1 if no ExitCoder is found. - - This function is the default error-handling behavior for an App. - -func ShowAppHelp(cCtx *Context) error - ShowAppHelp is an action that displays the help. - -func ShowAppHelpAndExit(c *Context, exitCode int) - ShowAppHelpAndExit - Prints the list of subcommands for the app and exits - with exit code. - -func ShowCommandCompletions(ctx *Context, command string) - ShowCommandCompletions prints the custom completions for a given command - -func ShowCommandHelp(ctx *Context, command string) error - ShowCommandHelp prints help for the given command - -func ShowCommandHelpAndExit(c *Context, command string, code int) - ShowCommandHelpAndExit - exits with code after showing help - -func ShowCompletions(cCtx *Context) - ShowCompletions prints the lists of commands within a given context - -func ShowSubcommandHelp(cCtx *Context) error - ShowSubcommandHelp prints help for the given subcommand - -func ShowSubcommandHelpAndExit(c *Context, exitCode int) - ShowSubcommandHelpAndExit - Prints help for the given subcommand and exits - with exit code. - -func ShowVersion(cCtx *Context) - ShowVersion prints the version number of the App - - -TYPES - -type ActionFunc func(*Context) error - ActionFunc is the action to execute when no subcommands are specified - -type ActionableFlag interface { - Flag - RunAction(*Context) error -} - ActionableFlag is an interface that wraps Flag interface and RunAction - operation. - -type AfterFunc func(*Context) error - AfterFunc is an action to execute after any subcommands are run, but after - the subcommand has finished it is run even if Action() panics - -type App struct { - // The name of the program. Defaults to path.Base(os.Args[0]) - Name string - // Full name of command for help, defaults to Name - HelpName string - // Description of the program. - Usage string - // Text to override the USAGE section of help - UsageText string - // Whether this command supports arguments - Args bool - // Description of the program argument format. - ArgsUsage string - // Version of the program - Version string - // Description of the program - Description string - // DefaultCommand is the (optional) name of a command - // to run if no command names are passed as CLI arguments. - DefaultCommand string - // List of commands to execute - Commands []*Command - // List of flags to parse - Flags []Flag - // Boolean to enable bash completion commands - EnableBashCompletion bool - // Boolean to hide built-in help command and help flag - HideHelp bool - // Boolean to hide built-in help command but keep help flag. - // Ignored if HideHelp is true. - HideHelpCommand bool - // Boolean to hide built-in version flag and the VERSION section of help - HideVersion bool - - // An action to execute when the shell completion flag is set - BashComplete BashCompleteFunc - // An action to execute before any subcommands are run, but after the context is ready - // If a non-nil error is returned, no subcommands are run - Before BeforeFunc - // An action to execute after any subcommands are run, but after the subcommand has finished - // It is run even if Action() panics - After AfterFunc - // The action to execute when no subcommands are specified - Action ActionFunc - // Execute this function if the proper command cannot be found - CommandNotFound CommandNotFoundFunc - // Execute this function if a usage error occurs - OnUsageError OnUsageErrorFunc - // Execute this function when an invalid flag is accessed from the context - InvalidFlagAccessHandler InvalidFlagAccessFunc - // Compilation date - Compiled time.Time - // List of all authors who contributed - Authors []*Author - // Copyright of the binary if any - Copyright string - // Reader reader to write input to (useful for tests) - Reader io.Reader - // Writer writer to write output to - Writer io.Writer - // ErrWriter writes error output - ErrWriter io.Writer - // ExitErrHandler processes any error encountered while running an App before - // it is returned to the caller. If no function is provided, HandleExitCoder - // is used as the default behavior. - ExitErrHandler ExitErrHandlerFunc - // Other custom info - Metadata map[string]interface{} - // Carries a function which returns app specific info. - ExtraInfo func() map[string]string - // CustomAppHelpTemplate the text template for app help topic. - // cli.go uses text/template to render templates. You can - // render custom help text by setting this variable. - CustomAppHelpTemplate string - // SliceFlagSeparator is used to customize the separator for SliceFlag, the default is "," - SliceFlagSeparator string - // DisableSliceFlagSeparator is used to disable SliceFlagSeparator, the default is false - DisableSliceFlagSeparator bool - // Boolean to enable short-option handling so user can combine several - // single-character bool arguments into one - // i.e. foobar -o -v -> foobar -ov - UseShortOptionHandling bool - // Enable suggestions for commands and flags - Suggest bool - // Allows global flags set by libraries which use flag.XXXVar(...) directly - // to be parsed through this library - AllowExtFlags bool - // Treat all flags as normal arguments if true - SkipFlagParsing bool - - // Has unexported fields. -} - App is the main structure of a cli application. It is recommended that an - app be created with the cli.NewApp() function - -func NewApp() *App - NewApp creates a new cli Application with some reasonable defaults for Name, - Usage, Version and Action. - -func (a *App) Command(name string) *Command - Command returns the named command on App. Returns nil if the command does - not exist - -func (a *App) Run(arguments []string) (err error) - Run is the entry point to the cli app. Parses the arguments slice and routes - to the proper flag/args combination - -func (a *App) RunAndExitOnError() - RunAndExitOnError calls .Run() and exits non-zero if an error was returned - - Deprecated: instead you should return an error that fulfills cli.ExitCoder - to cli.App.Run. This will cause the application to exit with the given error - code in the cli.ExitCoder - -func (a *App) RunAsSubcommand(ctx *Context) (err error) - RunAsSubcommand is for legacy/compatibility purposes only. New code should - only use App.RunContext. This function is slated to be removed in v3. - -func (a *App) RunContext(ctx context.Context, arguments []string) (err error) - RunContext is like Run except it takes a Context that will be passed to - its commands and sub-commands. Through this, you can propagate timeouts and - cancellation requests - -func (a *App) Setup() - Setup runs initialization code to ensure all data structures are ready - for `Run` or inspection prior to `Run`. It is internally called by `Run`, - but will return early if setup has already happened. - -func (a *App) ToFishCompletion() (string, error) - ToFishCompletion creates a fish completion string for the `*App` The - function errors if either parsing or writing of the string fails. - -func (a *App) ToMan() (string, error) - ToMan creates a man page string for the `*App` The function errors if either - parsing or writing of the string fails. - -func (a *App) ToManWithSection(sectionNumber int) (string, error) - ToMan creates a man page string with section number for the `*App` The - function errors if either parsing or writing of the string fails. - -func (a *App) ToMarkdown() (string, error) - ToMarkdown creates a markdown string for the `*App` The function errors if - either parsing or writing of the string fails. - -func (a *App) VisibleCategories() []CommandCategory - VisibleCategories returns a slice of categories and commands that are - Hidden=false - -func (a *App) VisibleCommands() []*Command - VisibleCommands returns a slice of the Commands with Hidden=false - -func (a *App) VisibleFlagCategories() []VisibleFlagCategory - VisibleFlagCategories returns a slice containing all the categories with the - flags they contain - -func (a *App) VisibleFlags() []Flag - VisibleFlags returns a slice of the Flags with Hidden=false - -type Args interface { - // Get returns the nth argument, or else a blank string - Get(n int) string - // First returns the first argument, or else a blank string - First() string - // Tail returns the rest of the arguments (not the first one) - // or else an empty string slice - Tail() []string - // Len returns the length of the wrapped slice - Len() int - // Present checks if there are any arguments present - Present() bool - // Slice returns a copy of the internal slice - Slice() []string -} - -type Author struct { - Name string // The Authors name - Email string // The Authors email -} - Author represents someone who has contributed to a cli project. - -func (a *Author) String() string - String makes Author comply to the Stringer interface, to allow an easy print - in the templating process - -type BashCompleteFunc func(*Context) - BashCompleteFunc is an action to execute when the shell completion flag is - set - -type BeforeFunc func(*Context) error - BeforeFunc is an action to execute before any subcommands are run, but after - the context is ready if a non-nil error is returned, no subcommands are run - -type BoolFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value bool - Destination *bool - - Aliases []string - EnvVars []string - - Count *int - - DisableDefaultText bool - - Action func(*Context, bool) error - // Has unexported fields. -} - BoolFlag is a flag with type bool - -func (f *BoolFlag) Apply(set *flag.FlagSet) error - Apply populates the flag given the flag set and environment - -func (f *BoolFlag) Get(ctx *Context) bool - Get returns the flag’s value in the given Context. - -func (f *BoolFlag) GetCategory() string - GetCategory returns the category for the flag - -func (f *BoolFlag) GetDefaultText() string - GetDefaultText returns the default text for this flag - -func (f *BoolFlag) GetEnvVars() []string - GetEnvVars returns the env vars for this flag - -func (f *BoolFlag) GetUsage() string - GetUsage returns the usage string for the flag - -func (f *BoolFlag) GetValue() string - GetValue returns the flags value as string representation and an empty - string if the flag takes no value at all. - -func (f *BoolFlag) IsRequired() bool - IsRequired returns whether or not the flag is required - -func (f *BoolFlag) IsSet() bool - IsSet returns whether or not the flag has been set through env or file - -func (f *BoolFlag) IsVisible() bool - IsVisible returns true if the flag is not hidden, otherwise false - -func (f *BoolFlag) Names() []string - Names returns the names of the flag - -func (f *BoolFlag) RunAction(c *Context) error - RunAction executes flag action if set - -func (f *BoolFlag) String() string - String returns a readable representation of this value (for usage defaults) - -func (f *BoolFlag) TakesValue() bool - TakesValue returns true of the flag takes a value, otherwise false - -type CategorizableFlag interface { - VisibleFlag - - GetCategory() string -} - CategorizableFlag is an interface that allows us to potentially use a flag - in a categorized representation. - -type Command struct { - // The name of the command - Name string - // A list of aliases for the command - Aliases []string - // A short description of the usage of this command - Usage string - // Custom text to show on USAGE section of help - UsageText string - // A longer explanation of how the command works - Description string - // Whether this command supports arguments - Args bool - // A short description of the arguments of this command - ArgsUsage string - // The category the command is part of - Category string - // The function to call when checking for bash command completions - BashComplete BashCompleteFunc - // An action to execute before any sub-subcommands are run, but after the context is ready - // If a non-nil error is returned, no sub-subcommands are run - Before BeforeFunc - // An action to execute after any subcommands are run, but after the subcommand has finished - // It is run even if Action() panics - After AfterFunc - // The function to call when this command is invoked - Action ActionFunc - // Execute this function if a usage error occurs. - OnUsageError OnUsageErrorFunc - // List of child commands - Subcommands []*Command - // List of flags to parse - Flags []Flag - - // Treat all flags as normal arguments if true - SkipFlagParsing bool - // Boolean to hide built-in help command and help flag - HideHelp bool - // Boolean to hide built-in help command but keep help flag - // Ignored if HideHelp is true. - HideHelpCommand bool - // Boolean to hide this command from help or completion - Hidden bool - // Boolean to enable short-option handling so user can combine several - // single-character bool arguments into one - // i.e. foobar -o -v -> foobar -ov - UseShortOptionHandling bool - - // Full name of command for help, defaults to full command name, including parent commands. - HelpName string - - // CustomHelpTemplate the text template for the command help topic. - // cli.go uses text/template to render templates. You can - // render custom help text by setting this variable. - CustomHelpTemplate string - - // Has unexported fields. -} - Command is a subcommand for a cli.App. - -func (cmd *Command) Command(name string) *Command - -func (c *Command) FullName() string - FullName returns the full name of the command. For subcommands this ensures - that parent commands are part of the command path - -func (c *Command) HasName(name string) bool - HasName returns true if Command.Name matches given name - -func (c *Command) Names() []string - Names returns the names including short names and aliases. - -func (c *Command) Run(cCtx *Context, arguments ...string) (err error) - -func (c *Command) VisibleCategories() []CommandCategory - VisibleCategories returns a slice of categories and commands that are - Hidden=false - -func (c *Command) VisibleCommands() []*Command - VisibleCommands returns a slice of the Commands with Hidden=false - -func (c *Command) VisibleFlagCategories() []VisibleFlagCategory - VisibleFlagCategories returns a slice containing all the visible flag - categories with the flags they contain - -func (c *Command) VisibleFlags() []Flag - VisibleFlags returns a slice of the Flags with Hidden=false - -type CommandCategories interface { - // AddCommand adds a command to a category, creating a new category if necessary. - AddCommand(category string, command *Command) - // Categories returns a slice of categories sorted by name - Categories() []CommandCategory -} - CommandCategories interface allows for category manipulation - -type CommandCategory interface { - // Name returns the category name string - Name() string - // VisibleCommands returns a slice of the Commands with Hidden=false - VisibleCommands() []*Command -} - CommandCategory is a category containing commands. - -type CommandNotFoundFunc func(*Context, string) - CommandNotFoundFunc is executed if the proper command cannot be found - -type Commands []*Command - -type CommandsByName []*Command - -func (c CommandsByName) Len() int - -func (c CommandsByName) Less(i, j int) bool - -func (c CommandsByName) Swap(i, j int) - -type Context struct { - context.Context - App *App - Command *Command - - // Has unexported fields. -} - Context is a type that is passed through to each Handler action in a cli - application. Context can be used to retrieve context-specific args and - parsed command-line options. - -func NewContext(app *App, set *flag.FlagSet, parentCtx *Context) *Context - NewContext creates a new context. For use in when invoking an App or Command - action. - -func (cCtx *Context) Args() Args - Args returns the command line arguments associated with the context. - -func (cCtx *Context) Bool(name string) bool - Bool looks up the value of a local BoolFlag, returns false if not found - -func (cCtx *Context) Count(name string) int - Count returns the num of occurrences of this flag - -func (cCtx *Context) Duration(name string) time.Duration - Duration looks up the value of a local DurationFlag, returns 0 if not found - -func (cCtx *Context) FlagNames() []string - FlagNames returns a slice of flag names used by the this context and all of - its parent contexts. - -func (cCtx *Context) Float64(name string) float64 - Float64 looks up the value of a local Float64Flag, returns 0 if not found - -func (cCtx *Context) Float64Slice(name string) []float64 - Float64Slice looks up the value of a local Float64SliceFlag, returns nil if - not found - -func (cCtx *Context) Generic(name string) interface{} - Generic looks up the value of a local GenericFlag, returns nil if not found - -func (cCtx *Context) Int(name string) int - Int looks up the value of a local IntFlag, returns 0 if not found - -func (cCtx *Context) Int64(name string) int64 - Int64 looks up the value of a local Int64Flag, returns 0 if not found - -func (cCtx *Context) Int64Slice(name string) []int64 - Int64Slice looks up the value of a local Int64SliceFlag, returns nil if not - found - -func (cCtx *Context) IntSlice(name string) []int - IntSlice looks up the value of a local IntSliceFlag, returns nil if not - found - -func (cCtx *Context) IsSet(name string) bool - IsSet determines if the flag was actually set - -func (cCtx *Context) Lineage() []*Context - Lineage returns *this* context and all of its ancestor contexts in order - from child to parent - -func (cCtx *Context) LocalFlagNames() []string - LocalFlagNames returns a slice of flag names used in this context. - -func (cCtx *Context) NArg() int - NArg returns the number of the command line arguments. - -func (cCtx *Context) NumFlags() int - NumFlags returns the number of flags set - -func (cCtx *Context) Path(name string) string - Path looks up the value of a local PathFlag, returns "" if not found - -func (cCtx *Context) Set(name, value string) error - Set sets a context flag to a value. - -func (cCtx *Context) String(name string) string - String looks up the value of a local StringFlag, returns "" if not found - -func (cCtx *Context) StringSlice(name string) []string - StringSlice looks up the value of a local StringSliceFlag, returns nil if - not found - -func (cCtx *Context) Timestamp(name string) *time.Time - Timestamp gets the timestamp from a flag name - -func (cCtx *Context) Uint(name string) uint - Uint looks up the value of a local UintFlag, returns 0 if not found - -func (cCtx *Context) Uint64(name string) uint64 - Uint64 looks up the value of a local Uint64Flag, returns 0 if not found - -func (cCtx *Context) Uint64Slice(name string) []uint64 - Uint64Slice looks up the value of a local Uint64SliceFlag, returns nil if - not found - -func (cCtx *Context) UintSlice(name string) []uint - UintSlice looks up the value of a local UintSliceFlag, returns nil if not - found - -func (cCtx *Context) Value(name string) interface{} - Value returns the value of the flag corresponding to `name` - -type Countable interface { - Count() int -} - Countable is an interface to enable detection of flag values which support - repetitive flags - -type DocGenerationFlag interface { - Flag - - // TakesValue returns true if the flag takes a value, otherwise false - TakesValue() bool - - // GetUsage returns the usage string for the flag - GetUsage() string - - // GetValue returns the flags value as string representation and an empty - // string if the flag takes no value at all. - GetValue() string - - // GetDefaultText returns the default text for this flag - GetDefaultText() string - - // GetEnvVars returns the env vars for this flag - GetEnvVars() []string -} - DocGenerationFlag is an interface that allows documentation generation for - the flag - -type DocGenerationSliceFlag interface { - DocGenerationFlag - - // IsSliceFlag returns true for flags that can be given multiple times. - IsSliceFlag() bool -} - DocGenerationSliceFlag extends DocGenerationFlag for slice-based flags. - -type DurationFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value time.Duration - Destination *time.Duration - - Aliases []string - EnvVars []string - - Action func(*Context, time.Duration) error - // Has unexported fields. -} - DurationFlag is a flag with type time.Duration - -func (f *DurationFlag) Apply(set *flag.FlagSet) error - Apply populates the flag given the flag set and environment - -func (f *DurationFlag) Get(ctx *Context) time.Duration - Get returns the flag’s value in the given Context. - -func (f *DurationFlag) GetCategory() string - GetCategory returns the category for the flag - -func (f *DurationFlag) GetDefaultText() string - GetDefaultText returns the default text for this flag - -func (f *DurationFlag) GetEnvVars() []string - GetEnvVars returns the env vars for this flag - -func (f *DurationFlag) GetUsage() string - GetUsage returns the usage string for the flag - -func (f *DurationFlag) GetValue() string - GetValue returns the flags value as string representation and an empty - string if the flag takes no value at all. - -func (f *DurationFlag) IsRequired() bool - IsRequired returns whether or not the flag is required - -func (f *DurationFlag) IsSet() bool - IsSet returns whether or not the flag has been set through env or file - -func (f *DurationFlag) IsVisible() bool - IsVisible returns true if the flag is not hidden, otherwise false - -func (f *DurationFlag) Names() []string - Names returns the names of the flag - -func (f *DurationFlag) RunAction(c *Context) error - RunAction executes flag action if set - -func (f *DurationFlag) String() string - String returns a readable representation of this value (for usage defaults) - -func (f *DurationFlag) TakesValue() bool - TakesValue returns true of the flag takes a value, otherwise false - -type ErrorFormatter interface { - Format(s fmt.State, verb rune) -} - ErrorFormatter is the interface that will suitably format the error output - -type ExitCoder interface { - error - ExitCode() int -} - ExitCoder is the interface checked by `App` and `Command` for a custom exit - code - -func Exit(message interface{}, exitCode int) ExitCoder - Exit wraps a message and exit code into an error, which by default is - handled with a call to os.Exit during default error handling. - - This is the simplest way to trigger a non-zero exit code for an App - without having to call os.Exit manually. During testing, this behavior - can be avoided by overriding the ExitErrHandler function on an App or the - package-global OsExiter function. - -func NewExitError(message interface{}, exitCode int) ExitCoder - NewExitError calls Exit to create a new ExitCoder. - - Deprecated: This function is a duplicate of Exit and will eventually be - removed. - -type ExitErrHandlerFunc func(cCtx *Context, err error) - ExitErrHandlerFunc is executed if provided in order to handle exitError - values returned by Actions and Before/After functions. - -type Flag interface { - fmt.Stringer - // Apply Flag settings to the given flag set - Apply(*flag.FlagSet) error - Names() []string - IsSet() bool -} - Flag is a common interface related to parsing flags in cli. For more - advanced flag parsing techniques, it is recommended that this interface be - implemented. - -var BashCompletionFlag Flag = &BoolFlag{ - Name: "generate-bash-completion", - Hidden: true, -} - BashCompletionFlag enables bash-completion for all commands and subcommands - -var HelpFlag Flag = &BoolFlag{ - Name: "help", - Aliases: []string{"h"}, - Usage: "show help", - DisableDefaultText: true, -} - HelpFlag prints the help for all commands and subcommands. Set to nil to - disable the flag. The subcommand will still be added unless HideHelp or - HideHelpCommand is set to true. - -var VersionFlag Flag = &BoolFlag{ - Name: "version", - Aliases: []string{"v"}, - Usage: "print the version", - DisableDefaultText: true, -} - VersionFlag prints the version for the application - -type FlagCategories interface { - // AddFlags adds a flag to a category, creating a new category if necessary. - AddFlag(category string, fl Flag) - // VisibleCategories returns a slice of visible flag categories sorted by name - VisibleCategories() []VisibleFlagCategory -} - FlagCategories interface allows for category manipulation - -type FlagEnvHintFunc func(envVars []string, str string) string - FlagEnvHintFunc is used by the default FlagStringFunc to annotate flag help - with the environment variable details. - -var FlagEnvHinter FlagEnvHintFunc = withEnvHint - FlagEnvHinter annotates flag help message with the environment variable - details. This is used by the default FlagStringer. - -type FlagFileHintFunc func(filePath, str string) string - FlagFileHintFunc is used by the default FlagStringFunc to annotate flag help - with the file path details. - -var FlagFileHinter FlagFileHintFunc = withFileHint - FlagFileHinter annotates flag help message with the environment variable - details. This is used by the default FlagStringer. - -type FlagNamePrefixFunc func(fullName []string, placeholder string) string - FlagNamePrefixFunc is used by the default FlagStringFunc to create prefix - text for a flag's full name. - -var FlagNamePrefixer FlagNamePrefixFunc = prefixedNames - FlagNamePrefixer converts a full flag name and its placeholder into the help - message flag prefix. This is used by the default FlagStringer. - -type FlagStringFunc func(Flag) string - FlagStringFunc is used by the help generation to display a flag, which is - expected to be a single line. - -var FlagStringer FlagStringFunc = stringifyFlag - FlagStringer converts a flag definition to a string. This is used by help to - display a flag. - -type FlagsByName []Flag - FlagsByName is a slice of Flag. - -func (f FlagsByName) Len() int - -func (f FlagsByName) Less(i, j int) bool - -func (f FlagsByName) Swap(i, j int) - -type Float64Flag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value float64 - Destination *float64 - - Aliases []string - EnvVars []string - - Action func(*Context, float64) error - // Has unexported fields. -} - Float64Flag is a flag with type float64 - -func (f *Float64Flag) Apply(set *flag.FlagSet) error - Apply populates the flag given the flag set and environment - -func (f *Float64Flag) Get(ctx *Context) float64 - Get returns the flag’s value in the given Context. - -func (f *Float64Flag) GetCategory() string - GetCategory returns the category for the flag - -func (f *Float64Flag) GetDefaultText() string - GetDefaultText returns the default text for this flag - -func (f *Float64Flag) GetEnvVars() []string - GetEnvVars returns the env vars for this flag - -func (f *Float64Flag) GetUsage() string - GetUsage returns the usage string for the flag - -func (f *Float64Flag) GetValue() string - GetValue returns the flags value as string representation and an empty - string if the flag takes no value at all. - -func (f *Float64Flag) IsRequired() bool - IsRequired returns whether or not the flag is required - -func (f *Float64Flag) IsSet() bool - IsSet returns whether or not the flag has been set through env or file - -func (f *Float64Flag) IsVisible() bool - IsVisible returns true if the flag is not hidden, otherwise false - -func (f *Float64Flag) Names() []string - Names returns the names of the flag - -func (f *Float64Flag) RunAction(c *Context) error - RunAction executes flag action if set - -func (f *Float64Flag) String() string - String returns a readable representation of this value (for usage defaults) - -func (f *Float64Flag) TakesValue() bool - TakesValue returns true of the flag takes a value, otherwise false - -type Float64Slice struct { - // Has unexported fields. -} - Float64Slice wraps []float64 to satisfy flag.Value - -func NewFloat64Slice(defaults ...float64) *Float64Slice - NewFloat64Slice makes a *Float64Slice with default values - -func (f *Float64Slice) Get() interface{} - Get returns the slice of float64s set by this flag - -func (f *Float64Slice) Serialize() string - Serialize allows Float64Slice to fulfill Serializer - -func (f *Float64Slice) Set(value string) error - Set parses the value into a float64 and appends it to the list of values - -func (f *Float64Slice) String() string - String returns a readable representation of this value (for usage defaults) - -func (f *Float64Slice) Value() []float64 - Value returns the slice of float64s set by this flag - -func (f *Float64Slice) WithSeparatorSpec(spec separatorSpec) - -type Float64SliceFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value *Float64Slice - Destination *Float64Slice - - Aliases []string - EnvVars []string - - Action func(*Context, []float64) error - // Has unexported fields. -} - Float64SliceFlag is a flag with type *Float64Slice - -func (f *Float64SliceFlag) Apply(set *flag.FlagSet) error - Apply populates the flag given the flag set and environment - -func (f *Float64SliceFlag) Get(ctx *Context) []float64 - Get returns the flag’s value in the given Context. - -func (f *Float64SliceFlag) GetCategory() string - GetCategory returns the category for the flag - -func (f *Float64SliceFlag) GetDefaultText() string - GetDefaultText returns the default text for this flag - -func (f *Float64SliceFlag) GetDestination() []float64 - -func (f *Float64SliceFlag) GetEnvVars() []string - GetEnvVars returns the env vars for this flag - -func (f *Float64SliceFlag) GetUsage() string - GetUsage returns the usage string for the flag - -func (f *Float64SliceFlag) GetValue() string - GetValue returns the flags value as string representation and an empty - string if the flag takes no value at all. - -func (f *Float64SliceFlag) IsRequired() bool - IsRequired returns whether or not the flag is required - -func (f *Float64SliceFlag) IsSet() bool - IsSet returns whether or not the flag has been set through env or file - -func (f *Float64SliceFlag) IsSliceFlag() bool - IsSliceFlag implements DocGenerationSliceFlag. - -func (f *Float64SliceFlag) IsVisible() bool - IsVisible returns true if the flag is not hidden, otherwise false - -func (f *Float64SliceFlag) Names() []string - Names returns the names of the flag - -func (f *Float64SliceFlag) RunAction(c *Context) error - RunAction executes flag action if set - -func (f *Float64SliceFlag) SetDestination(slice []float64) - -func (f *Float64SliceFlag) SetValue(slice []float64) - -func (f *Float64SliceFlag) String() string - String returns a readable representation of this value (for usage defaults) - -func (f *Float64SliceFlag) TakesValue() bool - TakesValue returns true if the flag takes a value, otherwise false - -func (f *Float64SliceFlag) WithSeparatorSpec(spec separatorSpec) - -type Generic interface { - Set(value string) error - String() string -} - Generic is a generic parseable type identified by a specific flag - -type GenericFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value Generic - Destination Generic - - Aliases []string - EnvVars []string - - TakesFile bool - - Action func(*Context, interface{}) error - // Has unexported fields. -} - GenericFlag is a flag with type Generic - -func (f *GenericFlag) Apply(set *flag.FlagSet) error - Apply takes the flagset and calls Set on the generic flag with the value - provided by the user for parsing by the flag - -func (f *GenericFlag) Get(ctx *Context) interface{} - Get returns the flag’s value in the given Context. - -func (f *GenericFlag) GetCategory() string - GetCategory returns the category for the flag - -func (f *GenericFlag) GetDefaultText() string - GetDefaultText returns the default text for this flag - -func (f *GenericFlag) GetEnvVars() []string - GetEnvVars returns the env vars for this flag - -func (f *GenericFlag) GetUsage() string - GetUsage returns the usage string for the flag - -func (f *GenericFlag) GetValue() string - GetValue returns the flags value as string representation and an empty - string if the flag takes no value at all. - -func (f *GenericFlag) IsRequired() bool - IsRequired returns whether or not the flag is required - -func (f *GenericFlag) IsSet() bool - IsSet returns whether or not the flag has been set through env or file - -func (f *GenericFlag) IsVisible() bool - IsVisible returns true if the flag is not hidden, otherwise false - -func (f *GenericFlag) Names() []string - Names returns the names of the flag - -func (f *GenericFlag) RunAction(c *Context) error - RunAction executes flag action if set - -func (f *GenericFlag) String() string - String returns a readable representation of this value (for usage defaults) - -func (f *GenericFlag) TakesValue() bool - TakesValue returns true of the flag takes a value, otherwise false - -type Int64Flag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value int64 - Destination *int64 - - Aliases []string - EnvVars []string - - Base int - - Action func(*Context, int64) error - // Has unexported fields. -} - Int64Flag is a flag with type int64 - -func (f *Int64Flag) Apply(set *flag.FlagSet) error - Apply populates the flag given the flag set and environment - -func (f *Int64Flag) Get(ctx *Context) int64 - Get returns the flag’s value in the given Context. - -func (f *Int64Flag) GetCategory() string - GetCategory returns the category for the flag - -func (f *Int64Flag) GetDefaultText() string - GetDefaultText returns the default text for this flag - -func (f *Int64Flag) GetEnvVars() []string - GetEnvVars returns the env vars for this flag - -func (f *Int64Flag) GetUsage() string - GetUsage returns the usage string for the flag - -func (f *Int64Flag) GetValue() string - GetValue returns the flags value as string representation and an empty - string if the flag takes no value at all. - -func (f *Int64Flag) IsRequired() bool - IsRequired returns whether or not the flag is required - -func (f *Int64Flag) IsSet() bool - IsSet returns whether or not the flag has been set through env or file - -func (f *Int64Flag) IsVisible() bool - IsVisible returns true if the flag is not hidden, otherwise false - -func (f *Int64Flag) Names() []string - Names returns the names of the flag - -func (f *Int64Flag) RunAction(c *Context) error - RunAction executes flag action if set - -func (f *Int64Flag) String() string - String returns a readable representation of this value (for usage defaults) - -func (f *Int64Flag) TakesValue() bool - TakesValue returns true of the flag takes a value, otherwise false - -type Int64Slice struct { - // Has unexported fields. -} - Int64Slice wraps []int64 to satisfy flag.Value - -func NewInt64Slice(defaults ...int64) *Int64Slice - NewInt64Slice makes an *Int64Slice with default values - -func (i *Int64Slice) Get() interface{} - Get returns the slice of ints set by this flag - -func (i *Int64Slice) Serialize() string - Serialize allows Int64Slice to fulfill Serializer - -func (i *Int64Slice) Set(value string) error - Set parses the value into an integer and appends it to the list of values - -func (i *Int64Slice) String() string - String returns a readable representation of this value (for usage defaults) - -func (i *Int64Slice) Value() []int64 - Value returns the slice of ints set by this flag - -func (i *Int64Slice) WithSeparatorSpec(spec separatorSpec) - -type Int64SliceFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value *Int64Slice - Destination *Int64Slice - - Aliases []string - EnvVars []string - - Action func(*Context, []int64) error - // Has unexported fields. -} - Int64SliceFlag is a flag with type *Int64Slice - -func (f *Int64SliceFlag) Apply(set *flag.FlagSet) error - Apply populates the flag given the flag set and environment - -func (f *Int64SliceFlag) Get(ctx *Context) []int64 - Get returns the flag’s value in the given Context. - -func (f *Int64SliceFlag) GetCategory() string - GetCategory returns the category for the flag - -func (f *Int64SliceFlag) GetDefaultText() string - GetDefaultText returns the default text for this flag - -func (f *Int64SliceFlag) GetDestination() []int64 - -func (f *Int64SliceFlag) GetEnvVars() []string - GetEnvVars returns the env vars for this flag - -func (f *Int64SliceFlag) GetUsage() string - GetUsage returns the usage string for the flag - -func (f *Int64SliceFlag) GetValue() string - GetValue returns the flags value as string representation and an empty - string if the flag takes no value at all. - -func (f *Int64SliceFlag) IsRequired() bool - IsRequired returns whether or not the flag is required - -func (f *Int64SliceFlag) IsSet() bool - IsSet returns whether or not the flag has been set through env or file - -func (f *Int64SliceFlag) IsSliceFlag() bool - IsSliceFlag implements DocGenerationSliceFlag. - -func (f *Int64SliceFlag) IsVisible() bool - IsVisible returns true if the flag is not hidden, otherwise false - -func (f *Int64SliceFlag) Names() []string - Names returns the names of the flag - -func (f *Int64SliceFlag) RunAction(c *Context) error - RunAction executes flag action if set - -func (f *Int64SliceFlag) SetDestination(slice []int64) - -func (f *Int64SliceFlag) SetValue(slice []int64) - -func (f *Int64SliceFlag) String() string - String returns a readable representation of this value (for usage defaults) - -func (f *Int64SliceFlag) TakesValue() bool - TakesValue returns true of the flag takes a value, otherwise false - -func (f *Int64SliceFlag) WithSeparatorSpec(spec separatorSpec) - -type IntFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value int - Destination *int - - Aliases []string - EnvVars []string - - Base int - - Action func(*Context, int) error - // Has unexported fields. -} - IntFlag is a flag with type int - -func (f *IntFlag) Apply(set *flag.FlagSet) error - Apply populates the flag given the flag set and environment - -func (f *IntFlag) Get(ctx *Context) int - Get returns the flag’s value in the given Context. - -func (f *IntFlag) GetCategory() string - GetCategory returns the category for the flag - -func (f *IntFlag) GetDefaultText() string - GetDefaultText returns the default text for this flag - -func (f *IntFlag) GetEnvVars() []string - GetEnvVars returns the env vars for this flag - -func (f *IntFlag) GetUsage() string - GetUsage returns the usage string for the flag - -func (f *IntFlag) GetValue() string - GetValue returns the flags value as string representation and an empty - string if the flag takes no value at all. - -func (f *IntFlag) IsRequired() bool - IsRequired returns whether or not the flag is required - -func (f *IntFlag) IsSet() bool - IsSet returns whether or not the flag has been set through env or file - -func (f *IntFlag) IsVisible() bool - IsVisible returns true if the flag is not hidden, otherwise false - -func (f *IntFlag) Names() []string - Names returns the names of the flag - -func (f *IntFlag) RunAction(c *Context) error - RunAction executes flag action if set - -func (f *IntFlag) String() string - String returns a readable representation of this value (for usage defaults) - -func (f *IntFlag) TakesValue() bool - TakesValue returns true of the flag takes a value, otherwise false - -type IntSlice struct { - // Has unexported fields. -} - IntSlice wraps []int to satisfy flag.Value - -func NewIntSlice(defaults ...int) *IntSlice - NewIntSlice makes an *IntSlice with default values - -func (i *IntSlice) Get() interface{} - Get returns the slice of ints set by this flag - -func (i *IntSlice) Serialize() string - Serialize allows IntSlice to fulfill Serializer - -func (i *IntSlice) Set(value string) error - Set parses the value into an integer and appends it to the list of values - -func (i *IntSlice) SetInt(value int) - TODO: Consistently have specific Set function for Int64 and Float64 ? SetInt - directly adds an integer to the list of values - -func (i *IntSlice) String() string - String returns a readable representation of this value (for usage defaults) - -func (i *IntSlice) Value() []int - Value returns the slice of ints set by this flag - -func (i *IntSlice) WithSeparatorSpec(spec separatorSpec) - -type IntSliceFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value *IntSlice - Destination *IntSlice - - Aliases []string - EnvVars []string - - Action func(*Context, []int) error - // Has unexported fields. -} - IntSliceFlag is a flag with type *IntSlice - -func (f *IntSliceFlag) Apply(set *flag.FlagSet) error - Apply populates the flag given the flag set and environment - -func (f *IntSliceFlag) Get(ctx *Context) []int - Get returns the flag’s value in the given Context. - -func (f *IntSliceFlag) GetCategory() string - GetCategory returns the category for the flag - -func (f *IntSliceFlag) GetDefaultText() string - GetDefaultText returns the default text for this flag - -func (f *IntSliceFlag) GetDestination() []int - -func (f *IntSliceFlag) GetEnvVars() []string - GetEnvVars returns the env vars for this flag - -func (f *IntSliceFlag) GetUsage() string - GetUsage returns the usage string for the flag - -func (f *IntSliceFlag) GetValue() string - GetValue returns the flags value as string representation and an empty - string if the flag takes no value at all. - -func (f *IntSliceFlag) IsRequired() bool - IsRequired returns whether or not the flag is required - -func (f *IntSliceFlag) IsSet() bool - IsSet returns whether or not the flag has been set through env or file - -func (f *IntSliceFlag) IsSliceFlag() bool - IsSliceFlag implements DocGenerationSliceFlag. - -func (f *IntSliceFlag) IsVisible() bool - IsVisible returns true if the flag is not hidden, otherwise false - -func (f *IntSliceFlag) Names() []string - Names returns the names of the flag - -func (f *IntSliceFlag) RunAction(c *Context) error - RunAction executes flag action if set - -func (f *IntSliceFlag) SetDestination(slice []int) - -func (f *IntSliceFlag) SetValue(slice []int) - -func (f *IntSliceFlag) String() string - String returns a readable representation of this value (for usage defaults) - -func (f *IntSliceFlag) TakesValue() bool - TakesValue returns true of the flag takes a value, otherwise false - -func (f *IntSliceFlag) WithSeparatorSpec(spec separatorSpec) - -type InvalidFlagAccessFunc func(*Context, string) - InvalidFlagAccessFunc is executed when an invalid flag is accessed from the - context. - -type MultiError interface { - error - Errors() []error -} - MultiError is an error that wraps multiple errors. - -type MultiFloat64Flag = SliceFlag[*Float64SliceFlag, []float64, float64] - MultiFloat64Flag extends Float64SliceFlag with support for using slices - directly, as Value and/or Destination. See also SliceFlag. - -type MultiInt64Flag = SliceFlag[*Int64SliceFlag, []int64, int64] - MultiInt64Flag extends Int64SliceFlag with support for using slices - directly, as Value and/or Destination. See also SliceFlag. - -type MultiIntFlag = SliceFlag[*IntSliceFlag, []int, int] - MultiIntFlag extends IntSliceFlag with support for using slices directly, - as Value and/or Destination. See also SliceFlag. - -type MultiStringFlag = SliceFlag[*StringSliceFlag, []string, string] - MultiStringFlag extends StringSliceFlag with support for using slices - directly, as Value and/or Destination. See also SliceFlag. - -type OnUsageErrorFunc func(cCtx *Context, err error, isSubcommand bool) error - OnUsageErrorFunc is executed if a usage error occurs. This is useful for - displaying customized usage error messages. This function is able to replace - the original error messages. If this function is not set, the "Incorrect - usage" is displayed and the execution is interrupted. - -type Path = string - -type PathFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value Path - Destination *Path - - Aliases []string - EnvVars []string - - TakesFile bool - - Action func(*Context, Path) error - // Has unexported fields. -} - PathFlag is a flag with type Path - -func (f *PathFlag) Apply(set *flag.FlagSet) error - Apply populates the flag given the flag set and environment - -func (f *PathFlag) Get(ctx *Context) string - Get returns the flag’s value in the given Context. - -func (f *PathFlag) GetCategory() string - GetCategory returns the category for the flag - -func (f *PathFlag) GetDefaultText() string - GetDefaultText returns the default text for this flag - -func (f *PathFlag) GetEnvVars() []string - GetEnvVars returns the env vars for this flag - -func (f *PathFlag) GetUsage() string - GetUsage returns the usage string for the flag - -func (f *PathFlag) GetValue() string - GetValue returns the flags value as string representation and an empty - string if the flag takes no value at all. - -func (f *PathFlag) IsRequired() bool - IsRequired returns whether or not the flag is required - -func (f *PathFlag) IsSet() bool - IsSet returns whether or not the flag has been set through env or file - -func (f *PathFlag) IsVisible() bool - IsVisible returns true if the flag is not hidden, otherwise false - -func (f *PathFlag) Names() []string - Names returns the names of the flag - -func (f *PathFlag) RunAction(c *Context) error - RunAction executes flag action if set - -func (f *PathFlag) String() string - String returns a readable representation of this value (for usage defaults) - -func (f *PathFlag) TakesValue() bool - TakesValue returns true of the flag takes a value, otherwise false - -type RequiredFlag interface { - Flag - - IsRequired() bool -} - RequiredFlag is an interface that allows us to mark flags as required - it allows flags required flags to be backwards compatible with the Flag - interface - -type Serializer interface { - Serialize() string -} - Serializer is used to circumvent the limitations of flag.FlagSet.Set - -type SliceFlag[T SliceFlagTarget[E], S ~[]E, E any] struct { - Target T - Value S - Destination *S -} - SliceFlag extends implementations like StringSliceFlag and IntSliceFlag - with support for using slices directly, as Value and/or Destination. - See also SliceFlagTarget, MultiStringFlag, MultiFloat64Flag, MultiInt64Flag, - MultiIntFlag. - -func (x *SliceFlag[T, S, E]) Apply(set *flag.FlagSet) error - -func (x *SliceFlag[T, S, E]) GetCategory() string - -func (x *SliceFlag[T, S, E]) GetDefaultText() string - -func (x *SliceFlag[T, S, E]) GetDestination() S - -func (x *SliceFlag[T, S, E]) GetEnvVars() []string - -func (x *SliceFlag[T, S, E]) GetUsage() string - -func (x *SliceFlag[T, S, E]) GetValue() string - -func (x *SliceFlag[T, S, E]) IsRequired() bool - -func (x *SliceFlag[T, S, E]) IsSet() bool - -func (x *SliceFlag[T, S, E]) IsVisible() bool - -func (x *SliceFlag[T, S, E]) Names() []string - -func (x *SliceFlag[T, S, E]) SetDestination(slice S) - -func (x *SliceFlag[T, S, E]) SetValue(slice S) - -func (x *SliceFlag[T, S, E]) String() string - -func (x *SliceFlag[T, S, E]) TakesValue() bool - -type SliceFlagTarget[E any] interface { - Flag - RequiredFlag - DocGenerationFlag - VisibleFlag - CategorizableFlag - - // SetValue should propagate the given slice to the target, ideally as a new value. - // Note that a nil slice should nil/clear any existing value (modelled as ~[]E). - SetValue(slice []E) - // SetDestination should propagate the given slice to the target, ideally as a new value. - // Note that a nil slice should nil/clear any existing value (modelled as ~*[]E). - SetDestination(slice []E) - // GetDestination should return the current value referenced by any destination, or nil if nil/unset. - GetDestination() []E -} - SliceFlagTarget models a target implementation for use with SliceFlag. The - three methods, SetValue, SetDestination, and GetDestination, are necessary - to propagate Value and Destination, where Value is propagated inwards - (initially), and Destination is propagated outwards (on every update). - -type StringFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value string - Destination *string - - Aliases []string - EnvVars []string - - TakesFile bool - - Action func(*Context, string) error - // Has unexported fields. -} - StringFlag is a flag with type string - -func (f *StringFlag) Apply(set *flag.FlagSet) error - Apply populates the flag given the flag set and environment - -func (f *StringFlag) Get(ctx *Context) string - Get returns the flag’s value in the given Context. - -func (f *StringFlag) GetCategory() string - GetCategory returns the category for the flag - -func (f *StringFlag) GetDefaultText() string - GetDefaultText returns the default text for this flag - -func (f *StringFlag) GetEnvVars() []string - GetEnvVars returns the env vars for this flag - -func (f *StringFlag) GetUsage() string - GetUsage returns the usage string for the flag - -func (f *StringFlag) GetValue() string - GetValue returns the flags value as string representation and an empty - string if the flag takes no value at all. - -func (f *StringFlag) IsRequired() bool - IsRequired returns whether or not the flag is required - -func (f *StringFlag) IsSet() bool - IsSet returns whether or not the flag has been set through env or file - -func (f *StringFlag) IsVisible() bool - IsVisible returns true if the flag is not hidden, otherwise false - -func (f *StringFlag) Names() []string - Names returns the names of the flag - -func (f *StringFlag) RunAction(c *Context) error - RunAction executes flag action if set - -func (f *StringFlag) String() string - String returns a readable representation of this value (for usage defaults) - -func (f *StringFlag) TakesValue() bool - TakesValue returns true of the flag takes a value, otherwise false - -type StringSlice struct { - // Has unexported fields. -} - StringSlice wraps a []string to satisfy flag.Value - -func NewStringSlice(defaults ...string) *StringSlice - NewStringSlice creates a *StringSlice with default values - -func (s *StringSlice) Get() interface{} - Get returns the slice of strings set by this flag - -func (s *StringSlice) Serialize() string - Serialize allows StringSlice to fulfill Serializer - -func (s *StringSlice) Set(value string) error - Set appends the string value to the list of values - -func (s *StringSlice) String() string - String returns a readable representation of this value (for usage defaults) - -func (s *StringSlice) Value() []string - Value returns the slice of strings set by this flag - -func (s *StringSlice) WithSeparatorSpec(spec separatorSpec) - -type StringSliceFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value *StringSlice - Destination *StringSlice - - Aliases []string - EnvVars []string - - TakesFile bool - - Action func(*Context, []string) error - - KeepSpace bool - // Has unexported fields. -} - StringSliceFlag is a flag with type *StringSlice - -func (f *StringSliceFlag) Apply(set *flag.FlagSet) error - Apply populates the flag given the flag set and environment - -func (f *StringSliceFlag) Get(ctx *Context) []string - Get returns the flag’s value in the given Context. - -func (f *StringSliceFlag) GetCategory() string - GetCategory returns the category for the flag - -func (f *StringSliceFlag) GetDefaultText() string - GetDefaultText returns the default text for this flag - -func (f *StringSliceFlag) GetDestination() []string - -func (f *StringSliceFlag) GetEnvVars() []string - GetEnvVars returns the env vars for this flag - -func (f *StringSliceFlag) GetUsage() string - GetUsage returns the usage string for the flag - -func (f *StringSliceFlag) GetValue() string - GetValue returns the flags value as string representation and an empty - string if the flag takes no value at all. - -func (f *StringSliceFlag) IsRequired() bool - IsRequired returns whether or not the flag is required - -func (f *StringSliceFlag) IsSet() bool - IsSet returns whether or not the flag has been set through env or file - -func (f *StringSliceFlag) IsSliceFlag() bool - IsSliceFlag implements DocGenerationSliceFlag. - -func (f *StringSliceFlag) IsVisible() bool - IsVisible returns true if the flag is not hidden, otherwise false - -func (f *StringSliceFlag) Names() []string - Names returns the names of the flag - -func (f *StringSliceFlag) RunAction(c *Context) error - RunAction executes flag action if set - -func (f *StringSliceFlag) SetDestination(slice []string) - -func (f *StringSliceFlag) SetValue(slice []string) - -func (f *StringSliceFlag) String() string - String returns a readable representation of this value (for usage defaults) - -func (f *StringSliceFlag) TakesValue() bool - TakesValue returns true of the flag takes a value, otherwise false - -func (f *StringSliceFlag) WithSeparatorSpec(spec separatorSpec) - -type SuggestCommandFunc func(commands []*Command, provided string) string - -type SuggestFlagFunc func(flags []Flag, provided string, hideHelp bool) string - -type Timestamp struct { - // Has unexported fields. -} - Timestamp wrap to satisfy golang's flag interface. - -func NewTimestamp(timestamp time.Time) *Timestamp - Timestamp constructor - -func (t *Timestamp) Get() interface{} - Get returns the flag structure - -func (t *Timestamp) Set(value string) error - Parses the string value to timestamp - -func (t *Timestamp) SetLayout(layout string) - Set the timestamp string layout for future parsing - -func (t *Timestamp) SetLocation(loc *time.Location) - Set perceived timezone of the to-be parsed time string - -func (t *Timestamp) SetTimestamp(value time.Time) - Set the timestamp value directly - -func (t *Timestamp) String() string - String returns a readable representation of this value (for usage defaults) - -func (t *Timestamp) Value() *time.Time - Value returns the timestamp value stored in the flag - -type TimestampFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value *Timestamp - Destination *Timestamp - - Aliases []string - EnvVars []string - - Layout string - - Timezone *time.Location - - Action func(*Context, *time.Time) error - // Has unexported fields. -} - TimestampFlag is a flag with type *Timestamp - -func (f *TimestampFlag) Apply(set *flag.FlagSet) error - Apply populates the flag given the flag set and environment - -func (f *TimestampFlag) Get(ctx *Context) *time.Time - Get returns the flag’s value in the given Context. - -func (f *TimestampFlag) GetCategory() string - GetCategory returns the category for the flag - -func (f *TimestampFlag) GetDefaultText() string - GetDefaultText returns the default text for this flag - -func (f *TimestampFlag) GetEnvVars() []string - GetEnvVars returns the env vars for this flag - -func (f *TimestampFlag) GetUsage() string - GetUsage returns the usage string for the flag - -func (f *TimestampFlag) GetValue() string - GetValue returns the flags value as string representation and an empty - string if the flag takes no value at all. - -func (f *TimestampFlag) IsRequired() bool - IsRequired returns whether or not the flag is required - -func (f *TimestampFlag) IsSet() bool - IsSet returns whether or not the flag has been set through env or file - -func (f *TimestampFlag) IsVisible() bool - IsVisible returns true if the flag is not hidden, otherwise false - -func (f *TimestampFlag) Names() []string - Names returns the names of the flag - -func (f *TimestampFlag) RunAction(c *Context) error - RunAction executes flag action if set - -func (f *TimestampFlag) String() string - String returns a readable representation of this value (for usage defaults) - -func (f *TimestampFlag) TakesValue() bool - TakesValue returns true of the flag takes a value, otherwise false - -type Uint64Flag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value uint64 - Destination *uint64 - - Aliases []string - EnvVars []string - - Base int - - Action func(*Context, uint64) error - // Has unexported fields. -} - Uint64Flag is a flag with type uint64 - -func (f *Uint64Flag) Apply(set *flag.FlagSet) error - Apply populates the flag given the flag set and environment - -func (f *Uint64Flag) Get(ctx *Context) uint64 - Get returns the flag’s value in the given Context. - -func (f *Uint64Flag) GetCategory() string - GetCategory returns the category for the flag - -func (f *Uint64Flag) GetDefaultText() string - GetDefaultText returns the default text for this flag - -func (f *Uint64Flag) GetEnvVars() []string - GetEnvVars returns the env vars for this flag - -func (f *Uint64Flag) GetUsage() string - GetUsage returns the usage string for the flag - -func (f *Uint64Flag) GetValue() string - GetValue returns the flags value as string representation and an empty - string if the flag takes no value at all. - -func (f *Uint64Flag) IsRequired() bool - IsRequired returns whether or not the flag is required - -func (f *Uint64Flag) IsSet() bool - IsSet returns whether or not the flag has been set through env or file - -func (f *Uint64Flag) IsVisible() bool - IsVisible returns true if the flag is not hidden, otherwise false - -func (f *Uint64Flag) Names() []string - Names returns the names of the flag - -func (f *Uint64Flag) RunAction(c *Context) error - RunAction executes flag action if set - -func (f *Uint64Flag) String() string - String returns a readable representation of this value (for usage defaults) - -func (f *Uint64Flag) TakesValue() bool - TakesValue returns true of the flag takes a value, otherwise false - -type Uint64Slice struct { - // Has unexported fields. -} - Uint64Slice wraps []int64 to satisfy flag.Value - -func NewUint64Slice(defaults ...uint64) *Uint64Slice - NewUint64Slice makes an *Uint64Slice with default values - -func (i *Uint64Slice) Get() interface{} - Get returns the slice of ints set by this flag - -func (i *Uint64Slice) Serialize() string - Serialize allows Uint64Slice to fulfill Serializer - -func (i *Uint64Slice) Set(value string) error - Set parses the value into an integer and appends it to the list of values - -func (i *Uint64Slice) String() string - String returns a readable representation of this value (for usage defaults) - -func (i *Uint64Slice) Value() []uint64 - Value returns the slice of ints set by this flag - -func (i *Uint64Slice) WithSeparatorSpec(spec separatorSpec) - -type Uint64SliceFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value *Uint64Slice - Destination *Uint64Slice - - Aliases []string - EnvVars []string - - Action func(*Context, []uint64) error - // Has unexported fields. -} - Uint64SliceFlag is a flag with type *Uint64Slice - -func (f *Uint64SliceFlag) Apply(set *flag.FlagSet) error - Apply populates the flag given the flag set and environment - -func (f *Uint64SliceFlag) Get(ctx *Context) []uint64 - Get returns the flag’s value in the given Context. - -func (f *Uint64SliceFlag) GetCategory() string - GetCategory returns the category for the flag - -func (f *Uint64SliceFlag) GetDefaultText() string - GetDefaultText returns the default text for this flag - -func (f *Uint64SliceFlag) GetEnvVars() []string - GetEnvVars returns the env vars for this flag - -func (f *Uint64SliceFlag) GetUsage() string - GetUsage returns the usage string for the flag - -func (f *Uint64SliceFlag) GetValue() string - GetValue returns the flags value as string representation and an empty - string if the flag takes no value at all. - -func (f *Uint64SliceFlag) IsRequired() bool - IsRequired returns whether or not the flag is required - -func (f *Uint64SliceFlag) IsSet() bool - IsSet returns whether or not the flag has been set through env or file - -func (f *Uint64SliceFlag) IsSliceFlag() bool - IsSliceFlag implements DocGenerationSliceFlag. - -func (f *Uint64SliceFlag) IsVisible() bool - IsVisible returns true if the flag is not hidden, otherwise false - -func (f *Uint64SliceFlag) Names() []string - Names returns the names of the flag - -func (f *Uint64SliceFlag) RunAction(c *Context) error - RunAction executes flag action if set - -func (f *Uint64SliceFlag) String() string - String returns a readable representation of this value (for usage defaults) - -func (f *Uint64SliceFlag) TakesValue() bool - TakesValue returns true of the flag takes a value, otherwise false - -func (f *Uint64SliceFlag) WithSeparatorSpec(spec separatorSpec) - -type UintFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value uint - Destination *uint - - Aliases []string - EnvVars []string - - Base int - - Action func(*Context, uint) error - // Has unexported fields. -} - UintFlag is a flag with type uint - -func (f *UintFlag) Apply(set *flag.FlagSet) error - Apply populates the flag given the flag set and environment - -func (f *UintFlag) Get(ctx *Context) uint - Get returns the flag’s value in the given Context. - -func (f *UintFlag) GetCategory() string - GetCategory returns the category for the flag - -func (f *UintFlag) GetDefaultText() string - GetDefaultText returns the default text for this flag - -func (f *UintFlag) GetEnvVars() []string - GetEnvVars returns the env vars for this flag - -func (f *UintFlag) GetUsage() string - GetUsage returns the usage string for the flag - -func (f *UintFlag) GetValue() string - GetValue returns the flags value as string representation and an empty - string if the flag takes no value at all. - -func (f *UintFlag) IsRequired() bool - IsRequired returns whether or not the flag is required - -func (f *UintFlag) IsSet() bool - IsSet returns whether or not the flag has been set through env or file - -func (f *UintFlag) IsVisible() bool - IsVisible returns true if the flag is not hidden, otherwise false - -func (f *UintFlag) Names() []string - Names returns the names of the flag - -func (f *UintFlag) RunAction(c *Context) error - RunAction executes flag action if set - -func (f *UintFlag) String() string - String returns a readable representation of this value (for usage defaults) - -func (f *UintFlag) TakesValue() bool - TakesValue returns true of the flag takes a value, otherwise false - -type UintSlice struct { - // Has unexported fields. -} - UintSlice wraps []int to satisfy flag.Value - -func NewUintSlice(defaults ...uint) *UintSlice - NewUintSlice makes an *UintSlice with default values - -func (i *UintSlice) Get() interface{} - Get returns the slice of ints set by this flag - -func (i *UintSlice) Serialize() string - Serialize allows UintSlice to fulfill Serializer - -func (i *UintSlice) Set(value string) error - Set parses the value into an integer and appends it to the list of values - -func (i *UintSlice) SetUint(value uint) - TODO: Consistently have specific Set function for Int64 and Float64 ? SetInt - directly adds an integer to the list of values - -func (i *UintSlice) String() string - String returns a readable representation of this value (for usage defaults) - -func (i *UintSlice) Value() []uint - Value returns the slice of ints set by this flag - -func (i *UintSlice) WithSeparatorSpec(spec separatorSpec) - -type UintSliceFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value *UintSlice - Destination *UintSlice - - Aliases []string - EnvVars []string - - Action func(*Context, []uint) error - // Has unexported fields. -} - UintSliceFlag is a flag with type *UintSlice - -func (f *UintSliceFlag) Apply(set *flag.FlagSet) error - Apply populates the flag given the flag set and environment - -func (f *UintSliceFlag) Get(ctx *Context) []uint - Get returns the flag’s value in the given Context. - -func (f *UintSliceFlag) GetCategory() string - GetCategory returns the category for the flag - -func (f *UintSliceFlag) GetDefaultText() string - GetDefaultText returns the default text for this flag - -func (f *UintSliceFlag) GetEnvVars() []string - GetEnvVars returns the env vars for this flag - -func (f *UintSliceFlag) GetUsage() string - GetUsage returns the usage string for the flag - -func (f *UintSliceFlag) GetValue() string - GetValue returns the flags value as string representation and an empty - string if the flag takes no value at all. - -func (f *UintSliceFlag) IsRequired() bool - IsRequired returns whether or not the flag is required - -func (f *UintSliceFlag) IsSet() bool - IsSet returns whether or not the flag has been set through env or file - -func (f *UintSliceFlag) IsSliceFlag() bool - IsSliceFlag implements DocGenerationSliceFlag. - -func (f *UintSliceFlag) IsVisible() bool - IsVisible returns true if the flag is not hidden, otherwise false - -func (f *UintSliceFlag) Names() []string - Names returns the names of the flag - -func (f *UintSliceFlag) RunAction(c *Context) error - RunAction executes flag action if set - -func (f *UintSliceFlag) String() string - String returns a readable representation of this value (for usage defaults) - -func (f *UintSliceFlag) TakesValue() bool - TakesValue returns true of the flag takes a value, otherwise false - -func (f *UintSliceFlag) WithSeparatorSpec(spec separatorSpec) - -type VisibleFlag interface { - Flag - - // IsVisible returns true if the flag is not hidden, otherwise false - IsVisible() bool -} - VisibleFlag is an interface that allows to check if a flag is visible - -type VisibleFlagCategory interface { - // Name returns the category name string - Name() string - // Flags returns a slice of VisibleFlag sorted by name - Flags() []VisibleFlag -} - VisibleFlagCategory is a category containing flags. - -package altsrc // import "github.com/urfave/cli/v2/altsrc" - - -FUNCTIONS - -func ApplyInputSourceValues(cCtx *cli.Context, inputSourceContext InputSourceContext, flags []cli.Flag) error - ApplyInputSourceValues iterates over all provided flags and executes - ApplyInputSourceValue on flags implementing the FlagInputSourceExtension - interface to initialize these flags to an alternate input source. - -func InitInputSource(flags []cli.Flag, createInputSource func() (InputSourceContext, error)) cli.BeforeFunc - InitInputSource is used to to setup an InputSourceContext on a cli.Command - Before method. It will create a new input source based on the func provided. - If there is no error it will then apply the new input source to any flags - that are supported by the input source - -func InitInputSourceWithContext(flags []cli.Flag, createInputSource func(cCtx *cli.Context) (InputSourceContext, error)) cli.BeforeFunc - InitInputSourceWithContext is used to to setup an InputSourceContext on - a cli.Command Before method. It will create a new input source based on - the func provided with potentially using existing cli.Context values to - initialize itself. If there is no error it will then apply the new input - source to any flags that are supported by the input source - -func NewJSONSourceFromFlagFunc(flag string) func(c *cli.Context) (InputSourceContext, error) - NewJSONSourceFromFlagFunc returns a func that takes a cli.Context and - returns an InputSourceContext suitable for retrieving config variables from - a file containing JSON data with the file name defined by the given flag. - -func NewTomlSourceFromFlagFunc(flagFileName string) func(cCtx *cli.Context) (InputSourceContext, error) - NewTomlSourceFromFlagFunc creates a new TOML InputSourceContext from a - provided flag name and source context. - -func NewYamlSourceFromFlagFunc(flagFileName string) func(cCtx *cli.Context) (InputSourceContext, error) - NewYamlSourceFromFlagFunc creates a new Yaml InputSourceContext from a - provided flag name and source context. - - -TYPES - -type BoolFlag struct { - *cli.BoolFlag - // Has unexported fields. -} - BoolFlag is the flag type that wraps cli.BoolFlag to allow for other values - to be specified - -func NewBoolFlag(fl *cli.BoolFlag) *BoolFlag - NewBoolFlag creates a new BoolFlag - -func (f *BoolFlag) Apply(set *flag.FlagSet) error - Apply saves the flagSet for later usage calls, then calls the wrapped - BoolFlag.Apply - -func (f *BoolFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error - ApplyInputSourceValue applies a Bool value to the flagSet if required - -type DurationFlag struct { - *cli.DurationFlag - // Has unexported fields. -} - DurationFlag is the flag type that wraps cli.DurationFlag to allow for other - values to be specified - -func NewDurationFlag(fl *cli.DurationFlag) *DurationFlag - NewDurationFlag creates a new DurationFlag - -func (f *DurationFlag) Apply(set *flag.FlagSet) error - Apply saves the flagSet for later usage calls, then calls the wrapped - DurationFlag.Apply - -func (f *DurationFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error - ApplyInputSourceValue applies a Duration value to the flagSet if required - -type FlagInputSourceExtension interface { - cli.Flag - ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error -} - FlagInputSourceExtension is an extension interface of cli.Flag that allows a - value to be set on the existing parsed flags. - -type Float64Flag struct { - *cli.Float64Flag - // Has unexported fields. -} - Float64Flag is the flag type that wraps cli.Float64Flag to allow for other - values to be specified - -func NewFloat64Flag(fl *cli.Float64Flag) *Float64Flag - NewFloat64Flag creates a new Float64Flag - -func (f *Float64Flag) Apply(set *flag.FlagSet) error - Apply saves the flagSet for later usage calls, then calls the wrapped - Float64Flag.Apply - -func (f *Float64Flag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error - ApplyInputSourceValue applies a Float64 value to the flagSet if required - -type Float64SliceFlag struct { - *cli.Float64SliceFlag - // Has unexported fields. -} - Float64SliceFlag is the flag type that wraps cli.Float64SliceFlag to allow - for other values to be specified - -func NewFloat64SliceFlag(fl *cli.Float64SliceFlag) *Float64SliceFlag - NewFloat64SliceFlag creates a new Float64SliceFlag - -func (f *Float64SliceFlag) Apply(set *flag.FlagSet) error - Apply saves the flagSet for later usage calls, then calls the wrapped - Float64SliceFlag.Apply - -func (f *Float64SliceFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error - ApplyInputSourceValue applies a Float64Slice value if required - -type GenericFlag struct { - *cli.GenericFlag - // Has unexported fields. -} - GenericFlag is the flag type that wraps cli.GenericFlag to allow for other - values to be specified - -func NewGenericFlag(fl *cli.GenericFlag) *GenericFlag - NewGenericFlag creates a new GenericFlag - -func (f *GenericFlag) Apply(set *flag.FlagSet) error - Apply saves the flagSet for later usage calls, then calls the wrapped - GenericFlag.Apply - -func (f *GenericFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error - ApplyInputSourceValue applies a generic value to the flagSet if required - -type InputSourceContext interface { - Source() string - - Int(name string) (int, error) - Int64(name string) (int64, error) - Uint(name string) (uint, error) - Uint64(name string) (uint64, error) - Duration(name string) (time.Duration, error) - Float64(name string) (float64, error) - String(name string) (string, error) - StringSlice(name string) ([]string, error) - IntSlice(name string) ([]int, error) - Int64Slice(name string) ([]int64, error) - Float64Slice(name string) ([]float64, error) - Generic(name string) (cli.Generic, error) - Bool(name string) (bool, error) - - // Has unexported methods. -} - InputSourceContext is an interface used to allow other input sources to be - implemented as needed. - - Source returns an identifier for the input source. In case of file source it - should return path to the file. - -func NewJSONSource(data []byte) (InputSourceContext, error) - NewJSONSource returns an InputSourceContext suitable for retrieving config - variables from raw JSON data. - -func NewJSONSourceFromFile(f string) (InputSourceContext, error) - NewJSONSourceFromFile returns an InputSourceContext suitable for retrieving - config variables from a file (or url) containing JSON data. - -func NewJSONSourceFromReader(r io.Reader) (InputSourceContext, error) - NewJSONSourceFromReader returns an InputSourceContext suitable for - retrieving config variables from an io.Reader that returns JSON data. - -func NewTomlSourceFromFile(file string) (InputSourceContext, error) - NewTomlSourceFromFile creates a new TOML InputSourceContext from a filepath. - -func NewYamlSourceFromFile(file string) (InputSourceContext, error) - NewYamlSourceFromFile creates a new Yaml InputSourceContext from a filepath. - -type Int64Flag struct { - *cli.Int64Flag - // Has unexported fields. -} - Int64Flag is the flag type that wraps cli.Int64Flag to allow for other - values to be specified - -func NewInt64Flag(fl *cli.Int64Flag) *Int64Flag - NewInt64Flag creates a new Int64Flag - -func (f *Int64Flag) Apply(set *flag.FlagSet) error - Apply saves the flagSet for later usage calls, then calls the wrapped - Int64Flag.Apply - -func (f *Int64Flag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error - -type Int64SliceFlag struct { - *cli.Int64SliceFlag - // Has unexported fields. -} - Int64SliceFlag is the flag type that wraps cli.Int64SliceFlag to allow for - other values to be specified - -func NewInt64SliceFlag(fl *cli.Int64SliceFlag) *Int64SliceFlag - NewInt64SliceFlag creates a new Int64SliceFlag - -func (f *Int64SliceFlag) Apply(set *flag.FlagSet) error - Apply saves the flagSet for later usage calls, then calls the wrapped - Int64SliceFlag.Apply - -func (f *Int64SliceFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error - ApplyInputSourceValue applies a Int64Slice value if required - -type IntFlag struct { - *cli.IntFlag - // Has unexported fields. -} - IntFlag is the flag type that wraps cli.IntFlag to allow for other values to - be specified - -func NewIntFlag(fl *cli.IntFlag) *IntFlag - NewIntFlag creates a new IntFlag - -func (f *IntFlag) Apply(set *flag.FlagSet) error - Apply saves the flagSet for later usage calls, then calls the wrapped - IntFlag.Apply - -func (f *IntFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error - ApplyInputSourceValue applies a int value to the flagSet if required - -type IntSliceFlag struct { - *cli.IntSliceFlag - // Has unexported fields. -} - IntSliceFlag is the flag type that wraps cli.IntSliceFlag to allow for other - values to be specified - -func NewIntSliceFlag(fl *cli.IntSliceFlag) *IntSliceFlag - NewIntSliceFlag creates a new IntSliceFlag - -func (f *IntSliceFlag) Apply(set *flag.FlagSet) error - Apply saves the flagSet for later usage calls, then calls the wrapped - IntSliceFlag.Apply - -func (f *IntSliceFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error - ApplyInputSourceValue applies a IntSlice value if required - -type MapInputSource struct { - // Has unexported fields. -} - MapInputSource implements InputSourceContext to return data from the map - that is loaded. - -func NewMapInputSource(file string, valueMap map[interface{}]interface{}) *MapInputSource - NewMapInputSource creates a new MapInputSource for implementing custom input - sources. - -func (fsm *MapInputSource) Bool(name string) (bool, error) - Bool returns an bool from the map otherwise returns false - -func (fsm *MapInputSource) Duration(name string) (time.Duration, error) - Duration returns a duration from the map if it exists otherwise returns 0 - -func (fsm *MapInputSource) Float64(name string) (float64, error) - Float64 returns an float64 from the map if it exists otherwise returns 0 - -func (fsm *MapInputSource) Float64Slice(name string) ([]float64, error) - Float64Slice returns an []float64 from the map if it exists otherwise - returns nil - -func (fsm *MapInputSource) Generic(name string) (cli.Generic, error) - Generic returns an cli.Generic from the map if it exists otherwise returns - nil - -func (fsm *MapInputSource) Int(name string) (int, error) - Int returns an int from the map if it exists otherwise returns 0 - -func (fsm *MapInputSource) Int64(name string) (int64, error) - Int64 returns an int64 from the map if it exists otherwise returns 0 - -func (fsm *MapInputSource) Int64Slice(name string) ([]int64, error) - Int64Slice returns an []int64 from the map if it exists otherwise returns - nil - -func (fsm *MapInputSource) IntSlice(name string) ([]int, error) - IntSlice returns an []int from the map if it exists otherwise returns nil - -func (fsm *MapInputSource) Source() string - Source returns the path of the source file - -func (fsm *MapInputSource) String(name string) (string, error) - String returns a string from the map if it exists otherwise returns an empty - string - -func (fsm *MapInputSource) StringSlice(name string) ([]string, error) - StringSlice returns an []string from the map if it exists otherwise returns - nil - -func (fsm *MapInputSource) Uint(name string) (uint, error) - Int64 returns an int64 from the map if it exists otherwise returns 0 - -func (fsm *MapInputSource) Uint64(name string) (uint64, error) - UInt64 returns an uint64 from the map if it exists otherwise returns 0 - -type PathFlag struct { - *cli.PathFlag - // Has unexported fields. -} - PathFlag is the flag type that wraps cli.PathFlag to allow for other values - to be specified - -func NewPathFlag(fl *cli.PathFlag) *PathFlag - NewPathFlag creates a new PathFlag - -func (f *PathFlag) Apply(set *flag.FlagSet) error - Apply saves the flagSet for later usage calls, then calls the wrapped - PathFlag.Apply - -func (f *PathFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error - ApplyInputSourceValue applies a Path value to the flagSet if required - -type StringFlag struct { - *cli.StringFlag - // Has unexported fields. -} - StringFlag is the flag type that wraps cli.StringFlag to allow for other - values to be specified - -func NewStringFlag(fl *cli.StringFlag) *StringFlag - NewStringFlag creates a new StringFlag - -func (f *StringFlag) Apply(set *flag.FlagSet) error - Apply saves the flagSet for later usage calls, then calls the wrapped - StringFlag.Apply - -func (f *StringFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error - ApplyInputSourceValue applies a String value to the flagSet if required - -type StringSliceFlag struct { - *cli.StringSliceFlag - // Has unexported fields. -} - StringSliceFlag is the flag type that wraps cli.StringSliceFlag to allow for - other values to be specified - -func NewStringSliceFlag(fl *cli.StringSliceFlag) *StringSliceFlag - NewStringSliceFlag creates a new StringSliceFlag - -func (f *StringSliceFlag) Apply(set *flag.FlagSet) error - Apply saves the flagSet for later usage calls, then calls the wrapped - StringSliceFlag.Apply - -func (f *StringSliceFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error - ApplyInputSourceValue applies a StringSlice value to the flagSet if required - -type Uint64Flag struct { - *cli.Uint64Flag - // Has unexported fields. -} - Uint64Flag is the flag type that wraps cli.Uint64Flag to allow for other - values to be specified - -func NewUint64Flag(fl *cli.Uint64Flag) *Uint64Flag - NewUint64Flag creates a new Uint64Flag - -func (f *Uint64Flag) Apply(set *flag.FlagSet) error - Apply saves the flagSet for later usage calls, then calls the wrapped - Uint64Flag.Apply - -func (f *Uint64Flag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error - -type UintFlag struct { - *cli.UintFlag - // Has unexported fields. -} - UintFlag is the flag type that wraps cli.UintFlag to allow for other values - to be specified - -func NewUintFlag(fl *cli.UintFlag) *UintFlag - NewUintFlag creates a new UintFlag - -func (f *UintFlag) Apply(set *flag.FlagSet) error - Apply saves the flagSet for later usage calls, then calls the wrapped - UintFlag.Apply - -func (f *UintFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error - diff --git a/vendor/github.com/urfave/cli/v2/help.go b/vendor/github.com/urfave/cli/v2/help.go deleted file mode 100644 index 640e2904..00000000 --- a/vendor/github.com/urfave/cli/v2/help.go +++ /dev/null @@ -1,564 +0,0 @@ -package cli - -import ( - "fmt" - "io" - "os" - "strings" - "text/tabwriter" - "text/template" - "unicode/utf8" -) - -const ( - helpName = "help" - helpAlias = "h" -) - -// this instance is to avoid recursion in the ShowCommandHelp which can -// add a help command again -var helpCommandDontUse = &Command{ - Name: helpName, - Aliases: []string{helpAlias}, - Usage: "Shows a list of commands or help for one command", - ArgsUsage: "[command]", -} - -var helpCommand = &Command{ - Name: helpName, - Aliases: []string{helpAlias}, - Usage: "Shows a list of commands or help for one command", - ArgsUsage: "[command]", - Action: func(cCtx *Context) error { - args := cCtx.Args() - argsPresent := args.First() != "" - firstArg := args.First() - - // This action can be triggered by a "default" action of a command - // or via cmd.Run when cmd == helpCmd. So we have following possibilities - // - // 1 $ app - // 2 $ app help - // 3 $ app foo - // 4 $ app help foo - // 5 $ app foo help - // 6 $ app foo -h (with no other sub-commands nor flags defined) - - // Case 4. when executing a help command set the context to parent - // to allow resolution of subsequent args. This will transform - // $ app help foo - // to - // $ app foo - // which will then be handled as case 3 - if cCtx.Command.Name == helpName || cCtx.Command.Name == helpAlias { - cCtx = cCtx.parentContext - } - - // Case 4. $ app hello foo - // foo is the command for which help needs to be shown - if argsPresent { - return ShowCommandHelp(cCtx, firstArg) - } - - // Case 1 & 2 - // Special case when running help on main app itself as opposed to individual - // commands/subcommands - if cCtx.parentContext.App == nil { - _ = ShowAppHelp(cCtx) - return nil - } - - // Case 3, 5 - if (len(cCtx.Command.Subcommands) == 1 && !cCtx.Command.HideHelp && !cCtx.Command.HideHelpCommand) || - (len(cCtx.Command.Subcommands) == 0 && cCtx.Command.HideHelp) { - templ := cCtx.Command.CustomHelpTemplate - if templ == "" { - templ = CommandHelpTemplate - } - HelpPrinter(cCtx.App.Writer, templ, cCtx.Command) - return nil - } - - // Case 6, handling incorporated in the callee itself - return ShowSubcommandHelp(cCtx) - }, -} - -// Prints help for the App or Command -type helpPrinter func(w io.Writer, templ string, data interface{}) - -// Prints help for the App or Command with custom template function. -type helpPrinterCustom func(w io.Writer, templ string, data interface{}, customFunc map[string]interface{}) - -// HelpPrinter is a function that writes the help output. If not set explicitly, -// this calls HelpPrinterCustom using only the default template functions. -// -// If custom logic for printing help is required, this function can be -// overridden. If the ExtraInfo field is defined on an App, this function -// should not be modified, as HelpPrinterCustom will be used directly in order -// to capture the extra information. -var HelpPrinter helpPrinter = printHelp - -// HelpPrinterCustom is a function that writes the help output. It is used as -// the default implementation of HelpPrinter, and may be called directly if -// the ExtraInfo field is set on an App. -// -// In the default implementation, if the customFuncs argument contains a -// "wrapAt" key, which is a function which takes no arguments and returns -// an int, this int value will be used to produce a "wrap" function used -// by the default template to wrap long lines. -var HelpPrinterCustom helpPrinterCustom = printHelpCustom - -// VersionPrinter prints the version for the App -var VersionPrinter = printVersion - -// ShowAppHelpAndExit - Prints the list of subcommands for the app and exits with exit code. -func ShowAppHelpAndExit(c *Context, exitCode int) { - _ = ShowAppHelp(c) - os.Exit(exitCode) -} - -// ShowAppHelp is an action that displays the help. -func ShowAppHelp(cCtx *Context) error { - tpl := cCtx.App.CustomAppHelpTemplate - if tpl == "" { - tpl = AppHelpTemplate - } - - if cCtx.App.ExtraInfo == nil { - HelpPrinter(cCtx.App.Writer, tpl, cCtx.App) - return nil - } - - customAppData := func() map[string]interface{} { - return map[string]interface{}{ - "ExtraInfo": cCtx.App.ExtraInfo, - } - } - HelpPrinterCustom(cCtx.App.Writer, tpl, cCtx.App, customAppData()) - - return nil -} - -// DefaultAppComplete prints the list of subcommands as the default app completion method -func DefaultAppComplete(cCtx *Context) { - DefaultCompleteWithFlags(nil)(cCtx) -} - -func printCommandSuggestions(commands []*Command, writer io.Writer) { - for _, command := range commands { - if command.Hidden { - continue - } - if strings.HasSuffix(os.Getenv("SHELL"), "zsh") { - for _, name := range command.Names() { - _, _ = fmt.Fprintf(writer, "%s:%s\n", name, command.Usage) - } - } else { - for _, name := range command.Names() { - _, _ = fmt.Fprintf(writer, "%s\n", name) - } - } - } -} - -func cliArgContains(flagName string) bool { - for _, name := range strings.Split(flagName, ",") { - name = strings.TrimSpace(name) - count := utf8.RuneCountInString(name) - if count > 2 { - count = 2 - } - flag := fmt.Sprintf("%s%s", strings.Repeat("-", count), name) - for _, a := range os.Args { - if a == flag { - return true - } - } - } - return false -} - -func printFlagSuggestions(lastArg string, flags []Flag, writer io.Writer) { - cur := strings.TrimPrefix(lastArg, "-") - cur = strings.TrimPrefix(cur, "-") - for _, flag := range flags { - if bflag, ok := flag.(*BoolFlag); ok && bflag.Hidden { - continue - } - for _, name := range flag.Names() { - name = strings.TrimSpace(name) - // this will get total count utf8 letters in flag name - count := utf8.RuneCountInString(name) - if count > 2 { - count = 2 // reuse this count to generate single - or -- in flag completion - } - // if flag name has more than one utf8 letter and last argument in cli has -- prefix then - // skip flag completion for short flags example -v or -x - if strings.HasPrefix(lastArg, "--") && count == 1 { - continue - } - // match if last argument matches this flag and it is not repeated - if strings.HasPrefix(name, cur) && cur != name && !cliArgContains(name) { - flagCompletion := fmt.Sprintf("%s%s", strings.Repeat("-", count), name) - _, _ = fmt.Fprintln(writer, flagCompletion) - } - } - } -} - -func DefaultCompleteWithFlags(cmd *Command) func(cCtx *Context) { - return func(cCtx *Context) { - var lastArg string - - // TODO: This shouldnt depend on os.Args rather it should - // depend on root arguments passed to App - if len(os.Args) > 2 { - lastArg = os.Args[len(os.Args)-2] - } - - if lastArg != "" { - if strings.HasPrefix(lastArg, "-") { - if cmd != nil { - printFlagSuggestions(lastArg, cmd.Flags, cCtx.App.Writer) - - return - } - - printFlagSuggestions(lastArg, cCtx.App.Flags, cCtx.App.Writer) - - return - } - } - - if cmd != nil { - printCommandSuggestions(cmd.Subcommands, cCtx.App.Writer) - return - } - - printCommandSuggestions(cCtx.Command.Subcommands, cCtx.App.Writer) - } -} - -// ShowCommandHelpAndExit - exits with code after showing help -func ShowCommandHelpAndExit(c *Context, command string, code int) { - _ = ShowCommandHelp(c, command) - os.Exit(code) -} - -// ShowCommandHelp prints help for the given command -func ShowCommandHelp(ctx *Context, command string) error { - - commands := ctx.App.Commands - if ctx.Command.Subcommands != nil { - commands = ctx.Command.Subcommands - } - for _, c := range commands { - if c.HasName(command) { - if !ctx.App.HideHelpCommand && !c.HasName(helpName) && len(c.Subcommands) != 0 && c.Command(helpName) == nil { - c.Subcommands = append(c.Subcommands, helpCommandDontUse) - } - if !ctx.App.HideHelp && HelpFlag != nil { - c.appendFlag(HelpFlag) - } - templ := c.CustomHelpTemplate - if templ == "" { - if len(c.Subcommands) == 0 { - templ = CommandHelpTemplate - } else { - templ = SubcommandHelpTemplate - } - } - - HelpPrinter(ctx.App.Writer, templ, c) - - return nil - } - } - - if ctx.App.CommandNotFound == nil { - errMsg := fmt.Sprintf("No help topic for '%v'", command) - if ctx.App.Suggest && SuggestCommand != nil { - if suggestion := SuggestCommand(ctx.Command.Subcommands, command); suggestion != "" { - errMsg += ". " + suggestion - } - } - return Exit(errMsg, 3) - } - - ctx.App.CommandNotFound(ctx, command) - return nil -} - -// ShowSubcommandHelpAndExit - Prints help for the given subcommand and exits with exit code. -func ShowSubcommandHelpAndExit(c *Context, exitCode int) { - _ = ShowSubcommandHelp(c) - os.Exit(exitCode) -} - -// ShowSubcommandHelp prints help for the given subcommand -func ShowSubcommandHelp(cCtx *Context) error { - if cCtx == nil { - return nil - } - // use custom template when provided (fixes #1703) - templ := SubcommandHelpTemplate - if cCtx.Command != nil && cCtx.Command.CustomHelpTemplate != "" { - templ = cCtx.Command.CustomHelpTemplate - } - HelpPrinter(cCtx.App.Writer, templ, cCtx.Command) - return nil -} - -// ShowVersion prints the version number of the App -func ShowVersion(cCtx *Context) { - VersionPrinter(cCtx) -} - -func printVersion(cCtx *Context) { - _, _ = fmt.Fprintf(cCtx.App.Writer, "%v version %v\n", cCtx.App.Name, cCtx.App.Version) -} - -// ShowCompletions prints the lists of commands within a given context -func ShowCompletions(cCtx *Context) { - c := cCtx.Command - if c != nil && c.BashComplete != nil { - c.BashComplete(cCtx) - } -} - -// ShowCommandCompletions prints the custom completions for a given command -func ShowCommandCompletions(ctx *Context, command string) { - c := ctx.Command.Command(command) - if c != nil { - if c.BashComplete != nil { - c.BashComplete(ctx) - } else { - DefaultCompleteWithFlags(c)(ctx) - } - } - -} - -// printHelpCustom is the default implementation of HelpPrinterCustom. -// -// The customFuncs map will be combined with a default template.FuncMap to -// allow using arbitrary functions in template rendering. -func printHelpCustom(out io.Writer, templ string, data interface{}, customFuncs map[string]interface{}) { - - const maxLineLength = 10000 - - funcMap := template.FuncMap{ - "join": strings.Join, - "subtract": subtract, - "indent": indent, - "nindent": nindent, - "trim": strings.TrimSpace, - "wrap": func(input string, offset int) string { return wrap(input, offset, maxLineLength) }, - "offset": offset, - "offsetCommands": offsetCommands, - } - - if customFuncs["wrapAt"] != nil { - if wa, ok := customFuncs["wrapAt"]; ok { - if waf, ok := wa.(func() int); ok { - wrapAt := waf() - customFuncs["wrap"] = func(input string, offset int) string { - return wrap(input, offset, wrapAt) - } - } - } - } - - for key, value := range customFuncs { - funcMap[key] = value - } - - w := tabwriter.NewWriter(out, 1, 8, 2, ' ', 0) - t := template.Must(template.New("help").Funcs(funcMap).Parse(templ)) - templates := map[string]string{ - "helpNameTemplate": helpNameTemplate, - "usageTemplate": usageTemplate, - "descriptionTemplate": descriptionTemplate, - "visibleCommandTemplate": visibleCommandTemplate, - "copyrightTemplate": copyrightTemplate, - "versionTemplate": versionTemplate, - "visibleFlagCategoryTemplate": visibleFlagCategoryTemplate, - "visibleFlagTemplate": visibleFlagTemplate, - "visibleGlobalFlagCategoryTemplate": strings.Replace(visibleFlagCategoryTemplate, "OPTIONS", "GLOBAL OPTIONS", -1), - "authorsTemplate": authorsTemplate, - "visibleCommandCategoryTemplate": visibleCommandCategoryTemplate, - } - for name, value := range templates { - if _, err := t.New(name).Parse(value); err != nil { - if os.Getenv("CLI_TEMPLATE_ERROR_DEBUG") != "" { - _, _ = fmt.Fprintf(ErrWriter, "CLI TEMPLATE ERROR: %#v\n", err) - } - } - } - - err := t.Execute(w, data) - if err != nil { - // If the writer is closed, t.Execute will fail, and there's nothing - // we can do to recover. - if os.Getenv("CLI_TEMPLATE_ERROR_DEBUG") != "" { - _, _ = fmt.Fprintf(ErrWriter, "CLI TEMPLATE ERROR: %#v\n", err) - } - return - } - _ = w.Flush() -} - -func printHelp(out io.Writer, templ string, data interface{}) { - HelpPrinterCustom(out, templ, data, nil) -} - -func checkVersion(cCtx *Context) bool { - found := false - for _, name := range VersionFlag.Names() { - if cCtx.Bool(name) { - found = true - } - } - return found -} - -func checkHelp(cCtx *Context) bool { - if HelpFlag == nil { - return false - } - found := false - for _, name := range HelpFlag.Names() { - if cCtx.Bool(name) { - found = true - break - } - } - - return found -} - -func checkShellCompleteFlag(a *App, arguments []string) (bool, []string) { - if !a.EnableBashCompletion { - return false, arguments - } - - pos := len(arguments) - 1 - lastArg := arguments[pos] - - if lastArg != "--generate-bash-completion" { - return false, arguments - } - - return true, arguments[:pos] -} - -func checkCompletions(cCtx *Context) bool { - if !cCtx.shellComplete { - return false - } - - if args := cCtx.Args(); args.Present() { - name := args.First() - if cmd := cCtx.Command.Command(name); cmd != nil { - // let the command handle the completion - return false - } - } - - ShowCompletions(cCtx) - return true -} - -func subtract(a, b int) int { - return a - b -} - -func indent(spaces int, v string) string { - pad := strings.Repeat(" ", spaces) - return pad + strings.Replace(v, "\n", "\n"+pad, -1) -} - -func nindent(spaces int, v string) string { - return "\n" + indent(spaces, v) -} - -func wrap(input string, offset int, wrapAt int) string { - var ss []string - - lines := strings.Split(input, "\n") - - padding := strings.Repeat(" ", offset) - - for i, line := range lines { - if line == "" { - ss = append(ss, line) - } else { - wrapped := wrapLine(line, offset, wrapAt, padding) - if i == 0 { - ss = append(ss, wrapped) - } else { - ss = append(ss, padding+wrapped) - - } - - } - } - - return strings.Join(ss, "\n") -} - -func wrapLine(input string, offset int, wrapAt int, padding string) string { - if wrapAt <= offset || len(input) <= wrapAt-offset { - return input - } - - lineWidth := wrapAt - offset - words := strings.Fields(input) - if len(words) == 0 { - return input - } - - wrapped := words[0] - spaceLeft := lineWidth - len(wrapped) - for _, word := range words[1:] { - if len(word)+1 > spaceLeft { - wrapped += "\n" + padding + word - spaceLeft = lineWidth - len(word) - } else { - wrapped += " " + word - spaceLeft -= 1 + len(word) - } - } - - return wrapped -} - -func offset(input string, fixed int) int { - return len(input) + fixed -} - -// this function tries to find the max width of the names column -// so say we have the following rows for help -// -// foo1, foo2, foo3 some string here -// bar1, b2 some other string here -// -// We want to offset the 2nd row usage by some amount so that everything -// is aligned -// -// foo1, foo2, foo3 some string here -// bar1, b2 some other string here -// -// to find that offset we find the length of all the rows and use the max -// to calculate the offset -func offsetCommands(cmds []*Command, fixed int) int { - var max int = 0 - for _, cmd := range cmds { - s := strings.Join(cmd.Names(), ", ") - if len(s) > max { - max = len(s) - } - } - return max + fixed -} diff --git a/vendor/github.com/urfave/cli/v2/mkdocs-reqs.txt b/vendor/github.com/urfave/cli/v2/mkdocs-reqs.txt deleted file mode 100644 index 482ad062..00000000 --- a/vendor/github.com/urfave/cli/v2/mkdocs-reqs.txt +++ /dev/null @@ -1,5 +0,0 @@ -mkdocs-git-revision-date-localized-plugin~=1.0 -mkdocs-material-extensions~=1.0 -mkdocs-material~=8.2 -mkdocs~=1.3 -pygments~=2.12 diff --git a/vendor/github.com/urfave/cli/v2/sliceflag.go b/vendor/github.com/urfave/cli/v2/sliceflag.go deleted file mode 100644 index b2ca5904..00000000 --- a/vendor/github.com/urfave/cli/v2/sliceflag.go +++ /dev/null @@ -1,290 +0,0 @@ -package cli - -import ( - "flag" - "reflect" -) - -type ( - // SliceFlag extends implementations like StringSliceFlag and IntSliceFlag with support for using slices directly, - // as Value and/or Destination. - // See also SliceFlagTarget, MultiStringFlag, MultiFloat64Flag, MultiInt64Flag, MultiIntFlag. - SliceFlag[T SliceFlagTarget[E], S ~[]E, E any] struct { - Target T - Value S - Destination *S - } - - // SliceFlagTarget models a target implementation for use with SliceFlag. - // The three methods, SetValue, SetDestination, and GetDestination, are necessary to propagate Value and - // Destination, where Value is propagated inwards (initially), and Destination is propagated outwards (on every - // update). - SliceFlagTarget[E any] interface { - Flag - RequiredFlag - DocGenerationFlag - VisibleFlag - CategorizableFlag - - // SetValue should propagate the given slice to the target, ideally as a new value. - // Note that a nil slice should nil/clear any existing value (modelled as ~[]E). - SetValue(slice []E) - // SetDestination should propagate the given slice to the target, ideally as a new value. - // Note that a nil slice should nil/clear any existing value (modelled as ~*[]E). - SetDestination(slice []E) - // GetDestination should return the current value referenced by any destination, or nil if nil/unset. - GetDestination() []E - } - - // MultiStringFlag extends StringSliceFlag with support for using slices directly, as Value and/or Destination. - // See also SliceFlag. - MultiStringFlag = SliceFlag[*StringSliceFlag, []string, string] - - // MultiFloat64Flag extends Float64SliceFlag with support for using slices directly, as Value and/or Destination. - // See also SliceFlag. - MultiFloat64Flag = SliceFlag[*Float64SliceFlag, []float64, float64] - - // MultiInt64Flag extends Int64SliceFlag with support for using slices directly, as Value and/or Destination. - // See also SliceFlag. - MultiInt64Flag = SliceFlag[*Int64SliceFlag, []int64, int64] - - // MultiIntFlag extends IntSliceFlag with support for using slices directly, as Value and/or Destination. - // See also SliceFlag. - MultiIntFlag = SliceFlag[*IntSliceFlag, []int, int] - - flagValueHook struct { - value Generic - hook func() - } -) - -var ( - // compile time assertions - - _ SliceFlagTarget[string] = (*StringSliceFlag)(nil) - _ SliceFlagTarget[string] = (*SliceFlag[*StringSliceFlag, []string, string])(nil) - _ SliceFlagTarget[string] = (*MultiStringFlag)(nil) - _ SliceFlagTarget[float64] = (*MultiFloat64Flag)(nil) - _ SliceFlagTarget[int64] = (*MultiInt64Flag)(nil) - _ SliceFlagTarget[int] = (*MultiIntFlag)(nil) - - _ Generic = (*flagValueHook)(nil) - _ Serializer = (*flagValueHook)(nil) -) - -func (x *SliceFlag[T, S, E]) Apply(set *flag.FlagSet) error { - x.Target.SetValue(x.convertSlice(x.Value)) - - destination := x.Destination - if destination == nil { - x.Target.SetDestination(nil) - - return x.Target.Apply(set) - } - - x.Target.SetDestination(x.convertSlice(*destination)) - - return applyFlagValueHook(set, x.Target.Apply, func() { - *destination = x.Target.GetDestination() - }) -} - -func (x *SliceFlag[T, S, E]) convertSlice(slice S) []E { - result := make([]E, len(slice)) - copy(result, slice) - return result -} - -func (x *SliceFlag[T, S, E]) SetValue(slice S) { - x.Value = slice -} - -func (x *SliceFlag[T, S, E]) SetDestination(slice S) { - if slice != nil { - x.Destination = &slice - } else { - x.Destination = nil - } -} - -func (x *SliceFlag[T, S, E]) GetDestination() S { - if destination := x.Destination; destination != nil { - return *destination - } - return nil -} - -func (x *SliceFlag[T, S, E]) String() string { return x.Target.String() } -func (x *SliceFlag[T, S, E]) Names() []string { return x.Target.Names() } -func (x *SliceFlag[T, S, E]) IsSet() bool { return x.Target.IsSet() } -func (x *SliceFlag[T, S, E]) IsRequired() bool { return x.Target.IsRequired() } -func (x *SliceFlag[T, S, E]) TakesValue() bool { return x.Target.TakesValue() } -func (x *SliceFlag[T, S, E]) GetUsage() string { return x.Target.GetUsage() } -func (x *SliceFlag[T, S, E]) GetValue() string { return x.Target.GetValue() } -func (x *SliceFlag[T, S, E]) GetDefaultText() string { return x.Target.GetDefaultText() } -func (x *SliceFlag[T, S, E]) GetEnvVars() []string { return x.Target.GetEnvVars() } -func (x *SliceFlag[T, S, E]) IsVisible() bool { return x.Target.IsVisible() } -func (x *SliceFlag[T, S, E]) GetCategory() string { return x.Target.GetCategory() } - -func (x *flagValueHook) Set(value string) error { - if err := x.value.Set(value); err != nil { - return err - } - x.hook() - return nil -} - -func (x *flagValueHook) String() string { - // note: this is necessary due to the way Go's flag package handles defaults - isZeroValue := func(f flag.Value, v string) bool { - /* - https://cs.opensource.google/go/go/+/refs/tags/go1.18.3:src/flag/flag.go;drc=2580d0e08d5e9f979b943758d3c49877fb2324cb;l=453 - - Copyright (c) 2009 The Go Authors. All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * 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. - * Neither the name of Google Inc. 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 - OWNER 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. - */ - // Build a zero value of the flag's Value type, and see if the - // result of calling its String method equals the value passed in. - // This works unless the Value type is itself an interface type. - typ := reflect.TypeOf(f) - var z reflect.Value - if typ.Kind() == reflect.Pointer { - z = reflect.New(typ.Elem()) - } else { - z = reflect.Zero(typ) - } - return v == z.Interface().(flag.Value).String() - } - if x.value != nil { - // only return non-empty if not the same string as returned by the zero value - if s := x.value.String(); !isZeroValue(x.value, s) { - return s - } - } - return `` -} - -func (x *flagValueHook) Serialize() string { - if value, ok := x.value.(Serializer); ok { - return value.Serialize() - } - return x.String() -} - -// applyFlagValueHook wraps calls apply then wraps flags to call a hook function on update and after initial apply. -func applyFlagValueHook(set *flag.FlagSet, apply func(set *flag.FlagSet) error, hook func()) error { - if apply == nil || set == nil || hook == nil { - panic(`invalid input`) - } - var tmp flag.FlagSet - if err := apply(&tmp); err != nil { - return err - } - tmp.VisitAll(func(f *flag.Flag) { set.Var(&flagValueHook{value: f.Value, hook: hook}, f.Name, f.Usage) }) - hook() - return nil -} - -// newSliceFlagValue is for implementing SliceFlagTarget.SetValue and SliceFlagTarget.SetDestination. -// It's e.g. as part of StringSliceFlag.SetValue, using the factory NewStringSlice. -func newSliceFlagValue[R any, S ~[]E, E any](factory func(defaults ...E) *R, defaults S) *R { - if defaults == nil { - return nil - } - return factory(defaults...) -} - -// unwrapFlagValue strips any/all *flagValueHook wrappers. -func unwrapFlagValue(v flag.Value) flag.Value { - for { - h, ok := v.(*flagValueHook) - if !ok { - return v - } - v = h.value - } -} - -// NOTE: the methods below are in this file to make use of the build constraint - -func (f *Float64SliceFlag) SetValue(slice []float64) { - f.Value = newSliceFlagValue(NewFloat64Slice, slice) -} - -func (f *Float64SliceFlag) SetDestination(slice []float64) { - f.Destination = newSliceFlagValue(NewFloat64Slice, slice) -} - -func (f *Float64SliceFlag) GetDestination() []float64 { - if destination := f.Destination; destination != nil { - return destination.Value() - } - return nil -} - -func (f *Int64SliceFlag) SetValue(slice []int64) { - f.Value = newSliceFlagValue(NewInt64Slice, slice) -} - -func (f *Int64SliceFlag) SetDestination(slice []int64) { - f.Destination = newSliceFlagValue(NewInt64Slice, slice) -} - -func (f *Int64SliceFlag) GetDestination() []int64 { - if destination := f.Destination; destination != nil { - return destination.Value() - } - return nil -} - -func (f *IntSliceFlag) SetValue(slice []int) { - f.Value = newSliceFlagValue(NewIntSlice, slice) -} - -func (f *IntSliceFlag) SetDestination(slice []int) { - f.Destination = newSliceFlagValue(NewIntSlice, slice) -} - -func (f *IntSliceFlag) GetDestination() []int { - if destination := f.Destination; destination != nil { - return destination.Value() - } - return nil -} - -func (f *StringSliceFlag) SetValue(slice []string) { - f.Value = newSliceFlagValue(NewStringSlice, slice) -} - -func (f *StringSliceFlag) SetDestination(slice []string) { - f.Destination = newSliceFlagValue(NewStringSlice, slice) -} - -func (f *StringSliceFlag) GetDestination() []string { - if destination := f.Destination; destination != nil { - return destination.Value() - } - return nil -} diff --git a/vendor/github.com/urfave/cli/v2/sort.go b/vendor/github.com/urfave/cli/v2/sort.go deleted file mode 100644 index 23d1c2f7..00000000 --- a/vendor/github.com/urfave/cli/v2/sort.go +++ /dev/null @@ -1,29 +0,0 @@ -package cli - -import "unicode" - -// lexicographicLess compares strings alphabetically considering case. -func lexicographicLess(i, j string) bool { - iRunes := []rune(i) - jRunes := []rune(j) - - lenShared := len(iRunes) - if lenShared > len(jRunes) { - lenShared = len(jRunes) - } - - for index := 0; index < lenShared; index++ { - ir := iRunes[index] - jr := jRunes[index] - - if lir, ljr := unicode.ToLower(ir), unicode.ToLower(jr); lir != ljr { - return lir < ljr - } - - if ir != jr { - return ir < jr - } - } - - return i < j -} diff --git a/vendor/github.com/urfave/cli/v2/suggestions.go b/vendor/github.com/urfave/cli/v2/suggestions.go deleted file mode 100644 index 9d2b7a81..00000000 --- a/vendor/github.com/urfave/cli/v2/suggestions.go +++ /dev/null @@ -1,68 +0,0 @@ -//go:build !urfave_cli_no_suggest -// +build !urfave_cli_no_suggest - -package cli - -import ( - "fmt" - - "github.com/xrash/smetrics" -) - -func init() { - SuggestFlag = suggestFlag - SuggestCommand = suggestCommand -} - -func jaroWinkler(a, b string) float64 { - // magic values are from https://github.com/xrash/smetrics/blob/039620a656736e6ad994090895784a7af15e0b80/jaro-winkler.go#L8 - const ( - boostThreshold = 0.7 - prefixSize = 4 - ) - return smetrics.JaroWinkler(a, b, boostThreshold, prefixSize) -} - -func suggestFlag(flags []Flag, provided string, hideHelp bool) string { - distance := 0.0 - suggestion := "" - - for _, flag := range flags { - flagNames := flag.Names() - if !hideHelp && HelpFlag != nil { - flagNames = append(flagNames, HelpFlag.Names()...) - } - for _, name := range flagNames { - newDistance := jaroWinkler(name, provided) - if newDistance > distance { - distance = newDistance - suggestion = name - } - } - } - - if len(suggestion) == 1 { - suggestion = "-" + suggestion - } else if len(suggestion) > 1 { - suggestion = "--" + suggestion - } - - return suggestion -} - -// suggestCommand takes a list of commands and a provided string to suggest a -// command name -func suggestCommand(commands []*Command, provided string) (suggestion string) { - distance := 0.0 - for _, command := range commands { - for _, name := range append(command.Names(), helpName, helpAlias) { - newDistance := jaroWinkler(name, provided) - if newDistance > distance { - distance = newDistance - suggestion = name - } - } - } - - return fmt.Sprintf(SuggestDidYouMeanTemplate, suggestion) -} diff --git a/vendor/github.com/urfave/cli/v2/zz_generated.flags.go b/vendor/github.com/urfave/cli/v2/zz_generated.flags.go deleted file mode 100644 index f2fc8c88..00000000 --- a/vendor/github.com/urfave/cli/v2/zz_generated.flags.go +++ /dev/null @@ -1,865 +0,0 @@ -// WARNING: this file is generated. DO NOT EDIT - -package cli - -import "time" - -// Float64SliceFlag is a flag with type *Float64Slice -type Float64SliceFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value *Float64Slice - Destination *Float64Slice - - Aliases []string - EnvVars []string - - defaultValue *Float64Slice - defaultValueSet bool - - separator separatorSpec - - Action func(*Context, []float64) error -} - -// IsSet returns whether or not the flag has been set through env or file -func (f *Float64SliceFlag) IsSet() bool { - return f.HasBeenSet -} - -// Names returns the names of the flag -func (f *Float64SliceFlag) Names() []string { - return FlagNames(f.Name, f.Aliases) -} - -// IsRequired returns whether or not the flag is required -func (f *Float64SliceFlag) IsRequired() bool { - return f.Required -} - -// IsVisible returns true if the flag is not hidden, otherwise false -func (f *Float64SliceFlag) IsVisible() bool { - return !f.Hidden -} - -// GenericFlag is a flag with type Generic -type GenericFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value Generic - Destination Generic - - Aliases []string - EnvVars []string - - defaultValue Generic - defaultValueSet bool - - TakesFile bool - - Action func(*Context, interface{}) error -} - -// String returns a readable representation of this value (for usage defaults) -func (f *GenericFlag) String() string { - return FlagStringer(f) -} - -// IsSet returns whether or not the flag has been set through env or file -func (f *GenericFlag) IsSet() bool { - return f.HasBeenSet -} - -// Names returns the names of the flag -func (f *GenericFlag) Names() []string { - return FlagNames(f.Name, f.Aliases) -} - -// IsRequired returns whether or not the flag is required -func (f *GenericFlag) IsRequired() bool { - return f.Required -} - -// IsVisible returns true if the flag is not hidden, otherwise false -func (f *GenericFlag) IsVisible() bool { - return !f.Hidden -} - -// Int64SliceFlag is a flag with type *Int64Slice -type Int64SliceFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value *Int64Slice - Destination *Int64Slice - - Aliases []string - EnvVars []string - - defaultValue *Int64Slice - defaultValueSet bool - - separator separatorSpec - - Action func(*Context, []int64) error -} - -// IsSet returns whether or not the flag has been set through env or file -func (f *Int64SliceFlag) IsSet() bool { - return f.HasBeenSet -} - -// Names returns the names of the flag -func (f *Int64SliceFlag) Names() []string { - return FlagNames(f.Name, f.Aliases) -} - -// IsRequired returns whether or not the flag is required -func (f *Int64SliceFlag) IsRequired() bool { - return f.Required -} - -// IsVisible returns true if the flag is not hidden, otherwise false -func (f *Int64SliceFlag) IsVisible() bool { - return !f.Hidden -} - -// IntSliceFlag is a flag with type *IntSlice -type IntSliceFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value *IntSlice - Destination *IntSlice - - Aliases []string - EnvVars []string - - defaultValue *IntSlice - defaultValueSet bool - - separator separatorSpec - - Action func(*Context, []int) error -} - -// IsSet returns whether or not the flag has been set through env or file -func (f *IntSliceFlag) IsSet() bool { - return f.HasBeenSet -} - -// Names returns the names of the flag -func (f *IntSliceFlag) Names() []string { - return FlagNames(f.Name, f.Aliases) -} - -// IsRequired returns whether or not the flag is required -func (f *IntSliceFlag) IsRequired() bool { - return f.Required -} - -// IsVisible returns true if the flag is not hidden, otherwise false -func (f *IntSliceFlag) IsVisible() bool { - return !f.Hidden -} - -// PathFlag is a flag with type Path -type PathFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value Path - Destination *Path - - Aliases []string - EnvVars []string - - defaultValue Path - defaultValueSet bool - - TakesFile bool - - Action func(*Context, Path) error -} - -// String returns a readable representation of this value (for usage defaults) -func (f *PathFlag) String() string { - return FlagStringer(f) -} - -// IsSet returns whether or not the flag has been set through env or file -func (f *PathFlag) IsSet() bool { - return f.HasBeenSet -} - -// Names returns the names of the flag -func (f *PathFlag) Names() []string { - return FlagNames(f.Name, f.Aliases) -} - -// IsRequired returns whether or not the flag is required -func (f *PathFlag) IsRequired() bool { - return f.Required -} - -// IsVisible returns true if the flag is not hidden, otherwise false -func (f *PathFlag) IsVisible() bool { - return !f.Hidden -} - -// StringSliceFlag is a flag with type *StringSlice -type StringSliceFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value *StringSlice - Destination *StringSlice - - Aliases []string - EnvVars []string - - defaultValue *StringSlice - defaultValueSet bool - - separator separatorSpec - - TakesFile bool - - Action func(*Context, []string) error - - KeepSpace bool -} - -// IsSet returns whether or not the flag has been set through env or file -func (f *StringSliceFlag) IsSet() bool { - return f.HasBeenSet -} - -// Names returns the names of the flag -func (f *StringSliceFlag) Names() []string { - return FlagNames(f.Name, f.Aliases) -} - -// IsRequired returns whether or not the flag is required -func (f *StringSliceFlag) IsRequired() bool { - return f.Required -} - -// IsVisible returns true if the flag is not hidden, otherwise false -func (f *StringSliceFlag) IsVisible() bool { - return !f.Hidden -} - -// TimestampFlag is a flag with type *Timestamp -type TimestampFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value *Timestamp - Destination *Timestamp - - Aliases []string - EnvVars []string - - defaultValue *Timestamp - defaultValueSet bool - - Layout string - - Timezone *time.Location - - Action func(*Context, *time.Time) error -} - -// String returns a readable representation of this value (for usage defaults) -func (f *TimestampFlag) String() string { - return FlagStringer(f) -} - -// IsSet returns whether or not the flag has been set through env or file -func (f *TimestampFlag) IsSet() bool { - return f.HasBeenSet -} - -// Names returns the names of the flag -func (f *TimestampFlag) Names() []string { - return FlagNames(f.Name, f.Aliases) -} - -// IsRequired returns whether or not the flag is required -func (f *TimestampFlag) IsRequired() bool { - return f.Required -} - -// IsVisible returns true if the flag is not hidden, otherwise false -func (f *TimestampFlag) IsVisible() bool { - return !f.Hidden -} - -// Uint64SliceFlag is a flag with type *Uint64Slice -type Uint64SliceFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value *Uint64Slice - Destination *Uint64Slice - - Aliases []string - EnvVars []string - - defaultValue *Uint64Slice - defaultValueSet bool - - separator separatorSpec - - Action func(*Context, []uint64) error -} - -// IsSet returns whether or not the flag has been set through env or file -func (f *Uint64SliceFlag) IsSet() bool { - return f.HasBeenSet -} - -// Names returns the names of the flag -func (f *Uint64SliceFlag) Names() []string { - return FlagNames(f.Name, f.Aliases) -} - -// IsRequired returns whether or not the flag is required -func (f *Uint64SliceFlag) IsRequired() bool { - return f.Required -} - -// IsVisible returns true if the flag is not hidden, otherwise false -func (f *Uint64SliceFlag) IsVisible() bool { - return !f.Hidden -} - -// UintSliceFlag is a flag with type *UintSlice -type UintSliceFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value *UintSlice - Destination *UintSlice - - Aliases []string - EnvVars []string - - defaultValue *UintSlice - defaultValueSet bool - - separator separatorSpec - - Action func(*Context, []uint) error -} - -// IsSet returns whether or not the flag has been set through env or file -func (f *UintSliceFlag) IsSet() bool { - return f.HasBeenSet -} - -// Names returns the names of the flag -func (f *UintSliceFlag) Names() []string { - return FlagNames(f.Name, f.Aliases) -} - -// IsRequired returns whether or not the flag is required -func (f *UintSliceFlag) IsRequired() bool { - return f.Required -} - -// IsVisible returns true if the flag is not hidden, otherwise false -func (f *UintSliceFlag) IsVisible() bool { - return !f.Hidden -} - -// BoolFlag is a flag with type bool -type BoolFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value bool - Destination *bool - - Aliases []string - EnvVars []string - - defaultValue bool - defaultValueSet bool - - Count *int - - DisableDefaultText bool - - Action func(*Context, bool) error -} - -// String returns a readable representation of this value (for usage defaults) -func (f *BoolFlag) String() string { - return FlagStringer(f) -} - -// IsSet returns whether or not the flag has been set through env or file -func (f *BoolFlag) IsSet() bool { - return f.HasBeenSet -} - -// Names returns the names of the flag -func (f *BoolFlag) Names() []string { - return FlagNames(f.Name, f.Aliases) -} - -// IsRequired returns whether or not the flag is required -func (f *BoolFlag) IsRequired() bool { - return f.Required -} - -// IsVisible returns true if the flag is not hidden, otherwise false -func (f *BoolFlag) IsVisible() bool { - return !f.Hidden -} - -// Float64Flag is a flag with type float64 -type Float64Flag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value float64 - Destination *float64 - - Aliases []string - EnvVars []string - - defaultValue float64 - defaultValueSet bool - - Action func(*Context, float64) error -} - -// String returns a readable representation of this value (for usage defaults) -func (f *Float64Flag) String() string { - return FlagStringer(f) -} - -// IsSet returns whether or not the flag has been set through env or file -func (f *Float64Flag) IsSet() bool { - return f.HasBeenSet -} - -// Names returns the names of the flag -func (f *Float64Flag) Names() []string { - return FlagNames(f.Name, f.Aliases) -} - -// IsRequired returns whether or not the flag is required -func (f *Float64Flag) IsRequired() bool { - return f.Required -} - -// IsVisible returns true if the flag is not hidden, otherwise false -func (f *Float64Flag) IsVisible() bool { - return !f.Hidden -} - -// IntFlag is a flag with type int -type IntFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value int - Destination *int - - Aliases []string - EnvVars []string - - defaultValue int - defaultValueSet bool - - Base int - - Action func(*Context, int) error -} - -// String returns a readable representation of this value (for usage defaults) -func (f *IntFlag) String() string { - return FlagStringer(f) -} - -// IsSet returns whether or not the flag has been set through env or file -func (f *IntFlag) IsSet() bool { - return f.HasBeenSet -} - -// Names returns the names of the flag -func (f *IntFlag) Names() []string { - return FlagNames(f.Name, f.Aliases) -} - -// IsRequired returns whether or not the flag is required -func (f *IntFlag) IsRequired() bool { - return f.Required -} - -// IsVisible returns true if the flag is not hidden, otherwise false -func (f *IntFlag) IsVisible() bool { - return !f.Hidden -} - -// Int64Flag is a flag with type int64 -type Int64Flag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value int64 - Destination *int64 - - Aliases []string - EnvVars []string - - defaultValue int64 - defaultValueSet bool - - Base int - - Action func(*Context, int64) error -} - -// String returns a readable representation of this value (for usage defaults) -func (f *Int64Flag) String() string { - return FlagStringer(f) -} - -// IsSet returns whether or not the flag has been set through env or file -func (f *Int64Flag) IsSet() bool { - return f.HasBeenSet -} - -// Names returns the names of the flag -func (f *Int64Flag) Names() []string { - return FlagNames(f.Name, f.Aliases) -} - -// IsRequired returns whether or not the flag is required -func (f *Int64Flag) IsRequired() bool { - return f.Required -} - -// IsVisible returns true if the flag is not hidden, otherwise false -func (f *Int64Flag) IsVisible() bool { - return !f.Hidden -} - -// StringFlag is a flag with type string -type StringFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value string - Destination *string - - Aliases []string - EnvVars []string - - defaultValue string - defaultValueSet bool - - TakesFile bool - - Action func(*Context, string) error -} - -// String returns a readable representation of this value (for usage defaults) -func (f *StringFlag) String() string { - return FlagStringer(f) -} - -// IsSet returns whether or not the flag has been set through env or file -func (f *StringFlag) IsSet() bool { - return f.HasBeenSet -} - -// Names returns the names of the flag -func (f *StringFlag) Names() []string { - return FlagNames(f.Name, f.Aliases) -} - -// IsRequired returns whether or not the flag is required -func (f *StringFlag) IsRequired() bool { - return f.Required -} - -// IsVisible returns true if the flag is not hidden, otherwise false -func (f *StringFlag) IsVisible() bool { - return !f.Hidden -} - -// DurationFlag is a flag with type time.Duration -type DurationFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value time.Duration - Destination *time.Duration - - Aliases []string - EnvVars []string - - defaultValue time.Duration - defaultValueSet bool - - Action func(*Context, time.Duration) error -} - -// String returns a readable representation of this value (for usage defaults) -func (f *DurationFlag) String() string { - return FlagStringer(f) -} - -// IsSet returns whether or not the flag has been set through env or file -func (f *DurationFlag) IsSet() bool { - return f.HasBeenSet -} - -// Names returns the names of the flag -func (f *DurationFlag) Names() []string { - return FlagNames(f.Name, f.Aliases) -} - -// IsRequired returns whether or not the flag is required -func (f *DurationFlag) IsRequired() bool { - return f.Required -} - -// IsVisible returns true if the flag is not hidden, otherwise false -func (f *DurationFlag) IsVisible() bool { - return !f.Hidden -} - -// UintFlag is a flag with type uint -type UintFlag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value uint - Destination *uint - - Aliases []string - EnvVars []string - - defaultValue uint - defaultValueSet bool - - Base int - - Action func(*Context, uint) error -} - -// String returns a readable representation of this value (for usage defaults) -func (f *UintFlag) String() string { - return FlagStringer(f) -} - -// IsSet returns whether or not the flag has been set through env or file -func (f *UintFlag) IsSet() bool { - return f.HasBeenSet -} - -// Names returns the names of the flag -func (f *UintFlag) Names() []string { - return FlagNames(f.Name, f.Aliases) -} - -// IsRequired returns whether or not the flag is required -func (f *UintFlag) IsRequired() bool { - return f.Required -} - -// IsVisible returns true if the flag is not hidden, otherwise false -func (f *UintFlag) IsVisible() bool { - return !f.Hidden -} - -// Uint64Flag is a flag with type uint64 -type Uint64Flag struct { - Name string - - Category string - DefaultText string - FilePath string - Usage string - - Required bool - Hidden bool - HasBeenSet bool - - Value uint64 - Destination *uint64 - - Aliases []string - EnvVars []string - - defaultValue uint64 - defaultValueSet bool - - Base int - - Action func(*Context, uint64) error -} - -// String returns a readable representation of this value (for usage defaults) -func (f *Uint64Flag) String() string { - return FlagStringer(f) -} - -// IsSet returns whether or not the flag has been set through env or file -func (f *Uint64Flag) IsSet() bool { - return f.HasBeenSet -} - -// Names returns the names of the flag -func (f *Uint64Flag) Names() []string { - return FlagNames(f.Name, f.Aliases) -} - -// IsRequired returns whether or not the flag is required -func (f *Uint64Flag) IsRequired() bool { - return f.Required -} - -// IsVisible returns true if the flag is not hidden, otherwise false -func (f *Uint64Flag) IsVisible() bool { - return !f.Hidden -} - -// vim:ro diff --git a/vendor/github.com/urfave/cli/v2/.gitignore b/vendor/github.com/urfave/cli/v3/.gitignore similarity index 52% rename from vendor/github.com/urfave/cli/v2/.gitignore rename to vendor/github.com/urfave/cli/v3/.gitignore index 1ef91a60..cbccea21 100644 --- a/vendor/github.com/urfave/cli/v2/.gitignore +++ b/vendor/github.com/urfave/cli/v3/.gitignore @@ -4,11 +4,8 @@ .*envrc .envrc .idea -# goimports is installed here if not available /.local/ /site/ coverage.txt internal/*/built-example vendor -/cmd/urfave-cli-genflags/urfave-cli-genflags -*.exe diff --git a/vendor/github.com/urfave/cli/v2/.golangci.yaml b/vendor/github.com/urfave/cli/v3/.golangci.yaml similarity index 84% rename from vendor/github.com/urfave/cli/v2/.golangci.yaml rename to vendor/github.com/urfave/cli/v3/.golangci.yaml index 89b6e866..a6e8c7e9 100644 --- a/vendor/github.com/urfave/cli/v2/.golangci.yaml +++ b/vendor/github.com/urfave/cli/v3/.golangci.yaml @@ -1,4 +1,5 @@ # https://golangci-lint.run/usage/configuration/ linters: enable: + - makezero - misspell diff --git a/vendor/github.com/urfave/cli/v2/CODE_OF_CONDUCT.md b/vendor/github.com/urfave/cli/v3/CODE_OF_CONDUCT.md similarity index 100% rename from vendor/github.com/urfave/cli/v2/CODE_OF_CONDUCT.md rename to vendor/github.com/urfave/cli/v3/CODE_OF_CONDUCT.md diff --git a/vendor/github.com/urfave/cli/v2/LICENSE b/vendor/github.com/urfave/cli/v3/LICENSE similarity index 96% rename from vendor/github.com/urfave/cli/v2/LICENSE rename to vendor/github.com/urfave/cli/v3/LICENSE index 2c84c78a..a23fc53d 100644 --- a/vendor/github.com/urfave/cli/v2/LICENSE +++ b/vendor/github.com/urfave/cli/v3/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2022 urfave/cli maintainers +Copyright (c) 2023 urfave/cli maintainers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/github.com/urfave/cli/v2/Makefile b/vendor/github.com/urfave/cli/v3/Makefile similarity index 92% rename from vendor/github.com/urfave/cli/v2/Makefile rename to vendor/github.com/urfave/cli/v3/Makefile index f0d41905..e9e13ff5 100644 --- a/vendor/github.com/urfave/cli/v2/Makefile +++ b/vendor/github.com/urfave/cli/v3/Makefile @@ -7,7 +7,7 @@ GO_RUN_BUILD := go run internal/build/build.go .PHONY: all -all: generate vet test check-binary-size gfmrun yamlfmt v2diff +all: generate vet test check-binary-size gfmrun # NOTE: this is a special catch-all rule to run any of the commands # defined in internal/build/build.go with optional arguments passed diff --git a/vendor/github.com/urfave/cli/v3/README.md b/vendor/github.com/urfave/cli/v3/README.md new file mode 100644 index 00000000..e04c7295 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/README.md @@ -0,0 +1,56 @@ +# Welcome to urfave/cli + +[![Go Reference][goreference_badge]][goreference_link] +[![Go Report Card][goreportcard_badge]][goreportcard_link] +[![codecov][codecov_badge]][codecov_link] +[![Tests status][test_badge]][test_link] + +urfave/cli is a **declarative**, simple, fast, and fun package for building +command line tools in Go featuring: + +- commands and subcommands with alias and prefix match support +- flexible and permissive help system +- dynamic shell completion for `bash`, `zsh`, `fish`, and `powershell` +- no dependencies except Go standard library +- input flags for simple types, slices of simple types, time, duration, and + others +- compound short flag support (`-a` `-b` `-c` can be shortened to `-abc`) +- documentation generation in `man` and Markdown (supported via the + [`urfave/cli-docs`][urfave/cli-docs] module) +- input lookup from: + - environment variables + - plain text files + - structured file formats (supported via the + [`urfave/cli-altsrc`][urfave/cli-altsrc] module) + +## Documentation + +See the hosted documentation website at . Contents of +this website are built from the [`./docs`](./docs) directory. + +## Support + +Check the [Q&A discussions]. If you don't find answer to your question, [create +a new discussion]. + +If you found a bug or have a feature request, [create a new issue]. + +Please keep in mind that this project is run by unpaid volunteers. + +### License + +See [`LICENSE`](./LICENSE). + +[test_badge]: https://github.com/urfave/cli/actions/workflows/test.yml/badge.svg +[test_link]: https://github.com/urfave/cli/actions/workflows/test.yml +[goreference_badge]: https://pkg.go.dev/badge/github.com/urfave/cli/v3.svg +[goreference_link]: https://pkg.go.dev/github.com/urfave/cli/v3 +[goreportcard_badge]: https://goreportcard.com/badge/github.com/urfave/cli/v3 +[goreportcard_link]: https://goreportcard.com/report/github.com/urfave/cli/v3 +[codecov_badge]: https://codecov.io/gh/urfave/cli/branch/main/graph/badge.svg?token=t9YGWLh05g +[codecov_link]: https://codecov.io/gh/urfave/cli +[Q&A discussions]: https://github.com/urfave/cli/discussions/categories/q-a +[create a new discussion]: https://github.com/urfave/cli/discussions/new?category=q-a +[urfave/cli-docs]: https://github.com/urfave/cli-docs +[urfave/cli-altsrc]: https://github.com/urfave/cli-altsrc +[create a new issue]: https://github.com/urfave/cli/issues/new/choose diff --git a/vendor/github.com/urfave/cli/v3/args.go b/vendor/github.com/urfave/cli/v3/args.go new file mode 100644 index 00000000..682eb497 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/args.go @@ -0,0 +1,153 @@ +package cli + +import ( + "fmt" + "time" +) + +type Args interface { + // Get returns the nth argument, or else a blank string + Get(n int) string + // First returns the first argument, or else a blank string + First() string + // Tail returns the rest of the arguments (not the first one) + // or else an empty string slice + Tail() []string + // Len returns the length of the wrapped slice + Len() int + // Present checks if there are any arguments present + Present() bool + // Slice returns a copy of the internal slice + Slice() []string +} + +type stringSliceArgs struct { + v []string +} + +func (a *stringSliceArgs) Get(n int) string { + if len(a.v) > n { + return a.v[n] + } + return "" +} + +func (a *stringSliceArgs) First() string { + return a.Get(0) +} + +func (a *stringSliceArgs) Tail() []string { + if a.Len() >= 2 { + tail := a.v[1:] + ret := make([]string, len(tail)) + copy(ret, tail) + return ret + } + + return []string{} +} + +func (a *stringSliceArgs) Len() int { + return len(a.v) +} + +func (a *stringSliceArgs) Present() bool { + return a.Len() != 0 +} + +func (a *stringSliceArgs) Slice() []string { + ret := make([]string, len(a.v)) + copy(ret, a.v) + return ret +} + +type Argument interface { + Parse([]string) ([]string, error) + Usage() string +} + +type ArgumentBase[T any, C any, VC ValueCreator[T, C]] struct { + Name string `json:"name"` // the name of this argument + Value T `json:"value"` // the default value of this argument + Destination *T `json:"-"` // the destination point for this argument + Values *[]T `json:"-"` // all the values of this argument, only if multiple are supported + UsageText string `json:"usageText"` // the usage text to show + Min int `json:"minTimes"` // the min num of occurrences of this argument + Max int `json:"maxTimes"` // the max num of occurrences of this argument, set to -1 for unlimited + Config C `json:"config"` // config for this argument similar to Flag Config +} + +func (a *ArgumentBase[T, C, VC]) Usage() string { + if a.UsageText != "" { + return a.UsageText + } + + usageFormat := "" + if a.Min == 0 { + if a.Max == 1 { + usageFormat = "[%[1]s]" + } else { + usageFormat = "[%[1]s ...]" + } + } else { + usageFormat = "%[1]s [%[1]s ...]" + } + return fmt.Sprintf(usageFormat, a.Name) +} + +func (a *ArgumentBase[T, C, VC]) Parse(s []string) ([]string, error) { + tracef("calling arg%[1] parse with args %[2]", &a.Name, s) + if a.Max == 0 { + fmt.Printf("WARNING args %s has max 0, not parsing argument", a.Name) + return s, nil + } + if a.Max != -1 && a.Min > a.Max { + fmt.Printf("WARNING args %s has min[%d] > max[%d], not parsing argument", a.Name, a.Min, a.Max) + return s, nil + } + + count := 0 + var vc VC + var t T + value := vc.Create(a.Value, &t, a.Config) + values := []T{} + + for _, arg := range s { + if err := value.Set(arg); err != nil { + return s, err + } + values = append(values, value.Get().(T)) + count++ + if count >= a.Max && a.Max > -1 { + break + } + } + if count < a.Min { + return s, fmt.Errorf("sufficient count of arg %s not provided, given %d expected %d", a.Name, count, a.Min) + } + + if a.Values == nil { + a.Values = &values + } else if count > 0 { + *a.Values = values + } + + if a.Max == 1 && a.Destination != nil { + if len(values) > 0 { + *a.Destination = values[0] + } else { + *a.Destination = t + } + } + + return s[count:], nil +} + +type ( + FloatArg = ArgumentBase[float64, NoConfig, floatValue] + IntArg = ArgumentBase[int64, IntegerConfig, intValue] + StringArg = ArgumentBase[string, StringConfig, stringValue] + StringMapArg = ArgumentBase[map[string]string, StringConfig, StringMap] + TimestampArg = ArgumentBase[time.Time, TimestampConfig, timestampValue] + UintArg = ArgumentBase[uint64, IntegerConfig, uintValue] +) diff --git a/vendor/github.com/urfave/cli/v3/autocomplete/bash_autocomplete b/vendor/github.com/urfave/cli/v3/autocomplete/bash_autocomplete new file mode 100644 index 00000000..7120a0d2 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/autocomplete/bash_autocomplete @@ -0,0 +1,35 @@ +#! /bin/bash + +: ${PROG:=$(basename ${BASH_SOURCE})} + +# Macs have bash3 for which the bash-completion package doesn't include +# _init_completion. This is a minimal version of that function. +_cli_init_completion() { + COMPREPLY=() + _get_comp_words_by_ref "$@" cur prev words cword +} + +_cli_bash_autocomplete() { + if [[ "${COMP_WORDS[0]}" != "source" ]]; then + local cur opts base words + COMPREPLY=() + cur="${COMP_WORDS[COMP_CWORD]}" + if declare -F _init_completion >/dev/null 2>&1; then + _init_completion -n "=:" || return + else + _cli_init_completion -n "=:" || return + fi + words=("${words[@]:0:$cword}") + if [[ "$cur" == "-"* ]]; then + requestComp="${words[*]} ${cur} --generate-shell-completion" + else + requestComp="${words[*]} --generate-shell-completion" + fi + opts=$(eval "${requestComp}" 2>/dev/null) + COMPREPLY=($(compgen -W "${opts}" -- ${cur})) + return 0 + fi +} + +complete -o bashdefault -o default -o nospace -F _cli_bash_autocomplete $PROG +unset PROG diff --git a/vendor/github.com/urfave/cli/v3/autocomplete/powershell_autocomplete.ps1 b/vendor/github.com/urfave/cli/v3/autocomplete/powershell_autocomplete.ps1 new file mode 100644 index 00000000..cbf76942 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/autocomplete/powershell_autocomplete.ps1 @@ -0,0 +1,9 @@ +$fn = $($MyInvocation.MyCommand.Name) +$name = $fn -replace "(.*)\.ps1$", '$1' +Register-ArgumentCompleter -Native -CommandName $name -ScriptBlock { + param($commandName, $wordToComplete, $cursorPosition) + $other = "$wordToComplete --generate-shell-completion" + Invoke-Expression $other | ForEach-Object { + [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) + } + } \ No newline at end of file diff --git a/vendor/github.com/urfave/cli/v3/autocomplete/zsh_autocomplete b/vendor/github.com/urfave/cli/v3/autocomplete/zsh_autocomplete new file mode 100644 index 00000000..943cf60b --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/autocomplete/zsh_autocomplete @@ -0,0 +1,30 @@ +#compdef program +compdef _program program + +# Replace all occurrences of "program" in this file with the actual name of your +# CLI program. We recommend using Find+Replace feature of your editor. Let's say +# your CLI program is called "acme", then replace like so: +# * program => acme +# * _program => _acme + +_program() { + local -a opts + local cur + cur=${words[-1]} + if [[ "$cur" == "-"* ]]; then + opts=("${(@f)$(${words[@]:0:#words[@]-1} ${cur} --generate-shell-completion)}") + else + opts=("${(@f)$(${words[@]:0:#words[@]-1} --generate-shell-completion)}") + fi + + if [[ "${opts[1]}" != "" ]]; then + _describe 'values' opts + else + _files + fi +} + +# don't run the completion function when being source-ed or eval-ed +if [ "$funcstack[1]" = "_program" ]; then + _program +fi diff --git a/vendor/github.com/urfave/cli/v2/category.go b/vendor/github.com/urfave/cli/v3/category.go similarity index 89% rename from vendor/github.com/urfave/cli/v2/category.go rename to vendor/github.com/urfave/cli/v3/category.go index 0986fffc..14e3649c 100644 --- a/vendor/github.com/urfave/cli/v2/category.go +++ b/vendor/github.com/urfave/cli/v3/category.go @@ -102,10 +102,15 @@ func newFlagCategoriesFromFlags(fs []Flag) FlagCategories { fc := newFlagCategories() var categorized bool + for _, fl := range fs { if cf, ok := fl.(CategorizableFlag); ok { - if cat := cf.GetCategory(); cat != "" && cf.IsVisible() { - fc.AddFlag(cat, cf) + visible := false + if vf, ok := fl.(VisibleFlag); ok { + visible = vf.IsVisible() + } + if cat := cf.GetCategory(); cat != "" && visible { + fc.AddFlag(cat, fl) categorized = true } } @@ -114,7 +119,11 @@ func newFlagCategoriesFromFlags(fs []Flag) FlagCategories { if categorized { for _, fl := range fs { if cf, ok := fl.(CategorizableFlag); ok { - if cf.GetCategory() == "" && cf.IsVisible() { + visible := false + if vf, ok := fl.(VisibleFlag); ok { + visible = vf.IsVisible() + } + if cf.GetCategory() == "" && visible { fc.AddFlag("", fl) } } @@ -153,7 +162,7 @@ type VisibleFlagCategory interface { // Name returns the category name string Name() string // Flags returns a slice of VisibleFlag sorted by name - Flags() []VisibleFlag + Flags() []Flag } type defaultVisibleFlagCategory struct { @@ -165,7 +174,7 @@ func (fc *defaultVisibleFlagCategory) Name() string { return fc.name } -func (fc *defaultVisibleFlagCategory) Flags() []VisibleFlag { +func (fc *defaultVisibleFlagCategory) Flags() []Flag { vfNames := []string{} for flName, fl := range fc.m { if vf, ok := fl.(VisibleFlag); ok { @@ -177,9 +186,9 @@ func (fc *defaultVisibleFlagCategory) Flags() []VisibleFlag { sort.Strings(vfNames) - ret := make([]VisibleFlag, len(vfNames)) + ret := make([]Flag, len(vfNames)) for i, flName := range vfNames { - ret[i] = fc.m[flName].(VisibleFlag) + ret[i] = fc.m[flName] } return ret diff --git a/vendor/github.com/urfave/cli/v3/cli.go b/vendor/github.com/urfave/cli/v3/cli.go new file mode 100644 index 00000000..d833aff5 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/cli.go @@ -0,0 +1,60 @@ +// Package cli provides a minimal framework for creating and organizing command line +// Go applications. cli is designed to be easy to understand and write, the most simple +// cli application can be written as follows: +// +// func main() { +// (&cli.Command{}).Run(context.Background(), os.Args) +// } +// +// Of course this application does not do much, so let's make this an actual application: +// +// func main() { +// cmd := &cli.Command{ +// Name: "greet", +// Usage: "say a greeting", +// Action: func(c *cli.Context) error { +// fmt.Println("Greetings") +// return nil +// }, +// } +// +// cmd.Run(context.Background(), os.Args) +// } +package cli + +import ( + "fmt" + "os" + "runtime" + "strings" +) + +var isTracingOn = os.Getenv("URFAVE_CLI_TRACING") == "on" + +func tracef(format string, a ...any) { + if !isTracingOn { + return + } + + if !strings.HasSuffix(format, "\n") { + format = format + "\n" + } + + pc, file, line, _ := runtime.Caller(1) + cf := runtime.FuncForPC(pc) + + fmt.Fprintf( + os.Stderr, + strings.Join([]string{ + "## URFAVE CLI TRACE ", + file, + ":", + fmt.Sprintf("%v", line), + " ", + fmt.Sprintf("(%s)", cf.Name()), + " ", + format, + }, ""), + a..., + ) +} diff --git a/vendor/github.com/urfave/cli/v3/command.go b/vendor/github.com/urfave/cli/v3/command.go new file mode 100644 index 00000000..9fa8f9dc --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/command.go @@ -0,0 +1,1296 @@ +package cli + +import ( + "bufio" + "context" + "flag" + "fmt" + "io" + "os" + "path/filepath" + "reflect" + "sort" + "strings" + "unicode" +) + +const ( + // ignoreFlagPrefix is to ignore test flags when adding flags from other packages + ignoreFlagPrefix = "test." + + commandContextKey = contextKey("cli.context") +) + +type contextKey string + +// Command contains everything needed to run an application that +// accepts a string slice of arguments such as os.Args. A given +// Command may contain Flags and sub-commands in Commands. +type Command struct { + // The name of the command + Name string `json:"name"` + // A list of aliases for the command + Aliases []string `json:"aliases"` + // A short description of the usage of this command + Usage string `json:"usage"` + // Text to override the USAGE section of help + UsageText string `json:"usageText"` + // A short description of the arguments of this command + ArgsUsage string `json:"argsUsage"` + // Version of the command + Version string `json:"version"` + // Longer explanation of how the command works + Description string `json:"description"` + // DefaultCommand is the (optional) name of a command + // to run if no command names are passed as CLI arguments. + DefaultCommand string `json:"defaultCommand"` + // The category the command is part of + Category string `json:"category"` + // List of child commands + Commands []*Command `json:"commands"` + // List of flags to parse + Flags []Flag `json:"flags"` + // Boolean to hide built-in help command and help flag + HideHelp bool `json:"hideHelp"` + // Ignored if HideHelp is true. + HideHelpCommand bool `json:"hideHelpCommand"` + // Boolean to hide built-in version flag and the VERSION section of help + HideVersion bool `json:"hideVersion"` + // Boolean to enable shell completion commands + EnableShellCompletion bool `json:"-"` + // Shell Completion generation command name + ShellCompletionCommandName string `json:"-"` + // The function to call when checking for shell command completions + ShellComplete ShellCompleteFunc `json:"-"` + // An action to execute before any subcommands are run, but after the context is ready + // If a non-nil error is returned, no subcommands are run + Before BeforeFunc `json:"-"` + // An action to execute after any subcommands are run, but after the subcommand has finished + // It is run even if Action() panics + After AfterFunc `json:"-"` + // The function to call when this command is invoked + Action ActionFunc `json:"-"` + // Execute this function if the proper command cannot be found + CommandNotFound CommandNotFoundFunc `json:"-"` + // Execute this function if a usage error occurs. + OnUsageError OnUsageErrorFunc `json:"-"` + // Execute this function when an invalid flag is accessed from the context + InvalidFlagAccessHandler InvalidFlagAccessFunc `json:"-"` + // Boolean to hide this command from help or completion + Hidden bool `json:"hidden"` + // List of all authors who contributed (string or fmt.Stringer) + // TODO: ~string | fmt.Stringer when interface unions are available + Authors []any `json:"authors"` + // Copyright of the binary if any + Copyright string `json:"copyright"` + // Reader reader to write input to (useful for tests) + Reader io.Reader `json:"-"` + // Writer writer to write output to + Writer io.Writer `json:"-"` + // ErrWriter writes error output + ErrWriter io.Writer `json:"-"` + // ExitErrHandler processes any error encountered while running an App before + // it is returned to the caller. If no function is provided, HandleExitCoder + // is used as the default behavior. + ExitErrHandler ExitErrHandlerFunc `json:"-"` + // Other custom info + Metadata map[string]interface{} `json:"metadata"` + // Carries a function which returns app specific info. + ExtraInfo func() map[string]string `json:"-"` + // CustomRootCommandHelpTemplate the text template for app help topic. + // cli.go uses text/template to render templates. You can + // render custom help text by setting this variable. + CustomRootCommandHelpTemplate string `json:"-"` + // SliceFlagSeparator is used to customize the separator for SliceFlag, the default is "," + SliceFlagSeparator string `json:"sliceFlagSeparator"` + // DisableSliceFlagSeparator is used to disable SliceFlagSeparator, the default is false + DisableSliceFlagSeparator bool `json:"disableSliceFlagSeparator"` + // Boolean to enable short-option handling so user can combine several + // single-character bool arguments into one + // i.e. foobar -o -v -> foobar -ov + UseShortOptionHandling bool `json:"useShortOptionHandling"` + // Enable suggestions for commands and flags + Suggest bool `json:"suggest"` + // Allows global flags set by libraries which use flag.XXXVar(...) directly + // to be parsed through this library + AllowExtFlags bool `json:"allowExtFlags"` + // Treat all flags as normal arguments if true + SkipFlagParsing bool `json:"skipFlagParsing"` + // CustomHelpTemplate the text template for the command help topic. + // cli.go uses text/template to render templates. You can + // render custom help text by setting this variable. + CustomHelpTemplate string `json:"-"` + // Use longest prefix match for commands + PrefixMatchCommands bool `json:"prefixMatchCommands"` + // Custom suggest command for matching + SuggestCommandFunc SuggestCommandFunc `json:"-"` + // Flag exclusion group + MutuallyExclusiveFlags []MutuallyExclusiveFlags `json:"mutuallyExclusiveFlags"` + // Arguments to parse for this command + Arguments []Argument `json:"arguments"` + // Whether to read arguments from stdin + // applicable to root command only + ReadArgsFromStdin bool `json:"readArgsFromStdin"` + + // categories contains the categorized commands and is populated on app startup + categories CommandCategories + // flagCategories contains the categorized flags and is populated on app startup + flagCategories FlagCategories + // flags that have been applied in current parse + appliedFlags []Flag + // The parent of this command. This value will be nil for the + // command at the root of the graph. + parent *Command + // the flag.FlagSet for this command + flagSet *flag.FlagSet + // parsed args + parsedArgs Args + // track state of error handling + isInError bool + // track state of defaults + didSetupDefaults bool + // whether in shell completion mode + shellCompletion bool +} + +// FullName returns the full name of the command. +// For commands with parents this ensures that the parent commands +// are part of the command path. +func (cmd *Command) FullName() string { + namePath := []string{} + + if cmd.parent != nil { + namePath = append(namePath, cmd.parent.FullName()) + } + + return strings.Join(append(namePath, cmd.Name), " ") +} + +func (cmd *Command) Command(name string) *Command { + for _, subCmd := range cmd.Commands { + if subCmd.HasName(name) { + return subCmd + } + } + + return nil +} + +func (cmd *Command) setupDefaults(osArgs []string) { + if cmd.didSetupDefaults { + tracef("already did setup (cmd=%[1]q)", cmd.Name) + return + } + + cmd.didSetupDefaults = true + + isRoot := cmd.parent == nil + tracef("isRoot? %[1]v (cmd=%[2]q)", isRoot, cmd.Name) + + if cmd.ShellComplete == nil { + tracef("setting default ShellComplete (cmd=%[1]q)", cmd.Name) + cmd.ShellComplete = DefaultCompleteWithFlags + } + + if cmd.Name == "" && isRoot { + name := filepath.Base(osArgs[0]) + tracef("setting cmd.Name from first arg basename (cmd=%[1]q)", name) + cmd.Name = name + } + + if cmd.Usage == "" && isRoot { + tracef("setting default Usage (cmd=%[1]q)", cmd.Name) + cmd.Usage = "A new cli application" + } + + if cmd.Version == "" { + tracef("setting HideVersion=true due to empty Version (cmd=%[1]q)", cmd.Name) + cmd.HideVersion = true + } + + if cmd.Action == nil { + tracef("setting default Action as help command action (cmd=%[1]q)", cmd.Name) + cmd.Action = helpCommandAction + } + + if cmd.Reader == nil { + tracef("setting default Reader as os.Stdin (cmd=%[1]q)", cmd.Name) + cmd.Reader = os.Stdin + } + + if cmd.Writer == nil { + tracef("setting default Writer as os.Stdout (cmd=%[1]q)", cmd.Name) + cmd.Writer = os.Stdout + } + + if cmd.ErrWriter == nil { + tracef("setting default ErrWriter as os.Stderr (cmd=%[1]q)", cmd.Name) + cmd.ErrWriter = os.Stderr + } + + if cmd.AllowExtFlags { + tracef("visiting all flags given AllowExtFlags=true (cmd=%[1]q)", cmd.Name) + // add global flags added by other packages + flag.VisitAll(func(f *flag.Flag) { + // skip test flags + if !strings.HasPrefix(f.Name, ignoreFlagPrefix) { + cmd.Flags = append(cmd.Flags, &extFlag{f}) + } + }) + } + + for _, subCmd := range cmd.Commands { + tracef("setting sub-command (cmd=%[1]q) parent as self (cmd=%[2]q)", subCmd.Name, cmd.Name) + subCmd.parent = cmd + } + + cmd.ensureHelp() + + if !cmd.HideVersion && isRoot { + tracef("appending version flag (cmd=%[1]q)", cmd.Name) + cmd.appendFlag(VersionFlag) + } + + if cmd.PrefixMatchCommands && cmd.SuggestCommandFunc == nil { + tracef("setting default SuggestCommandFunc (cmd=%[1]q)", cmd.Name) + cmd.SuggestCommandFunc = suggestCommand + } + + if cmd.EnableShellCompletion || cmd.Root().shellCompletion { + completionCommand := buildCompletionCommand() + + if cmd.ShellCompletionCommandName != "" { + tracef( + "setting completion command name (%[1]q) from "+ + "cmd.ShellCompletionCommandName (cmd=%[2]q)", + cmd.ShellCompletionCommandName, cmd.Name, + ) + completionCommand.Name = cmd.ShellCompletionCommandName + } + + tracef("appending completionCommand (cmd=%[1]q)", cmd.Name) + cmd.appendCommand(completionCommand) + } + + tracef("setting command categories (cmd=%[1]q)", cmd.Name) + cmd.categories = newCommandCategories() + + for _, subCmd := range cmd.Commands { + cmd.categories.AddCommand(subCmd.Category, subCmd) + } + + tracef("sorting command categories (cmd=%[1]q)", cmd.Name) + sort.Sort(cmd.categories.(*commandCategories)) + + tracef("setting category on mutually exclusive flags (cmd=%[1]q)", cmd.Name) + for _, grp := range cmd.MutuallyExclusiveFlags { + grp.propagateCategory() + } + + tracef("setting flag categories (cmd=%[1]q)", cmd.Name) + cmd.flagCategories = newFlagCategoriesFromFlags(cmd.allFlags()) + + if cmd.Metadata == nil { + tracef("setting default Metadata (cmd=%[1]q)", cmd.Name) + cmd.Metadata = map[string]any{} + } + + if len(cmd.SliceFlagSeparator) != 0 { + tracef("setting defaultSliceFlagSeparator from cmd.SliceFlagSeparator (cmd=%[1]q)", cmd.Name) + defaultSliceFlagSeparator = cmd.SliceFlagSeparator + } + + tracef("setting disableSliceFlagSeparator from cmd.DisableSliceFlagSeparator (cmd=%[1]q)", cmd.Name) + disableSliceFlagSeparator = cmd.DisableSliceFlagSeparator +} + +func (cmd *Command) setupCommandGraph() { + tracef("setting up command graph (cmd=%[1]q)", cmd.Name) + + for _, subCmd := range cmd.Commands { + subCmd.parent = cmd + subCmd.setupSubcommand() + subCmd.setupCommandGraph() + } +} + +func (cmd *Command) setupSubcommand() { + tracef("setting up self as sub-command (cmd=%[1]q)", cmd.Name) + + cmd.ensureHelp() + + tracef("setting command categories (cmd=%[1]q)", cmd.Name) + cmd.categories = newCommandCategories() + + for _, subCmd := range cmd.Commands { + cmd.categories.AddCommand(subCmd.Category, subCmd) + } + + tracef("sorting command categories (cmd=%[1]q)", cmd.Name) + sort.Sort(cmd.categories.(*commandCategories)) + + tracef("setting category on mutually exclusive flags (cmd=%[1]q)", cmd.Name) + for _, grp := range cmd.MutuallyExclusiveFlags { + grp.propagateCategory() + } + + tracef("setting flag categories (cmd=%[1]q)", cmd.Name) + cmd.flagCategories = newFlagCategoriesFromFlags(cmd.allFlags()) +} + +func (cmd *Command) hideHelp() bool { + tracef("hide help (cmd=%[1]q)", cmd.Name) + for c := cmd; c != nil; c = c.parent { + if c.HideHelp { + return true + } + } + + return false +} + +func (cmd *Command) ensureHelp() { + tracef("ensuring help (cmd=%[1]q)", cmd.Name) + + helpCommand := buildHelpCommand(true) + + if !cmd.hideHelp() { + if cmd.Command(helpCommand.Name) == nil { + if !cmd.HideHelpCommand { + tracef("appending helpCommand (cmd=%[1]q)", cmd.Name) + cmd.appendCommand(helpCommand) + } + } + + if HelpFlag != nil { + tracef("appending HelpFlag (cmd=%[1]q)", cmd.Name) + cmd.appendFlag(HelpFlag) + } + } +} + +func (cmd *Command) parseArgsFromStdin() ([]string, error) { + type state int + const ( + stateSearchForToken state = -1 + stateSearchForString state = 0 + ) + + st := stateSearchForToken + linenum := 1 + token := "" + args := []string{} + + breader := bufio.NewReader(cmd.Reader) + +outer: + for { + ch, _, err := breader.ReadRune() + if err == io.EOF { + switch st { + case stateSearchForToken: + if token != "--" { + args = append(args, token) + } + case stateSearchForString: + // make sure string is not empty + for _, t := range token { + if !unicode.IsSpace(t) { + args = append(args, token) + } + } + } + break outer + } + if err != nil { + return nil, err + } + switch st { + case stateSearchForToken: + if unicode.IsSpace(ch) || ch == '"' { + if ch == '\n' { + linenum++ + } + if token != "" { + // end the processing here + if token == "--" { + break outer + } + args = append(args, token) + token = "" + } + if ch == '"' { + st = stateSearchForString + } + continue + } + token += string(ch) + case stateSearchForString: + if ch != '"' { + token += string(ch) + } else { + if token != "" { + args = append(args, token) + token = "" + } + /*else { + //TODO. Should we pass in empty strings ? + }*/ + st = stateSearchForToken + } + } + } + + tracef("parsed stdin args as %v (cmd=%[2]q)", args, cmd.Name) + + return args, nil +} + +// Run is the entry point to the command graph. The positional +// arguments are parsed according to the Flag and Command +// definitions and the matching Action functions are run. +func (cmd *Command) Run(ctx context.Context, osArgs []string) (deferErr error) { + tracef("running with arguments %[1]q (cmd=%[2]q)", osArgs, cmd.Name) + cmd.setupDefaults(osArgs) + + if v, ok := ctx.Value(commandContextKey).(*Command); ok { + tracef("setting parent (cmd=%[1]q) command from context.Context value (cmd=%[2]q)", v.Name, cmd.Name) + cmd.parent = v + } + + if cmd.parent == nil { + if cmd.ReadArgsFromStdin { + if args, err := cmd.parseArgsFromStdin(); err != nil { + return err + } else { + osArgs = append(osArgs, args...) + } + } + // handle the completion flag separately from the flagset since + // completion could be attempted after a flag, but before its value was put + // on the command line. this causes the flagset to interpret the completion + // flag name as the value of the flag before it which is undesirable + // note that we can only do this because the shell autocomplete function + // always appends the completion flag at the end of the command + tracef("checking osArgs %v (cmd=%[2]q)", osArgs, cmd.Name) + cmd.shellCompletion, osArgs = checkShellCompleteFlag(cmd, osArgs) + + tracef("setting cmd.shellCompletion=%[1]v from checkShellCompleteFlag (cmd=%[2]q)", cmd.shellCompletion && cmd.EnableShellCompletion, cmd.Name) + cmd.shellCompletion = cmd.EnableShellCompletion && cmd.shellCompletion + } + + tracef("using post-checkShellCompleteFlag arguments %[1]q (cmd=%[2]q)", osArgs, cmd.Name) + + tracef("setting self as cmd in context (cmd=%[1]q)", cmd.Name) + ctx = context.WithValue(ctx, commandContextKey, cmd) + + if cmd.parent == nil { + cmd.setupCommandGraph() + } + + args, err := cmd.parseFlags(&stringSliceArgs{v: osArgs}) + + tracef("using post-parse arguments %[1]q (cmd=%[2]q)", args, cmd.Name) + + if checkCompletions(ctx, cmd) { + return nil + } + + if err != nil { + tracef("setting deferErr from %[1]q (cmd=%[2]q)", err, cmd.Name) + deferErr = err + + cmd.isInError = true + if cmd.OnUsageError != nil { + err = cmd.OnUsageError(ctx, cmd, err, cmd.parent != nil) + err = cmd.handleExitCoder(ctx, err) + return err + } + fmt.Fprintf(cmd.Root().ErrWriter, "Incorrect Usage: %s\n\n", err.Error()) + if cmd.Suggest { + if suggestion, err := cmd.suggestFlagFromError(err, ""); err == nil { + fmt.Fprintf(cmd.Root().ErrWriter, "%s", suggestion) + } + } + if !cmd.hideHelp() { + if cmd.parent == nil { + tracef("running ShowAppHelp") + if err := ShowAppHelp(cmd); err != nil { + tracef("SILENTLY IGNORING ERROR running ShowAppHelp %[1]v (cmd=%[2]q)", err, cmd.Name) + } + } else { + tracef("running ShowCommandHelp with %[1]q", cmd.Name) + if err := ShowCommandHelp(ctx, cmd, cmd.Name); err != nil { + tracef("SILENTLY IGNORING ERROR running ShowCommandHelp with %[1]q %[2]v", cmd.Name, err) + } + } + } + + return err + } + + if cmd.checkHelp() { + return helpCommandAction(ctx, cmd) + } else { + tracef("no help is wanted (cmd=%[1]q)", cmd.Name) + } + + if cmd.parent == nil && !cmd.HideVersion && checkVersion(cmd) { + ShowVersion(cmd) + return nil + } + + if cmd.After != nil && !cmd.Root().shellCompletion { + defer func() { + if err := cmd.After(ctx, cmd); err != nil { + err = cmd.handleExitCoder(ctx, err) + + if deferErr != nil { + deferErr = newMultiError(deferErr, err) + } else { + deferErr = err + } + } + }() + } + + for _, grp := range cmd.MutuallyExclusiveFlags { + if err := grp.check(cmd); err != nil { + _ = ShowSubcommandHelp(cmd) + return err + } + } + + if cmd.Before != nil && !cmd.Root().shellCompletion { + if err := cmd.Before(ctx, cmd); err != nil { + deferErr = cmd.handleExitCoder(ctx, err) + return deferErr + } + } + + tracef("running flag actions (cmd=%[1]q)", cmd.Name) + + if err := cmd.runFlagActions(ctx); err != nil { + return err + } + + var subCmd *Command + + if args.Present() { + tracef("checking positional args %[1]q (cmd=%[2]q)", args, cmd.Name) + + name := args.First() + + tracef("using first positional argument as sub-command name=%[1]q (cmd=%[2]q)", name, cmd.Name) + + if cmd.SuggestCommandFunc != nil { + name = cmd.SuggestCommandFunc(cmd.Commands, name) + } + subCmd = cmd.Command(name) + if subCmd == nil { + hasDefault := cmd.DefaultCommand != "" + isFlagName := checkStringSliceIncludes(name, cmd.FlagNames()) + + if hasDefault { + tracef("using default command=%[1]q (cmd=%[2]q)", cmd.DefaultCommand, cmd.Name) + } + + if isFlagName || hasDefault { + argsWithDefault := cmd.argsWithDefaultCommand(args) + tracef("using default command args=%[1]q (cmd=%[2]q)", argsWithDefault, cmd.Name) + if !reflect.DeepEqual(args, argsWithDefault) { + subCmd = cmd.Command(argsWithDefault.First()) + } + } + } + } else if cmd.parent == nil && cmd.DefaultCommand != "" { + tracef("no positional args present; checking default command %[1]q (cmd=%[2]q)", cmd.DefaultCommand, cmd.Name) + + if dc := cmd.Command(cmd.DefaultCommand); dc != cmd { + subCmd = dc + } + } + + if subCmd != nil { + tracef("running sub-command %[1]q with arguments %[2]q (cmd=%[3]q)", subCmd.Name, cmd.Args(), cmd.Name) + return subCmd.Run(ctx, cmd.Args().Slice()) + } + + if cmd.Action == nil { + cmd.Action = helpCommandAction + } else { + if err := cmd.checkAllRequiredFlags(); err != nil { + cmd.isInError = true + _ = ShowSubcommandHelp(cmd) + return err + } + + if len(cmd.Arguments) > 0 { + rargs := cmd.Args().Slice() + tracef("calling argparse with %[1]v", rargs) + for _, arg := range cmd.Arguments { + var err error + rargs, err = arg.Parse(rargs) + if err != nil { + tracef("calling with %[1]v (cmd=%[2]q)", err, cmd.Name) + return err + } + } + cmd.parsedArgs = &stringSliceArgs{v: rargs} + } + } + + if err := cmd.Action(ctx, cmd); err != nil { + tracef("calling handleExitCoder with %[1]v (cmd=%[2]q)", err, cmd.Name) + deferErr = cmd.handleExitCoder(ctx, err) + } + + tracef("returning deferErr (cmd=%[1]q) %[2]q", cmd.Name, deferErr) + return deferErr +} + +func (cmd *Command) checkHelp() bool { + tracef("checking if help is wanted (cmd=%[1]q)", cmd.Name) + + if HelpFlag == nil { + return false + } + + for _, name := range HelpFlag.Names() { + if cmd.Bool(name) { + return true + } + } + + return false +} + +func (cmd *Command) newFlagSet() (*flag.FlagSet, error) { + allFlags := cmd.allFlags() + + cmd.appliedFlags = append(cmd.appliedFlags, allFlags...) + + tracef("making new flag set (cmd=%[1]q)", cmd.Name) + + return newFlagSet(cmd.Name, allFlags) +} + +func (cmd *Command) allFlags() []Flag { + var flags []Flag + flags = append(flags, cmd.Flags...) + for _, grpf := range cmd.MutuallyExclusiveFlags { + for _, f1 := range grpf.Flags { + flags = append(flags, f1...) + } + } + return flags +} + +// useShortOptionHandling traverses Lineage() for *any* ancestors +// with UseShortOptionHandling +func (cmd *Command) useShortOptionHandling() bool { + for _, pCmd := range cmd.Lineage() { + if pCmd.UseShortOptionHandling { + return true + } + } + + return false +} + +func (cmd *Command) suggestFlagFromError(err error, commandName string) (string, error) { + fl, parseErr := flagFromError(err) + if parseErr != nil { + return "", err + } + + flags := cmd.Flags + hideHelp := cmd.hideHelp() + + if commandName != "" { + subCmd := cmd.Command(commandName) + if subCmd == nil { + return "", err + } + flags = subCmd.Flags + hideHelp = hideHelp || subCmd.HideHelp + } + + suggestion := SuggestFlag(flags, fl, hideHelp) + if len(suggestion) == 0 { + return "", err + } + + return fmt.Sprintf(SuggestDidYouMeanTemplate, suggestion) + "\n\n", nil +} + +func (cmd *Command) parseFlags(args Args) (Args, error) { + tracef("parsing flags from arguments %[1]q (cmd=%[2]q)", args, cmd.Name) + + cmd.parsedArgs = nil + if v, err := cmd.newFlagSet(); err != nil { + return args, err + } else { + cmd.flagSet = v + } + + if cmd.SkipFlagParsing { + tracef("skipping flag parsing (cmd=%[1]q)", cmd.Name) + + return cmd.Args(), cmd.flagSet.Parse(append([]string{"--"}, args.Tail()...)) + } + + tracef("walking command lineage for persistent flags (cmd=%[1]q)", cmd.Name) + + for pCmd := cmd.parent; pCmd != nil; pCmd = pCmd.parent { + tracef( + "checking ancestor command=%[1]q for persistent flags (cmd=%[2]q)", + pCmd.Name, cmd.Name, + ) + + for _, fl := range pCmd.Flags { + flNames := fl.Names() + + pfl, ok := fl.(LocalFlag) + if !ok || pfl.IsLocal() { + tracef("skipping non-persistent flag %[1]q (cmd=%[2]q)", flNames, cmd.Name) + continue + } + + tracef( + "checking for applying persistent flag=%[1]q pCmd=%[2]q (cmd=%[3]q)", + flNames, pCmd.Name, cmd.Name, + ) + + applyPersistentFlag := true + + cmd.flagSet.VisitAll(func(f *flag.Flag) { + for _, name := range flNames { + if name == f.Name { + applyPersistentFlag = false + break + } + } + }) + + if !applyPersistentFlag { + tracef("not applying as persistent flag=%[1]q (cmd=%[2]q)", flNames, cmd.Name) + + continue + } + + tracef("applying as persistent flag=%[1]q (cmd=%[2]q)", flNames, cmd.Name) + + if err := fl.Apply(cmd.flagSet); err != nil { + return cmd.Args(), err + } + + tracef("appending to applied flags flag=%[1]q (cmd=%[2]q)", flNames, cmd.Name) + cmd.appliedFlags = append(cmd.appliedFlags, fl) + } + } + + tracef("parsing flags iteratively tail=%[1]q (cmd=%[2]q)", args.Tail(), cmd.Name) + defer tracef("done parsing flags (cmd=%[1]q)", cmd.Name) + + rargs := args.Tail() + posArgs := []string{} + for { + tracef("rearrange:1 (cmd=%[1]q) %[2]q", cmd.Name, rargs) + for { + tracef("rearrange:2 (cmd=%[1]q) %[2]q %[3]q", cmd.Name, posArgs, rargs) + + // no more args to parse. Break out of inner loop + if len(rargs) == 0 { + break + } + + if strings.TrimSpace(rargs[0]) == "" { + break + } + + // stop parsing once we see a "--" + if rargs[0] == "--" { + posArgs = append(posArgs, rargs...) + cmd.parsedArgs = &stringSliceArgs{posArgs} + return cmd.parsedArgs, nil + } + + // let flagset parse this + if rargs[0][0] == '-' { + break + } + + tracef("rearrange-3 (cmd=%[1]q) check %[2]q", cmd.Name, rargs[0]) + + // if there is a command by that name let the command handle the + // rest of the parsing + if cmd.Command(rargs[0]) != nil { + posArgs = append(posArgs, rargs...) + cmd.parsedArgs = &stringSliceArgs{posArgs} + return cmd.parsedArgs, nil + } + + posArgs = append(posArgs, rargs[0]) + + // if this is the sole argument then + // break from inner loop + if len(rargs) == 1 { + rargs = []string{} + break + } + + rargs = rargs[1:] + } + if err := parseIter(cmd.flagSet, cmd, rargs, cmd.Root().shellCompletion); err != nil { + posArgs = append(posArgs, cmd.flagSet.Args()...) + tracef("returning-1 (cmd=%[1]q) args %[2]q", cmd.Name, posArgs) + cmd.parsedArgs = &stringSliceArgs{posArgs} + return cmd.parsedArgs, err + } + tracef("rearrange-4 (cmd=%[1]q) check %[2]q", cmd.Name, cmd.flagSet.Args()) + rargs = cmd.flagSet.Args() + if len(rargs) == 0 || strings.TrimSpace(rargs[0]) == "" || rargs[0] == "-" { + break + } + } + + posArgs = append(posArgs, cmd.flagSet.Args()...) + tracef("returning-2 (cmd=%[1]q) args %[2]q", cmd.Name, posArgs) + cmd.parsedArgs = &stringSliceArgs{posArgs} + return cmd.parsedArgs, nil +} + +// Names returns the names including short names and aliases. +func (cmd *Command) Names() []string { + return append([]string{cmd.Name}, cmd.Aliases...) +} + +// HasName returns true if Command.Name matches given name +func (cmd *Command) HasName(name string) bool { + for _, n := range cmd.Names() { + if n == name { + return true + } + } + + return false +} + +// VisibleCategories returns a slice of categories and commands that are +// Hidden=false +func (cmd *Command) VisibleCategories() []CommandCategory { + ret := []CommandCategory{} + for _, category := range cmd.categories.Categories() { + if visible := func() CommandCategory { + if len(category.VisibleCommands()) > 0 { + return category + } + return nil + }(); visible != nil { + ret = append(ret, visible) + } + } + return ret +} + +// VisibleCommands returns a slice of the Commands with Hidden=false +func (cmd *Command) VisibleCommands() []*Command { + var ret []*Command + for _, command := range cmd.Commands { + if !command.Hidden { + ret = append(ret, command) + } + } + return ret +} + +// VisibleFlagCategories returns a slice containing all the visible flag categories with the flags they contain +func (cmd *Command) VisibleFlagCategories() []VisibleFlagCategory { + if cmd.flagCategories == nil { + cmd.flagCategories = newFlagCategoriesFromFlags(cmd.allFlags()) + } + return cmd.flagCategories.VisibleCategories() +} + +// VisibleFlags returns a slice of the Flags with Hidden=false +func (cmd *Command) VisibleFlags() []Flag { + return visibleFlags(cmd.allFlags()) +} + +func (cmd *Command) appendFlag(fl Flag) { + if !hasFlag(cmd.Flags, fl) { + cmd.Flags = append(cmd.Flags, fl) + } +} + +// VisiblePersistentFlags returns a slice of [LocalFlag] with Persistent=true and Hidden=false. +func (cmd *Command) VisiblePersistentFlags() []Flag { + var flags []Flag + for _, fl := range cmd.Root().Flags { + pfl, ok := fl.(LocalFlag) + if !ok || pfl.IsLocal() { + continue + } + flags = append(flags, fl) + } + return visibleFlags(flags) +} + +func (cmd *Command) appendCommand(aCmd *Command) { + if !hasCommand(cmd.Commands, aCmd) { + aCmd.parent = cmd + cmd.Commands = append(cmd.Commands, aCmd) + } +} + +func (cmd *Command) handleExitCoder(ctx context.Context, err error) error { + if cmd.parent != nil { + return cmd.parent.handleExitCoder(ctx, err) + } + + if cmd.ExitErrHandler != nil { + cmd.ExitErrHandler(ctx, cmd, err) + return err + } + + HandleExitCoder(err) + return err +} + +func (cmd *Command) argsWithDefaultCommand(oldArgs Args) Args { + if cmd.DefaultCommand != "" { + rawArgs := append([]string{cmd.DefaultCommand}, oldArgs.Slice()...) + newArgs := &stringSliceArgs{v: rawArgs} + + return newArgs + } + + return oldArgs +} + +// Root returns the Command at the root of the graph +func (cmd *Command) Root() *Command { + if cmd.parent == nil { + return cmd + } + + return cmd.parent.Root() +} + +func (cmd *Command) lookupFlag(name string) Flag { + for _, pCmd := range cmd.Lineage() { + for _, f := range pCmd.Flags { + for _, n := range f.Names() { + if n == name { + tracef("flag found for name %[1]q (cmd=%[2]q)", name, cmd.Name) + return f + } + } + } + } + + tracef("flag NOT found for name %[1]q (cmd=%[2]q)", name, cmd.Name) + return nil +} + +func (cmd *Command) lookupFlagSet(name string) *flag.FlagSet { + for _, pCmd := range cmd.Lineage() { + if pCmd.flagSet == nil { + continue + } + + if f := pCmd.flagSet.Lookup(name); f != nil { + tracef("matching flag set found for name %[1]q (cmd=%[2]q)", name, cmd.Name) + return pCmd.flagSet + } + } + + tracef("matching flag set NOT found for name %[1]q (cmd=%[2]q)", name, cmd.Name) + cmd.onInvalidFlag(context.TODO(), name) + return nil +} + +func (cmd *Command) checkRequiredFlag(f Flag) (bool, string) { + if rf, ok := f.(RequiredFlag); ok && rf.IsRequired() { + flagPresent := false + flagName := "" + + for _, key := range f.Names() { + // use the first name to return since that is the + // primary flag name + if flagName == "" { + flagName = key + } + + if cmd.IsSet(strings.TrimSpace(key)) { + flagPresent = true + break + } + } + + if !flagPresent && flagName != "" { + return false, flagName + } + } + return true, "" +} + +func (cmd *Command) checkAllRequiredFlags() requiredFlagsErr { + for pCmd := cmd; pCmd != nil; pCmd = pCmd.parent { + if err := pCmd.checkRequiredFlags(); err != nil { + return err + } + } + return nil +} + +func (cmd *Command) checkRequiredFlags() requiredFlagsErr { + tracef("checking for required flags (cmd=%[1]q)", cmd.Name) + + missingFlags := []string{} + + for _, f := range cmd.appliedFlags { + if ok, name := cmd.checkRequiredFlag(f); !ok { + missingFlags = append(missingFlags, name) + } + } + + if len(missingFlags) != 0 { + tracef("found missing required flags %[1]q (cmd=%[2]q)", missingFlags, cmd.Name) + + return &errRequiredFlags{missingFlags: missingFlags} + } + + tracef("all required flags set (cmd=%[1]q)", cmd.Name) + + return nil +} + +func (cmd *Command) onInvalidFlag(ctx context.Context, name string) { + for cmd != nil { + if cmd.InvalidFlagAccessHandler != nil { + cmd.InvalidFlagAccessHandler(ctx, cmd, name) + break + } + cmd = cmd.parent + } +} + +// NumFlags returns the number of flags set +func (cmd *Command) NumFlags() int { + return cmd.flagSet.NFlag() +} + +// Set sets a context flag to a value. +func (cmd *Command) Set(name, value string) error { + if fs := cmd.lookupFlagSet(name); fs != nil { + return fs.Set(name, value) + } + + return fmt.Errorf("no such flag -%s", name) +} + +// IsSet determines if the flag was actually set +func (cmd *Command) IsSet(name string) bool { + flSet := cmd.lookupFlagSet(name) + + if flSet == nil { + return false + } + + isSet := false + + flSet.Visit(func(f *flag.Flag) { + if f.Name == name { + isSet = true + } + }) + + if isSet { + tracef("flag with name %[1]q found via flag set lookup (cmd=%[2]q)", name, cmd.Name) + return true + } + + fl := cmd.lookupFlag(name) + if fl == nil { + tracef("flag with name %[1]q NOT found; assuming not set (cmd=%[2]q)", name, cmd.Name) + return false + } + + isSet = fl.IsSet() + if isSet { + tracef("flag with name %[1]q is set (cmd=%[2]q)", name, cmd.Name) + } else { + tracef("flag with name %[1]q is NOT set (cmd=%[2]q)", name, cmd.Name) + } + + return isSet +} + +// LocalFlagNames returns a slice of flag names used in this +// command. +func (cmd *Command) LocalFlagNames() []string { + names := []string{} + + cmd.flagSet.Visit(makeFlagNameVisitor(&names)) + + // Check the flags which have been set via env or file + for _, f := range cmd.Flags { + if f.IsSet() { + names = append(names, f.Names()...) + } + } + + // Sort out the duplicates since flag could be set via multiple + // paths + m := map[string]struct{}{} + uniqNames := []string{} + + for _, name := range names { + if _, ok := m[name]; !ok { + m[name] = struct{}{} + uniqNames = append(uniqNames, name) + } + } + + return uniqNames +} + +// FlagNames returns a slice of flag names used by the this command +// and all of its parent commands. +func (cmd *Command) FlagNames() []string { + names := cmd.LocalFlagNames() + + if cmd.parent != nil { + names = append(cmd.parent.FlagNames(), names...) + } + + return names +} + +// Lineage returns *this* command and all of its ancestor commands +// in order from child to parent +func (cmd *Command) Lineage() []*Command { + lineage := []*Command{cmd} + + if cmd.parent != nil { + lineage = append(lineage, cmd.parent.Lineage()...) + } + + return lineage +} + +// Count returns the num of occurrences of this flag +func (cmd *Command) Count(name string) int { + if fs := cmd.lookupFlagSet(name); fs != nil { + if cf, ok := fs.Lookup(name).Value.(Countable); ok { + return cf.Count() + } + } + return 0 +} + +// Value returns the value of the flag corresponding to `name` +func (cmd *Command) Value(name string) interface{} { + if fs := cmd.lookupFlagSet(name); fs != nil { + tracef("value found for name %[1]q (cmd=%[2]q)", name, cmd.Name) + return fs.Lookup(name).Value.(flag.Getter).Get() + } + + tracef("value NOT found for name %[1]q (cmd=%[2]q)", name, cmd.Name) + return nil +} + +// Args returns the command line arguments associated with the +// command. +func (cmd *Command) Args() Args { + if cmd.parsedArgs != nil { + return cmd.parsedArgs + } + return &stringSliceArgs{v: cmd.flagSet.Args()} +} + +// NArg returns the number of the command line arguments. +func (cmd *Command) NArg() int { + return cmd.Args().Len() +} + +func hasCommand(commands []*Command, command *Command) bool { + for _, existing := range commands { + if command == existing { + return true + } + } + + return false +} + +func (cmd *Command) runFlagActions(ctx context.Context) error { + for _, fl := range cmd.appliedFlags { + isSet := false + + // check only local flagset for running local flag actions + for _, name := range fl.Names() { + cmd.flagSet.Visit(func(f *flag.Flag) { + if f.Name == name { + isSet = true + } + }) + if isSet { + break + } + } + + // If the flag hasnt been set on cmd line then we need to further + // check if it has been set via other means. If however it has + // been set by other means but it is persistent(and not set via current cmd) + // do not run the flag action + if !isSet { + if !fl.IsSet() { + continue + } + if pf, ok := fl.(LocalFlag); ok && !pf.IsLocal() { + continue + } + } + + if af, ok := fl.(ActionableFlag); ok { + if err := af.RunAction(ctx, cmd); err != nil { + return err + } + } + } + + return nil +} + +func checkStringSliceIncludes(want string, sSlice []string) bool { + found := false + for _, s := range sSlice { + if want == s { + found = true + break + } + } + + return found +} + +func makeFlagNameVisitor(names *[]string) func(*flag.Flag) { + return func(f *flag.Flag) { + nameParts := strings.Split(f.Name, ",") + name := strings.TrimSpace(nameParts[0]) + + for _, part := range nameParts { + part = strings.TrimSpace(part) + if len(part) > len(name) { + name = part + } + } + + if name != "" { + *names = append(*names, name) + } + } +} diff --git a/vendor/github.com/urfave/cli/v3/completion.go b/vendor/github.com/urfave/cli/v3/completion.go new file mode 100644 index 00000000..2319a815 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/completion.go @@ -0,0 +1,68 @@ +package cli + +import ( + "context" + "embed" + "fmt" + "sort" +) + +const ( + completionCommandName = "generate-completion" +) + +var ( + //go:embed autocomplete + autoCompleteFS embed.FS + + shellCompletions = map[string]renderCompletion{ + "bash": getCompletion("autocomplete/bash_autocomplete"), + "ps": getCompletion("autocomplete/powershell_autocomplete.ps1"), + "zsh": getCompletion("autocomplete/zsh_autocomplete"), + "fish": func(c *Command) (string, error) { + return c.ToFishCompletion() + }, + } +) + +type renderCompletion func(*Command) (string, error) + +func getCompletion(s string) renderCompletion { + return func(c *Command) (string, error) { + b, err := autoCompleteFS.ReadFile(s) + return string(b), err + } +} + +func buildCompletionCommand() *Command { + return &Command{ + Name: completionCommandName, + Hidden: true, + Action: completionCommandAction, + } +} + +func completionCommandAction(ctx context.Context, cmd *Command) error { + var shells []string + for k := range shellCompletions { + shells = append(shells, k) + } + + sort.Strings(shells) + + if cmd.Args().Len() == 0 { + return Exit(fmt.Sprintf("no shell provided for completion command. available shells are %+v", shells), 1) + } + s := cmd.Args().First() + + if rc, ok := shellCompletions[s]; !ok { + return Exit(fmt.Sprintf("unknown shell %s, available shells are %+v", s, shells), 1) + } else if c, err := rc(cmd); err != nil { + return Exit(err, 1) + } else { + if _, err = cmd.Writer.Write([]byte(c)); err != nil { + return Exit(err, 1) + } + } + return nil +} diff --git a/vendor/github.com/urfave/cli/v2/errors.go b/vendor/github.com/urfave/cli/v3/errors.go similarity index 78% rename from vendor/github.com/urfave/cli/v2/errors.go rename to vendor/github.com/urfave/cli/v3/errors.go index a818727d..18938e4d 100644 --- a/vendor/github.com/urfave/cli/v2/errors.go +++ b/vendor/github.com/urfave/cli/v3/errors.go @@ -41,9 +41,7 @@ func (m *multiError) Error() string { // Errors returns a copy of the errors slice func (m *multiError) Errors() []error { errs := make([]error, len(*m)) - for _, err := range *m { - errs = append(errs, err) - } + copy(errs, *m) return errs } @@ -57,8 +55,7 @@ type errRequiredFlags struct { } func (e *errRequiredFlags) Error() string { - numberOfMissingFlags := len(e.missingFlags) - if numberOfMissingFlags == 1 { + if len(e.missingFlags) == 1 { return fmt.Sprintf("Required flag %q not set", e.missingFlags[0]) } joinedMissingFlags := strings.Join(e.missingFlags, ", ") @@ -69,6 +66,38 @@ func (e *errRequiredFlags) getMissingFlags() []string { return e.missingFlags } +type mutuallyExclusiveGroup struct { + flag1Name string + flag2Name string +} + +func (e *mutuallyExclusiveGroup) Error() string { + return fmt.Sprintf("option %s cannot be set along with option %s", e.flag1Name, e.flag2Name) +} + +type mutuallyExclusiveGroupRequiredFlag struct { + flags *MutuallyExclusiveFlags +} + +func (e *mutuallyExclusiveGroupRequiredFlag) Error() string { + var missingFlags []string + for _, grpf := range e.flags.Flags { + var grpString []string + for _, f := range grpf { + grpString = append(grpString, f.Names()...) + } + if len(e.flags.Flags) == 1 { + err := errRequiredFlags{ + missingFlags: grpString, + } + return err.Error() + } + missingFlags = append(missingFlags, strings.Join(grpString, " ")) + } + + return fmt.Sprintf("one of these flags needs to be provided: %s", strings.Join(missingFlags, ", ")) +} + // ErrorFormatter is the interface that will suitably format the error output type ErrorFormatter interface { Format(s fmt.State, verb rune) @@ -86,13 +115,6 @@ type exitError struct { err error } -// NewExitError calls Exit to create a new ExitCoder. -// -// Deprecated: This function is a duplicate of Exit and will eventually be removed. -func NewExitError(message interface{}, exitCode int) ExitCoder { - return Exit(message, exitCode) -} - // Exit wraps a message and exit code into an error, which by default is // handled with a call to os.Exit during default error handling. // @@ -176,3 +198,12 @@ func handleMultiError(multiErr MultiError) int { } return code } + +type typeError[T any] struct { + other any +} + +func (te *typeError[T]) Error() string { + var t T + return fmt.Sprintf("Expected type %T got instead %T", t, te.other) +} diff --git a/vendor/github.com/urfave/cli/v2/fish.go b/vendor/github.com/urfave/cli/v3/fish.go similarity index 59% rename from vendor/github.com/urfave/cli/v2/fish.go rename to vendor/github.com/urfave/cli/v3/fish.go index 909dfc5a..b2b6ec93 100644 --- a/vendor/github.com/urfave/cli/v2/fish.go +++ b/vendor/github.com/urfave/cli/v3/fish.go @@ -10,21 +10,21 @@ import ( // ToFishCompletion creates a fish completion string for the `*App` // The function errors if either parsing or writing of the string fails. -func (a *App) ToFishCompletion() (string, error) { +func (cmd *Command) ToFishCompletion() (string, error) { var w bytes.Buffer - if err := a.writeFishCompletionTemplate(&w); err != nil { + if err := cmd.writeFishCompletionTemplate(&w); err != nil { return "", err } return w.String(), nil } -type fishCompletionTemplate struct { - App *App +type fishCommandCompletionTemplate struct { + Command *Command Completions []string AllCommands []string } -func (a *App) writeFishCompletionTemplate(w io.Writer) error { +func (cmd *Command) writeFishCompletionTemplate(w io.Writer) error { const name = "cli" t, err := template.New(name).Parse(FishCompletionTemplate) if err != nil { @@ -33,38 +33,38 @@ func (a *App) writeFishCompletionTemplate(w io.Writer) error { allCommands := []string{} // Add global flags - completions := a.prepareFishFlags(a.VisibleFlags(), allCommands) + completions := cmd.prepareFishFlags(cmd.VisibleFlags(), allCommands) // Add help flag - if !a.HideHelp { + if !cmd.HideHelp { completions = append( completions, - a.prepareFishFlags([]Flag{HelpFlag}, allCommands)..., + cmd.prepareFishFlags([]Flag{HelpFlag}, allCommands)..., ) } // Add version flag - if !a.HideVersion { + if !cmd.HideVersion { completions = append( completions, - a.prepareFishFlags([]Flag{VersionFlag}, allCommands)..., + cmd.prepareFishFlags([]Flag{VersionFlag}, allCommands)..., ) } // Add commands and their flags completions = append( completions, - a.prepareFishCommands(a.VisibleCommands(), &allCommands, []string{})..., + cmd.prepareFishCommands(cmd.VisibleCommands(), &allCommands, []string{})..., ) - return t.ExecuteTemplate(w, name, &fishCompletionTemplate{ - App: a, + return t.ExecuteTemplate(w, name, &fishCommandCompletionTemplate{ + Command: cmd, Completions: completions, AllCommands: allCommands, }) } -func (a *App) prepareFishCommands(commands []*Command, allCommands *[]string, previousCommands []string) []string { +func (cmd *Command) prepareFishCommands(commands []*Command, allCommands *[]string, previousCommands []string) []string { completions := []string{} for _, command := range commands { if command.Hidden { @@ -74,8 +74,8 @@ func (a *App) prepareFishCommands(commands []*Command, allCommands *[]string, pr var completion strings.Builder completion.WriteString(fmt.Sprintf( "complete -r -c %s -n '%s' -a '%s'", - a.Name, - a.fishSubcommandHelper(previousCommands), + cmd.Name, + cmd.fishSubcommandHelper(previousCommands), strings.Join(command.Names(), " "), )) @@ -87,7 +87,7 @@ func (a *App) prepareFishCommands(commands []*Command, allCommands *[]string, pr if !command.HideHelp { completions = append( completions, - a.prepareFishFlags([]Flag{HelpFlag}, command.Names())..., + cmd.prepareFishFlags([]Flag{HelpFlag}, command.Names())..., ) } @@ -95,15 +95,15 @@ func (a *App) prepareFishCommands(commands []*Command, allCommands *[]string, pr completions = append(completions, completion.String()) completions = append( completions, - a.prepareFishFlags(command.VisibleFlags(), command.Names())..., + cmd.prepareFishFlags(command.VisibleFlags(), command.Names())..., ) // recursively iterate subcommands - if len(command.Subcommands) > 0 { + if len(command.Commands) > 0 { completions = append( completions, - a.prepareFishCommands( - command.Subcommands, allCommands, command.Names(), + cmd.prepareFishCommands( + command.Commands, allCommands, command.Names(), )..., ) } @@ -112,24 +112,19 @@ func (a *App) prepareFishCommands(commands []*Command, allCommands *[]string, pr return completions } -func (a *App) prepareFishFlags(flags []Flag, previousCommands []string) []string { +func (cmd *Command) prepareFishFlags(flags []Flag, previousCommands []string) []string { completions := []string{} for _, f := range flags { - flag, ok := f.(DocGenerationFlag) - if !ok { - continue - } - completion := &strings.Builder{} completion.WriteString(fmt.Sprintf( "complete -c %s -n '%s'", - a.Name, - a.fishSubcommandHelper(previousCommands), + cmd.Name, + cmd.fishSubcommandHelper(previousCommands), )) fishAddFileFlag(f, completion) - for idx, opt := range flag.Names() { + for idx, opt := range f.Names() { if idx == 0 { completion.WriteString(fmt.Sprintf( " -l %s", strings.TrimSpace(opt), @@ -138,17 +133,18 @@ func (a *App) prepareFishFlags(flags []Flag, previousCommands []string) []string completion.WriteString(fmt.Sprintf( " -s %s", strings.TrimSpace(opt), )) - } } - if flag.TakesValue() { - completion.WriteString(" -r") - } + if flag, ok := f.(DocGenerationFlag); ok { + if flag.TakesValue() { + completion.WriteString(" -r") + } - if flag.GetUsage() != "" { - completion.WriteString(fmt.Sprintf(" -d '%s'", - escapeSingleQuotes(flag.GetUsage()))) + if flag.GetUsage() != "" { + completion.WriteString(fmt.Sprintf(" -d '%s'", + escapeSingleQuotes(flag.GetUsage()))) + } } completions = append(completions, completion.String()) @@ -159,10 +155,6 @@ func (a *App) prepareFishFlags(flags []Flag, previousCommands []string) []string func fishAddFileFlag(flag Flag, completion *strings.Builder) { switch f := flag.(type) { - case *GenericFlag: - if f.TakesFile { - return - } case *StringFlag: if f.TakesFile { return @@ -171,16 +163,12 @@ func fishAddFileFlag(flag Flag, completion *strings.Builder) { if f.TakesFile { return } - case *PathFlag: - if f.TakesFile { - return - } } completion.WriteString(" -f") } -func (a *App) fishSubcommandHelper(allCommands []string) string { - fishHelper := fmt.Sprintf("__fish_%s_no_subcommand", a.Name) +func (cmd *Command) fishSubcommandHelper(allCommands []string) string { + fishHelper := fmt.Sprintf("__fish_%s_no_subcommand", cmd.Name) if len(allCommands) > 0 { fishHelper = fmt.Sprintf( "__fish_seen_subcommand_from %s", @@ -188,7 +176,6 @@ func (a *App) fishSubcommandHelper(allCommands []string) string { ) } return fishHelper - } func escapeSingleQuotes(input string) string { diff --git a/vendor/github.com/urfave/cli/v2/flag.go b/vendor/github.com/urfave/cli/v3/flag.go similarity index 66% rename from vendor/github.com/urfave/cli/v2/flag.go rename to vendor/github.com/urfave/cli/v3/flag.go index 4d04de3d..420ea5e9 100644 --- a/vendor/github.com/urfave/cli/v2/flag.go +++ b/vendor/github.com/urfave/cli/v3/flag.go @@ -1,7 +1,7 @@ package cli import ( - "errors" + "context" "flag" "fmt" "io" @@ -9,15 +9,15 @@ import ( "regexp" "runtime" "strings" - "syscall" "time" ) const defaultPlaceholder = "value" -const ( - defaultSliceFlagSeparator = "," - disableSliceFlagSeparator = false +var ( + defaultSliceFlagSeparator = "," + defaultMapFlagKeyValueSeparator = "=" + disableSliceFlagSeparator = false ) var ( @@ -26,28 +26,30 @@ var ( commaWhitespace = regexp.MustCompile("[, ]+.*") ) -// BashCompletionFlag enables bash-completion for all commands and subcommands -var BashCompletionFlag Flag = &BoolFlag{ - Name: "generate-bash-completion", +// GenerateShellCompletionFlag enables shell completion +var GenerateShellCompletionFlag Flag = &BoolFlag{ + Name: "generate-shell-completion", Hidden: true, } // VersionFlag prints the version for the application var VersionFlag Flag = &BoolFlag{ - Name: "version", - Aliases: []string{"v"}, - Usage: "print the version", - DisableDefaultText: true, + Name: "version", + Aliases: []string{"v"}, + Usage: "print the version", + HideDefault: true, + Local: true, } // HelpFlag prints the help for all commands and subcommands. // Set to nil to disable the flag. The subcommand // will still be added unless HideHelp or HideHelpCommand is set to true. var HelpFlag Flag = &BoolFlag{ - Name: "help", - Aliases: []string{"h"}, - Usage: "show help", - DisableDefaultText: true, + Name: "help", + Aliases: []string{"h"}, + Usage: "show help", + HideDefault: true, + Local: true, } // FlagStringer converts a flag definition to a string. This is used by help @@ -93,8 +95,7 @@ func (f FlagsByName) Swap(i, j int) { // ActionableFlag is an interface that wraps Flag interface and RunAction operation. type ActionableFlag interface { - Flag - RunAction(*Context) error + RunAction(context.Context, *Command) error } // Flag is a common interface related to parsing flags in cli. @@ -102,24 +103,26 @@ type ActionableFlag interface { // this interface be implemented. type Flag interface { fmt.Stringer + // Apply Flag settings to the given flag set Apply(*flag.FlagSet) error + + // All possible names for this flag Names() []string + + // Whether the flag has been set or not IsSet() bool } // RequiredFlag is an interface that allows us to mark flags as required // it allows flags required flags to be backwards compatible with the Flag interface type RequiredFlag interface { - Flag - + // whether the flag is a required flag or not IsRequired() bool } // DocGenerationFlag is an interface that allows documentation generation for the flag type DocGenerationFlag interface { - Flag - // TakesValue returns true if the flag takes a value, otherwise false TakesValue() bool @@ -135,30 +138,18 @@ type DocGenerationFlag interface { // GetEnvVars returns the env vars for this flag GetEnvVars() []string + + // IsDefaultVisible returns whether the default value should be shown in + // help text + IsDefaultVisible() bool } -// DocGenerationSliceFlag extends DocGenerationFlag for slice-based flags. -type DocGenerationSliceFlag interface { +// DocGenerationMultiValueFlag extends DocGenerationFlag for slice/map based flags. +type DocGenerationMultiValueFlag interface { DocGenerationFlag - // IsSliceFlag returns true for flags that can be given multiple times. - IsSliceFlag() bool -} - -// VisibleFlag is an interface that allows to check if a flag is visible -type VisibleFlag interface { - Flag - - // IsVisible returns true if the flag is not hidden, otherwise false - IsVisible() bool -} - -// CategorizableFlag is an interface that allows us to potentially -// use a flag in a categorized representation. -type CategorizableFlag interface { - VisibleFlag - - GetCategory() string + // IsMultiValueFlag returns true for flags that can be given multiple times. + IsMultiValueFlag() bool } // Countable is an interface to enable detection of flag values which support @@ -167,63 +158,47 @@ type Countable interface { Count() int } -func flagSet(name string, flags []Flag, spec separatorSpec) (*flag.FlagSet, error) { +// VisibleFlag is an interface that allows to check if a flag is visible +type VisibleFlag interface { + // IsVisible returns true if the flag is not hidden, otherwise false + IsVisible() bool +} + +// CategorizableFlag is an interface that allows us to potentially +// use a flag in a categorized representation. +type CategorizableFlag interface { + // Returns the category of the flag + GetCategory() string + + // Sets the category of the flag + SetCategory(string) +} + +// LocalFlag is an interface to enable detection of flags which are local +// to current command +type LocalFlag interface { + IsLocal() bool +} + +// IsDefaultVisible returns true if the flag is not hidden, otherwise false +func (f *FlagBase[T, C, V]) IsDefaultVisible() bool { + return !f.HideDefault +} + +func newFlagSet(name string, flags []Flag) (*flag.FlagSet, error) { set := flag.NewFlagSet(name, flag.ContinueOnError) for _, f := range flags { - if c, ok := f.(customizedSeparator); ok { - c.WithSeparatorSpec(spec) - } if err := f.Apply(set); err != nil { return nil, err } } + set.SetOutput(io.Discard) + return set, nil } -func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) { - switch ff.Value.(type) { - case Serializer: - _ = set.Set(name, ff.Value.(Serializer).Serialize()) - default: - _ = set.Set(name, ff.Value.String()) - } -} - -func normalizeFlags(flags []Flag, set *flag.FlagSet) error { - visited := make(map[string]bool) - set.Visit(func(f *flag.Flag) { - visited[f.Name] = true - }) - for _, f := range flags { - parts := f.Names() - if len(parts) == 1 { - continue - } - var ff *flag.Flag - for _, name := range parts { - name = strings.Trim(name, " ") - if visited[name] { - if ff != nil { - return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name) - } - ff = set.Lookup(name) - } - } - if ff == nil { - continue - } - for _, name := range parts { - name = strings.Trim(name, " ") - if !visited[name] { - copyFlag(name, ff, set) - } - } - } - return nil -} - func visibleFlags(fl []Flag) []Flag { var visible []Flag for _, f := range fl { @@ -342,20 +317,19 @@ func stringifyFlag(f Flag) string { defaultValueString := "" - // set default text for all flags except bool flags - // for bool flags display default text if DisableDefaultText is not - // set - if bf, ok := f.(*BoolFlag); !ok || !bf.DisableDefaultText { - if s := df.GetDefaultText(); s != "" { + // don't print default text for required flags + if rf, ok := f.(RequiredFlag); !ok || !rf.IsRequired() { + isVisible := df.IsDefaultVisible() + if s := df.GetDefaultText(); isVisible && s != "" { defaultValueString = fmt.Sprintf(formatDefault("%s"), s) } } usageWithDefault := strings.TrimSpace(usage + defaultValueString) - pn := prefixedNames(df.Names(), placeholder) - sliceFlag, ok := f.(DocGenerationSliceFlag) - if ok && sliceFlag.IsSliceFlag() { + pn := prefixedNames(f.Names(), placeholder) + sliceFlag, ok := f.(DocGenerationMultiValueFlag) + if ok && sliceFlag.IsMultiValueFlag() { pn = pn + " [ " + pn + " ]" } @@ -372,48 +346,10 @@ func hasFlag(flags []Flag, fl Flag) bool { return false } -// Return the first value from a list of environment variables and files -// (which may or may not exist), a description of where the value was found, -// and a boolean which is true if a value was found. -func flagFromEnvOrFile(envVars []string, filePath string) (value string, fromWhere string, found bool) { - for _, envVar := range envVars { - envVar = strings.TrimSpace(envVar) - if value, found := syscall.Getenv(envVar); found { - return value, fmt.Sprintf("environment variable %q", envVar), true - } - } - for _, fileVar := range strings.Split(filePath, ",") { - if fileVar != "" { - if data, err := os.ReadFile(fileVar); err == nil { - return string(data), fmt.Sprintf("file %q", filePath), true - } - } - } - return "", "", false -} - -type customizedSeparator interface { - WithSeparatorSpec(separatorSpec) -} - -type separatorSpec struct { - sep string - disabled bool - customized bool -} - -func (s separatorSpec) flagSplitMultiValues(val string) []string { - var ( - disabled bool = s.disabled - sep string = s.sep - ) - if !s.customized { - disabled = disableSliceFlagSeparator - sep = defaultSliceFlagSeparator - } - if disabled { +func flagSplitMultiValues(val string) []string { + if disableSliceFlagSeparator { return []string{val} } - return strings.Split(val, sep) + return strings.Split(val, defaultSliceFlagSeparator) } diff --git a/vendor/github.com/urfave/cli/v3/flag_bool.go b/vendor/github.com/urfave/cli/v3/flag_bool.go new file mode 100644 index 00000000..4ad81d58 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_bool.go @@ -0,0 +1,87 @@ +package cli + +import ( + "errors" + "strconv" +) + +type BoolFlag = FlagBase[bool, BoolConfig, boolValue] + +// BoolConfig defines the configuration for bool flags +type BoolConfig struct { + Count *int +} + +// boolValue needs to implement the boolFlag internal interface in flag +// to be able to capture bool fields and values +// +// type boolFlag interface { +// Value +// IsBoolFlag() bool +// } +type boolValue struct { + destination *bool + count *int +} + +func (cmd *Command) Bool(name string) bool { + if v, ok := cmd.Value(name).(bool); ok { + tracef("bool available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + return v + } + + tracef("bool NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return false +} + +// Below functions are to satisfy the ValueCreator interface + +// Create creates the bool value +func (b boolValue) Create(val bool, p *bool, c BoolConfig) Value { + *p = val + if c.Count == nil { + c.Count = new(int) + } + return &boolValue{ + destination: p, + count: c.Count, + } +} + +// ToString formats the bool value +func (b boolValue) ToString(value bool) string { + return strconv.FormatBool(value) +} + +// Below functions are to satisfy the flag.Value interface + +func (b *boolValue) Set(s string) error { + v, err := strconv.ParseBool(s) + if err != nil { + err = errors.New("parse error") + return err + } + *b.destination = v + if b.count != nil { + *b.count = *b.count + 1 + } + return err +} + +func (b *boolValue) Get() interface{} { return *b.destination } + +func (b *boolValue) String() string { + if b.destination != nil { + return strconv.FormatBool(*b.destination) + } + return strconv.FormatBool(false) +} + +func (b *boolValue) IsBoolFlag() bool { return true } + +func (b *boolValue) Count() int { + if b.count != nil { + return *b.count + } + return 0 +} diff --git a/vendor/github.com/urfave/cli/v3/flag_bool_with_inverse.go b/vendor/github.com/urfave/cli/v3/flag_bool_with_inverse.go new file mode 100644 index 00000000..00871d61 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_bool_with_inverse.go @@ -0,0 +1,194 @@ +package cli + +import ( + "context" + "flag" + "fmt" + "strings" +) + +var DefaultInverseBoolPrefix = "no-" + +type BoolWithInverseFlag struct { + // The BoolFlag which the positive and negative flags are generated from + *BoolFlag + + // The prefix used to indicate a negative value + // Default: `env` becomes `no-env` + InversePrefix string + + positiveFlag *BoolFlag + negativeFlag *BoolFlag + + // pointers obtained from the embedded bool flag + posDest *bool + posCount *int + + negDest *bool +} + +func (parent *BoolWithInverseFlag) Flags() []Flag { + return []Flag{parent.positiveFlag, parent.negativeFlag} +} + +func (parent *BoolWithInverseFlag) IsSet() bool { + return (*parent.posCount > 0) || (parent.positiveFlag.IsSet() || parent.negativeFlag.IsSet()) +} + +func (parent *BoolWithInverseFlag) Value() bool { + return *parent.posDest +} + +func (parent *BoolWithInverseFlag) RunAction(ctx context.Context, cmd *Command) error { + if *parent.negDest && *parent.posDest { + return fmt.Errorf("cannot set both flags `--%s` and `--%s`", parent.positiveFlag.Name, parent.negativeFlag.Name) + } + + if *parent.negDest { + err := cmd.Set(parent.positiveFlag.Name, "false") + if err != nil { + return err + } + } + + if parent.BoolFlag.Action != nil { + return parent.BoolFlag.Action(ctx, cmd, parent.Value()) + } + + return nil +} + +// Initialize creates a new BoolFlag that has an inverse flag +// +// consider a bool flag `--env`, there is no way to set it to false +// this function allows you to set `--env` or `--no-env` and in the command action +// it can be determined that BoolWithInverseFlag.IsSet(). +func (parent *BoolWithInverseFlag) initialize() { + child := parent.BoolFlag + + parent.negDest = new(bool) + if child.Destination != nil { + parent.posDest = child.Destination + } else { + parent.posDest = new(bool) + } + + if child.Config.Count != nil { + parent.posCount = child.Config.Count + } else { + parent.posCount = new(int) + } + + parent.positiveFlag = child + parent.positiveFlag.Destination = parent.posDest + parent.positiveFlag.Config.Count = parent.posCount + + parent.negativeFlag = &BoolFlag{ + Category: child.Category, + DefaultText: child.DefaultText, + Sources: NewValueSourceChain(child.Sources.Chain...), + Usage: child.Usage, + Required: child.Required, + Hidden: child.Hidden, + Local: child.Local, + Value: child.Value, + Destination: parent.negDest, + TakesFile: child.TakesFile, + OnlyOnce: child.OnlyOnce, + hasBeenSet: child.hasBeenSet, + applied: child.applied, + creator: boolValue{}, + value: child.value, + } + + // Set inverse names ex: --env => --no-env + parent.negativeFlag.Name = parent.inverseName() + parent.negativeFlag.Aliases = parent.inverseAliases() + + if len(child.Sources.EnvKeys()) > 0 { + sources := []ValueSource{} + + for _, envVar := range child.GetEnvVars() { + sources = append(sources, &envVarValueSource{Key: strings.ToUpper(parent.InversePrefix) + envVar}) + } + parent.negativeFlag.Sources = NewValueSourceChain(sources...) + } +} + +func (parent *BoolWithInverseFlag) inverseName() string { + if parent.InversePrefix == "" { + parent.InversePrefix = DefaultInverseBoolPrefix + } + + return parent.InversePrefix + parent.BoolFlag.Name +} + +func (parent *BoolWithInverseFlag) inversePrefix() string { + if parent.InversePrefix == "" { + return DefaultInverseBoolPrefix + } + + return parent.InversePrefix +} + +func (parent *BoolWithInverseFlag) inverseAliases() (aliases []string) { + if len(parent.BoolFlag.Aliases) > 0 { + aliases = make([]string, len(parent.BoolFlag.Aliases)) + for idx, alias := range parent.BoolFlag.Aliases { + aliases[idx] = parent.InversePrefix + alias + } + } + + return +} + +func (parent *BoolWithInverseFlag) Apply(set *flag.FlagSet) error { + if parent.positiveFlag == nil { + parent.initialize() + } + + if err := parent.positiveFlag.Apply(set); err != nil { + return err + } + + if err := parent.negativeFlag.Apply(set); err != nil { + return err + } + + return nil +} + +func (parent *BoolWithInverseFlag) Names() []string { + // Get Names when flag has not been initialized + if parent.positiveFlag == nil { + return append(parent.BoolFlag.Names(), FlagNames(parent.inverseName(), parent.inverseAliases())...) + } + + if *parent.negDest { + return parent.negativeFlag.Names() + } + + if *parent.posDest { + return parent.positiveFlag.Names() + } + + return append(parent.negativeFlag.Names(), parent.positiveFlag.Names()...) +} + +// String implements the standard Stringer interface. +// +// Example for BoolFlag{Name: "env"} +// --[no-]env (default: false) +func (parent *BoolWithInverseFlag) String() string { + out := FlagStringer(parent) + i := strings.Index(out, "\t") + + prefix := "--" + + // single character flags are prefixed with `-` instead of `--` + if len(parent.Name) == 1 { + prefix = "-" + } + + return fmt.Sprintf("%s[%s]%s%s", prefix, parent.inversePrefix(), parent.Name, out[i:]) +} diff --git a/vendor/github.com/urfave/cli/v3/flag_duration.go b/vendor/github.com/urfave/cli/v3/flag_duration.go new file mode 100644 index 00000000..37b4cb64 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_duration.go @@ -0,0 +1,47 @@ +package cli + +import ( + "fmt" + "time" +) + +type DurationFlag = FlagBase[time.Duration, NoConfig, durationValue] + +// -- time.Duration Value +type durationValue time.Duration + +// Below functions are to satisfy the ValueCreator interface + +func (d durationValue) Create(val time.Duration, p *time.Duration, c NoConfig) Value { + *p = val + return (*durationValue)(p) +} + +func (d durationValue) ToString(val time.Duration) string { + return fmt.Sprintf("%v", val) +} + +// Below functions are to satisfy the flag.Value interface + +func (d *durationValue) Set(s string) error { + v, err := time.ParseDuration(s) + if err != nil { + return err + } + *d = durationValue(v) + return err +} + +func (d *durationValue) Get() any { return time.Duration(*d) } + +func (d *durationValue) String() string { return (*time.Duration)(d).String() } + +func (cmd *Command) Duration(name string) time.Duration { + if v, ok := cmd.Value(name).(time.Duration); ok { + tracef("duration available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + return v + } + + tracef("bool NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return 0 +} diff --git a/vendor/github.com/urfave/cli/v2/flag_ext.go b/vendor/github.com/urfave/cli/v3/flag_ext.go similarity index 100% rename from vendor/github.com/urfave/cli/v2/flag_ext.go rename to vendor/github.com/urfave/cli/v3/flag_ext.go diff --git a/vendor/github.com/urfave/cli/v3/flag_float.go b/vendor/github.com/urfave/cli/v3/flag_float.go new file mode 100644 index 00000000..406b55b6 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_float.go @@ -0,0 +1,48 @@ +package cli + +import ( + "strconv" +) + +type FloatFlag = FlagBase[float64, NoConfig, floatValue] + +// -- float64 Value +type floatValue float64 + +// Below functions are to satisfy the ValueCreator interface + +func (f floatValue) Create(val float64, p *float64, c NoConfig) Value { + *p = val + return (*floatValue)(p) +} + +func (f floatValue) ToString(b float64) string { + return strconv.FormatFloat(b, 'g', -1, 64) +} + +// Below functions are to satisfy the flag.Value interface + +func (f *floatValue) Set(s string) error { + v, err := strconv.ParseFloat(s, 64) + if err != nil { + return err + } + *f = floatValue(v) + return err +} + +func (f *floatValue) Get() any { return float64(*f) } + +func (f *floatValue) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 64) } + +// Float looks up the value of a local FloatFlag, returns +// 0 if not found +func (cmd *Command) Float(name string) float64 { + if v, ok := cmd.Value(name).(float64); ok { + tracef("float available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + return v + } + + tracef("float NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return 0 +} diff --git a/vendor/github.com/urfave/cli/v3/flag_float_slice.go b/vendor/github.com/urfave/cli/v3/flag_float_slice.go new file mode 100644 index 00000000..390e466e --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_float_slice.go @@ -0,0 +1,35 @@ +package cli + +import ( + "flag" +) + +type ( + FloatSlice = SliceBase[float64, NoConfig, floatValue] + FloatSliceFlag = FlagBase[[]float64, NoConfig, FloatSlice] +) + +var NewFloatSlice = NewSliceBase[float64, NoConfig, floatValue] + +// FloatSlice looks up the value of a local FloatSliceFlag, returns +// nil if not found +func (cmd *Command) FloatSlice(name string) []float64 { + if flSet := cmd.lookupFlagSet(name); flSet != nil { + return lookupFloatSlice(name, flSet, cmd.Name) + } + + return nil +} + +func lookupFloatSlice(name string, set *flag.FlagSet, cmdName string) []float64 { + fl := set.Lookup(name) + if fl != nil { + if v, ok := fl.Value.(flag.Getter).Get().([]float64); ok { + tracef("float slice available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmdName) + return v + } + } + + tracef("float slice NOT available for flag name %[1]q (cmd=%[2]q)", name, cmdName) + return nil +} diff --git a/vendor/github.com/urfave/cli/v3/flag_impl.go b/vendor/github.com/urfave/cli/v3/flag_impl.go new file mode 100644 index 00000000..77bc5918 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_impl.go @@ -0,0 +1,286 @@ +package cli + +import ( + "context" + "flag" + "fmt" + "reflect" +) + +// Value represents a value as used by cli. +// For now it implements the golang flag.Value interface +type Value interface { + flag.Value + flag.Getter +} + +type boolFlag interface { + IsBoolFlag() bool +} + +type fnValue struct { + fn func(string) error + isBool bool + v Value +} + +func (f *fnValue) Get() any { return f.v.Get() } +func (f *fnValue) Set(s string) error { return f.fn(s) } +func (f *fnValue) String() string { + if f.v == nil { + return "" + } + return f.v.String() +} + +func (f *fnValue) Serialize() string { + if s, ok := f.v.(Serializer); ok { + return s.Serialize() + } + return f.v.String() +} + +func (f *fnValue) IsBoolFlag() bool { return f.isBool } +func (f *fnValue) Count() int { + if s, ok := f.v.(Countable); ok { + return s.Count() + } + return 0 +} + +// ValueCreator is responsible for creating a flag.Value emulation +// as well as custom formatting +// +// T specifies the type +// C specifies the config for the type +type ValueCreator[T any, C any] interface { + Create(T, *T, C) Value + ToString(T) string +} + +// NoConfig is for flags which dont need a custom configuration +type NoConfig struct{} + +// FlagBase [T,C,VC] is a generic flag base which can be used +// as a boilerplate to implement the most common interfaces +// used by urfave/cli. +// +// T specifies the type +// C specifies the configuration required(if any for that flag type) +// VC specifies the value creator which creates the flag.Value emulation +type FlagBase[T any, C any, VC ValueCreator[T, C]] struct { + Name string `json:"name"` // name of the flag + Category string `json:"category"` // category of the flag, if any + DefaultText string `json:"defaultText"` // default text of the flag for usage purposes + HideDefault bool `json:"hideDefault"` // whether to hide the default value in output + Usage string `json:"usage"` // usage string for help output + Sources ValueSourceChain `json:"-"` // sources to load flag value from + Required bool `json:"required"` // whether the flag is required or not + Hidden bool `json:"hidden"` // whether to hide the flag in help output + Local bool `json:"local"` // whether the flag needs to be applied to subcommands as well + Value T `json:"defaultValue"` // default value for this flag if not set by from any source + Destination *T `json:"-"` // destination pointer for value when set + Aliases []string `json:"aliases"` // Aliases that are allowed for this flag + TakesFile bool `json:"takesFileArg"` // whether this flag takes a file argument, mainly for shell completion purposes + Action func(context.Context, *Command, T) error `json:"-"` // Action callback to be called when flag is set + Config C `json:"config"` // Additional/Custom configuration associated with this flag type + OnlyOnce bool `json:"onlyOnce"` // whether this flag can be duplicated on the command line + Validator func(T) error `json:"-"` // custom function to validate this flag value + ValidateDefaults bool `json:"validateDefaults"` // whether to validate defaults or not + + // unexported fields for internal use + count int // number of times the flag has been set + hasBeenSet bool // whether the flag has been set from env or file + applied bool // whether the flag has been applied to a flag set already + creator VC // value creator for this flag type + value Value // value representing this flag's value +} + +// GetValue returns the flags value as string representation and an empty +// string if the flag takes no value at all. +func (f *FlagBase[T, C, V]) GetValue() string { + if reflect.TypeOf(f.Value).Kind() == reflect.Bool { + return "" + } + return fmt.Sprintf("%v", f.Value) +} + +// Apply populates the flag given the flag set and environment +func (f *FlagBase[T, C, V]) Apply(set *flag.FlagSet) error { + tracef("apply (flag=%[1]q)", f.Name) + + // TODO move this phase into a separate flag initialization function + // if flag has been applied previously then it would have already been set + // from env or file. So no need to apply the env set again. However + // lots of units tests prior to persistent flags assumed that the + // flag can be applied to different flag sets multiple times while still + // keeping the env set. + if !f.applied || f.Local { + newVal := f.Value + + if val, source, found := f.Sources.LookupWithSource(); found { + tmpVal := f.creator.Create(f.Value, new(T), f.Config) + if val != "" || reflect.TypeOf(f.Value).Kind() == reflect.String { + if err := tmpVal.Set(val); err != nil { + return fmt.Errorf( + "could not parse %[1]q as %[2]T value from %[3]s for flag %[4]s: %[5]s", + val, f.Value, source, f.Name, err, + ) + } + } else if val == "" && reflect.TypeOf(f.Value).Kind() == reflect.Bool { + val = "false" + if err := tmpVal.Set(val); err != nil { + return fmt.Errorf( + "could not parse %[1]q as %[2]T value from %[3]s for flag %[4]s: %[5]s", + val, f.Value, source, f.Name, err, + ) + } + } + + newVal = tmpVal.Get().(T) + f.hasBeenSet = true + } + + if f.Destination == nil { + f.value = f.creator.Create(newVal, new(T), f.Config) + } else { + f.value = f.creator.Create(newVal, f.Destination, f.Config) + } + + // Validate the given default or values set from external sources as well + if f.Validator != nil && f.ValidateDefaults { + if v, ok := f.value.Get().(T); !ok { + return &typeError[T]{ + other: f.value.Get(), + } + } else if err := f.Validator(v); err != nil { + return err + } + } + } + + isBool := false + if b, ok := f.value.(boolFlag); ok && b.IsBoolFlag() { + isBool = true + } + + for _, name := range f.Names() { + set.Var(&fnValue{ + fn: func(val string) error { + if f.count == 1 && f.OnlyOnce { + return fmt.Errorf("cant duplicate this flag") + } + f.count++ + if err := f.value.Set(val); err != nil { + return err + } + f.hasBeenSet = true + if f.Validator != nil { + if v, ok := f.value.Get().(T); !ok { + return &typeError[T]{ + other: f.value.Get(), + } + } else if err := f.Validator(v); err != nil { + return err + } + } + return nil + }, + isBool: isBool, + v: f.value, + }, name, f.Usage) + } + + f.applied = true + return nil +} + +// String returns a readable representation of this value (for usage defaults) +func (f *FlagBase[T, C, V]) String() string { + return FlagStringer(f) +} + +// IsSet returns whether or not the flag has been set through env or file +func (f *FlagBase[T, C, V]) IsSet() bool { + return f.hasBeenSet +} + +// Names returns the names of the flag +func (f *FlagBase[T, C, V]) Names() []string { + return FlagNames(f.Name, f.Aliases) +} + +// IsRequired returns whether or not the flag is required +func (f *FlagBase[T, C, V]) IsRequired() bool { + return f.Required +} + +// IsVisible returns true if the flag is not hidden, otherwise false +func (f *FlagBase[T, C, V]) IsVisible() bool { + return !f.Hidden +} + +// GetCategory returns the category of the flag +func (f *FlagBase[T, C, V]) GetCategory() string { + return f.Category +} + +func (f *FlagBase[T, C, V]) SetCategory(c string) { + f.Category = c +} + +// GetUsage returns the usage string for the flag +func (f *FlagBase[T, C, V]) GetUsage() string { + return f.Usage +} + +// GetEnvVars returns the env vars for this flag +func (f *FlagBase[T, C, V]) GetEnvVars() []string { + return f.Sources.EnvKeys() +} + +// TakesValue returns true if the flag takes a value, otherwise false +func (f *FlagBase[T, C, V]) TakesValue() bool { + var t T + return reflect.TypeOf(t).Kind() != reflect.Bool +} + +// GetDefaultText returns the default text for this flag +func (f *FlagBase[T, C, V]) GetDefaultText() string { + if f.DefaultText != "" { + return f.DefaultText + } + var v V + return v.ToString(f.Value) +} + +// Get returns the flag’s value in the given Command. +func (f *FlagBase[T, C, V]) Get(cmd *Command) T { + if v, ok := cmd.Value(f.Name).(T); ok { + return v + } + var t T + return t +} + +// RunAction executes flag action if set +func (f *FlagBase[T, C, V]) RunAction(ctx context.Context, cmd *Command) error { + if f.Action != nil { + return f.Action(ctx, cmd, f.Get(cmd)) + } + + return nil +} + +// IsMultiValueFlag returns true if the value type T can take multiple +// values from cmd line. This is true for slice and map type flags +func (f *FlagBase[T, C, VC]) IsMultiValueFlag() bool { + // TBD how to specify + kind := reflect.TypeOf(f.Value).Kind() + return kind == reflect.Slice || kind == reflect.Map +} + +// IsLocal returns false if flag needs to be persistent across subcommands +func (f *FlagBase[T, C, VC]) IsLocal() bool { + return f.Local +} diff --git a/vendor/github.com/urfave/cli/v3/flag_int.go b/vendor/github.com/urfave/cli/v3/flag_int.go new file mode 100644 index 00000000..f8e3640b --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_int.go @@ -0,0 +1,59 @@ +package cli + +import ( + "strconv" +) + +type IntFlag = FlagBase[int64, IntegerConfig, intValue] + +// IntegerConfig is the configuration for all integer type flags +type IntegerConfig struct { + Base int +} + +// -- int64 Value +type intValue struct { + val *int64 + base int +} + +// Below functions are to satisfy the ValueCreator interface + +func (i intValue) Create(val int64, p *int64, c IntegerConfig) Value { + *p = val + return &intValue{ + val: p, + base: c.Base, + } +} + +func (i intValue) ToString(b int64) string { + return strconv.FormatInt(b, 10) +} + +// Below functions are to satisfy the flag.Value interface + +func (i *intValue) Set(s string) error { + v, err := strconv.ParseInt(s, i.base, 64) + if err != nil { + return err + } + *i.val = v + return err +} + +func (i *intValue) Get() any { return int64(*i.val) } + +func (i *intValue) String() string { return strconv.FormatInt(int64(*i.val), 10) } + +// Int looks up the value of a local Int64Flag, returns +// 0 if not found +func (cmd *Command) Int(name string) int64 { + if v, ok := cmd.Value(name).(int64); ok { + tracef("int available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + return v + } + + tracef("int NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return 0 +} diff --git a/vendor/github.com/urfave/cli/v3/flag_int_slice.go b/vendor/github.com/urfave/cli/v3/flag_int_slice.go new file mode 100644 index 00000000..94a9b78d --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_int_slice.go @@ -0,0 +1,20 @@ +package cli + +type ( + IntSlice = SliceBase[int64, IntegerConfig, intValue] + IntSliceFlag = FlagBase[[]int64, IntegerConfig, IntSlice] +) + +var NewIntSlice = NewSliceBase[int64, IntegerConfig, intValue] + +// IntSlice looks up the value of a local IntSliceFlag, returns +// nil if not found +func (cmd *Command) IntSlice(name string) []int64 { + if v, ok := cmd.Value(name).([]int64); ok { + tracef("int slice available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + return v + } + + tracef("int slice NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return nil +} diff --git a/vendor/github.com/urfave/cli/v3/flag_map_impl.go b/vendor/github.com/urfave/cli/v3/flag_map_impl.go new file mode 100644 index 00000000..e0ba88be --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_map_impl.go @@ -0,0 +1,116 @@ +package cli + +import ( + "encoding/json" + "fmt" + "reflect" + "sort" + "strings" +) + +// MapBase wraps map[string]T to satisfy flag.Value +type MapBase[T any, C any, VC ValueCreator[T, C]] struct { + dict *map[string]T + hasBeenSet bool + value Value +} + +func (i MapBase[T, C, VC]) Create(val map[string]T, p *map[string]T, c C) Value { + *p = map[string]T{} + for k, v := range val { + (*p)[k] = v + } + var t T + np := new(T) + var vc VC + return &MapBase[T, C, VC]{ + dict: p, + value: vc.Create(t, np, c), + } +} + +// NewMapBase makes a *MapBase with default values +func NewMapBase[T any, C any, VC ValueCreator[T, C]](defaults map[string]T) *MapBase[T, C, VC] { + return &MapBase[T, C, VC]{ + dict: &defaults, + } +} + +// Set parses the value and appends it to the list of values +func (i *MapBase[T, C, VC]) Set(value string) error { + if !i.hasBeenSet { + *i.dict = map[string]T{} + i.hasBeenSet = true + } + + if strings.HasPrefix(value, slPfx) { + // Deserializing assumes overwrite + _ = json.Unmarshal([]byte(strings.Replace(value, slPfx, "", 1)), &i.dict) + i.hasBeenSet = true + return nil + } + + for _, item := range flagSplitMultiValues(value) { + key, value, ok := strings.Cut(item, defaultMapFlagKeyValueSeparator) + if !ok { + return fmt.Errorf("item %q is missing separator %q", item, defaultMapFlagKeyValueSeparator) + } + if err := i.value.Set(value); err != nil { + return err + } + tmp, ok := i.value.Get().(T) + if !ok { + return fmt.Errorf("unable to cast %v", i.value) + } + (*i.dict)[key] = tmp + } + + return nil +} + +// String returns a readable representation of this value (for usage defaults) +func (i *MapBase[T, C, VC]) String() string { + v := i.Value() + var t T + if reflect.TypeOf(t).Kind() == reflect.String { + return fmt.Sprintf("%v", v) + } + return fmt.Sprintf("%T{%s}", v, i.ToString(v)) +} + +// Serialize allows MapBase to fulfill Serializer +func (i *MapBase[T, C, VC]) Serialize() string { + jsonBytes, _ := json.Marshal(i.dict) + return fmt.Sprintf("%s%s", slPfx, string(jsonBytes)) +} + +// Value returns the mapping of values set by this flag +func (i *MapBase[T, C, VC]) Value() map[string]T { + if i.dict == nil { + return map[string]T{} + } + return *i.dict +} + +// Get returns the mapping of values set by this flag +func (i *MapBase[T, C, VC]) Get() interface{} { + return *i.dict +} + +func (i MapBase[T, C, VC]) ToString(t map[string]T) string { + var defaultVals []string + var vc VC + for _, k := range sortedKeys(t) { + defaultVals = append(defaultVals, k+defaultMapFlagKeyValueSeparator+vc.ToString(t[k])) + } + return strings.Join(defaultVals, ", ") +} + +func sortedKeys[T any](dict map[string]T) []string { + keys := make([]string, 0, len(dict)) + for k := range dict { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} diff --git a/vendor/github.com/urfave/cli/v3/flag_mutex.go b/vendor/github.com/urfave/cli/v3/flag_mutex.go new file mode 100644 index 00000000..e03de8da --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_mutex.go @@ -0,0 +1,56 @@ +package cli + +// MutuallyExclusiveFlags defines a mutually exclusive flag group +// Multiple option paths can be provided out of which +// only one can be defined on cmdline +// So for example +// [ --foo | [ --bar something --darth somethingelse ] ] +type MutuallyExclusiveFlags struct { + // Flag list + Flags [][]Flag + + // whether this group is required + Required bool + + // Category to apply to all flags within group + Category string +} + +func (grp MutuallyExclusiveFlags) check(cmd *Command) error { + oneSet := false + e := &mutuallyExclusiveGroup{} + + for _, grpf := range grp.Flags { + for _, f := range grpf { + for _, name := range f.Names() { + if cmd.IsSet(name) { + if oneSet { + e.flag2Name = name + return e + } + e.flag1Name = name + oneSet = true + break + } + } + if oneSet { + break + } + } + } + + if !oneSet && grp.Required { + return &mutuallyExclusiveGroupRequiredFlag{flags: &grp} + } + return nil +} + +func (grp MutuallyExclusiveFlags) propagateCategory() { + for _, grpf := range grp.Flags { + for _, f := range grpf { + if cf, ok := f.(CategorizableFlag); ok { + cf.SetCategory(grp.Category) + } + } + } +} diff --git a/vendor/github.com/urfave/cli/v3/flag_slice_base.go b/vendor/github.com/urfave/cli/v3/flag_slice_base.go new file mode 100644 index 00000000..7278e3ed --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_slice_base.go @@ -0,0 +1,110 @@ +package cli + +import ( + "encoding/json" + "fmt" + "reflect" + "strings" +) + +// SliceBase wraps []T to satisfy flag.Value +type SliceBase[T any, C any, VC ValueCreator[T, C]] struct { + slice *[]T + hasBeenSet bool + value Value +} + +func (i SliceBase[T, C, VC]) Create(val []T, p *[]T, c C) Value { + *p = []T{} + *p = append(*p, val...) + var t T + np := new(T) + var vc VC + return &SliceBase[T, C, VC]{ + slice: p, + value: vc.Create(t, np, c), + } +} + +// NewSliceBase makes a *SliceBase with default values +func NewSliceBase[T any, C any, VC ValueCreator[T, C]](defaults ...T) *SliceBase[T, C, VC] { + return &SliceBase[T, C, VC]{ + slice: &defaults, + } +} + +// SetOne directly adds a value to the list of values +func (i *SliceBase[T, C, VC]) SetOne(value T) { + if !i.hasBeenSet { + *i.slice = []T{} + i.hasBeenSet = true + } + + *i.slice = append(*i.slice, value) +} + +// Set parses the value and appends it to the list of values +func (i *SliceBase[T, C, VC]) Set(value string) error { + if !i.hasBeenSet { + *i.slice = []T{} + i.hasBeenSet = true + } + + if strings.HasPrefix(value, slPfx) { + // Deserializing assumes overwrite + _ = json.Unmarshal([]byte(strings.Replace(value, slPfx, "", 1)), &i.slice) + i.hasBeenSet = true + return nil + } + + for _, s := range flagSplitMultiValues(value) { + if err := i.value.Set(strings.TrimSpace(s)); err != nil { + return err + } + tmp, ok := i.value.Get().(T) + if !ok { + return fmt.Errorf("unable to cast %v", i.value) + } + *i.slice = append(*i.slice, tmp) + } + + return nil +} + +// String returns a readable representation of this value (for usage defaults) +func (i *SliceBase[T, C, VC]) String() string { + v := i.Value() + var t T + if reflect.TypeOf(t).Kind() == reflect.String { + return fmt.Sprintf("%v", v) + } + return fmt.Sprintf("%T{%s}", v, i.ToString(v)) +} + +// Serialize allows SliceBase to fulfill Serializer +func (i *SliceBase[T, C, VC]) Serialize() string { + jsonBytes, _ := json.Marshal(i.slice) + return fmt.Sprintf("%s%s", slPfx, string(jsonBytes)) +} + +// Value returns the slice of values set by this flag +func (i *SliceBase[T, C, VC]) Value() []T { + if i.slice == nil { + return []T{} + } + return *i.slice +} + +// Get returns the slice of values set by this flag +func (i *SliceBase[T, C, VC]) Get() interface{} { + return *i.slice +} + +func (i SliceBase[T, C, VC]) ToString(t []T) string { + var defaultVals []string + var v VC + for _, s := range t { + defaultVals = append(defaultVals, v.ToString(s)) + } + return strings.Join(defaultVals, ", ") +} diff --git a/vendor/github.com/urfave/cli/v3/flag_string.go b/vendor/github.com/urfave/cli/v3/flag_string.go new file mode 100644 index 00000000..bdc1ec65 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_string.go @@ -0,0 +1,66 @@ +package cli + +import ( + "fmt" + "strings" +) + +type StringFlag = FlagBase[string, StringConfig, stringValue] + +// StringConfig defines the configuration for string flags +type StringConfig struct { + // Whether to trim whitespace of parsed value + TrimSpace bool +} + +// -- string Value +type stringValue struct { + destination *string + trimSpace bool +} + +// Below functions are to satisfy the ValueCreator interface + +func (s stringValue) Create(val string, p *string, c StringConfig) Value { + *p = val + return &stringValue{ + destination: p, + trimSpace: c.TrimSpace, + } +} + +func (s stringValue) ToString(val string) string { + if val == "" { + return val + } + return fmt.Sprintf("%q", val) +} + +// Below functions are to satisfy the flag.Value interface + +func (s *stringValue) Set(val string) error { + if s.trimSpace { + val = strings.TrimSpace(val) + } + *s.destination = val + return nil +} + +func (s *stringValue) Get() any { return *s.destination } + +func (s *stringValue) String() string { + if s.destination != nil { + return *s.destination + } + return "" +} + +func (cmd *Command) String(name string) string { + if v, ok := cmd.Value(name).(string); ok { + tracef("string available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + return v + } + + tracef("string NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return "" +} diff --git a/vendor/github.com/urfave/cli/v3/flag_string_map.go b/vendor/github.com/urfave/cli/v3/flag_string_map.go new file mode 100644 index 00000000..52fd7362 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_string_map.go @@ -0,0 +1,20 @@ +package cli + +type ( + StringMap = MapBase[string, StringConfig, stringValue] + StringMapFlag = FlagBase[map[string]string, StringConfig, StringMap] +) + +var NewStringMap = NewMapBase[string, StringConfig, stringValue] + +// StringMap looks up the value of a local StringMapFlag, returns +// nil if not found +func (cmd *Command) StringMap(name string) map[string]string { + if v, ok := cmd.Value(name).(map[string]string); ok { + tracef("string map available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + return v + } + + tracef("string map NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return nil +} diff --git a/vendor/github.com/urfave/cli/v3/flag_string_slice.go b/vendor/github.com/urfave/cli/v3/flag_string_slice.go new file mode 100644 index 00000000..4cb6c5a0 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_string_slice.go @@ -0,0 +1,20 @@ +package cli + +type ( + StringSlice = SliceBase[string, StringConfig, stringValue] + StringSliceFlag = FlagBase[[]string, StringConfig, StringSlice] +) + +var NewStringSlice = NewSliceBase[string, StringConfig, stringValue] + +// StringSlice looks up the value of a local StringSliceFlag, returns +// nil if not found +func (cmd *Command) StringSlice(name string) []string { + if v, ok := cmd.Value(name).([]string); ok { + tracef("string slice available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + return v + } + + tracef("string slice NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return nil +} diff --git a/vendor/github.com/urfave/cli/v3/flag_timestamp.go b/vendor/github.com/urfave/cli/v3/flag_timestamp.go new file mode 100644 index 00000000..8b9dd16a --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_timestamp.go @@ -0,0 +1,152 @@ +package cli + +import ( + "errors" + "fmt" + "time" +) + +type TimestampFlag = FlagBase[time.Time, TimestampConfig, timestampValue] + +// TimestampConfig defines the config for timestamp flags +type TimestampConfig struct { + Timezone *time.Location + // Available layouts for flag value. + // + // Note that value for formats with missing year/date will be interpreted as current year/date respectively. + // + // Read more about time layouts: https://pkg.go.dev/time#pkg-constants + Layouts []string +} + +// timestampValue wrap to satisfy golang's flag interface. +type timestampValue struct { + timestamp *time.Time + hasBeenSet bool + layouts []string + location *time.Location +} + +var _ ValueCreator[time.Time, TimestampConfig] = timestampValue{} + +// Below functions are to satisfy the ValueCreator interface + +func (t timestampValue) Create(val time.Time, p *time.Time, c TimestampConfig) Value { + *p = val + return ×tampValue{ + timestamp: p, + layouts: c.Layouts, + location: c.Timezone, + } +} + +func (t timestampValue) ToString(b time.Time) string { + if b.IsZero() { + return "" + } + return fmt.Sprintf("%v", b) +} + +// Timestamp constructor(for internal testing only) +func newTimestamp(timestamp time.Time) *timestampValue { + return ×tampValue{timestamp: ×tamp} +} + +// Below functions are to satisfy the flag.Value interface + +// Parses the string value to timestamp +func (t *timestampValue) Set(value string) error { + var timestamp time.Time + var err error + + if t.location == nil { + t.location = time.UTC + } + + if len(t.layouts) == 0 { + return errors.New("got nil/empty layouts slice") + } + + for _, layout := range t.layouts { + var locErr error + + timestamp, locErr = time.ParseInLocation(layout, value, t.location) + if locErr != nil { + if err == nil { + err = locErr + continue + } + + err = newMultiError(err, locErr) + continue + } + + err = nil + break + } + + if err != nil { + return err + } + + defaultTS, _ := time.ParseInLocation(time.TimeOnly, time.TimeOnly, timestamp.Location()) + + n := time.Now() + + // If format is missing date (or year only), set it explicitly to current + if timestamp.Truncate(time.Hour*24).UnixNano() == defaultTS.Truncate(time.Hour*24).UnixNano() { + timestamp = time.Date( + n.Year(), + n.Month(), + n.Day(), + timestamp.Hour(), + timestamp.Minute(), + timestamp.Second(), + timestamp.Nanosecond(), + timestamp.Location(), + ) + } else if timestamp.Year() == 0 { + timestamp = time.Date( + n.Year(), + timestamp.Month(), + timestamp.Day(), + timestamp.Hour(), + timestamp.Minute(), + timestamp.Second(), + timestamp.Nanosecond(), + timestamp.Location(), + ) + } + + if t.timestamp != nil { + *t.timestamp = timestamp + } + t.hasBeenSet = true + return nil +} + +// String returns a readable representation of this value (for usage defaults) +func (t *timestampValue) String() string { + return fmt.Sprintf("%#v", t.timestamp) +} + +// Value returns the timestamp value stored in the flag +func (t *timestampValue) Value() *time.Time { + return t.timestamp +} + +// Get returns the flag structure +func (t *timestampValue) Get() any { + return *t.timestamp +} + +// Timestamp gets the timestamp from a flag name +func (cmd *Command) Timestamp(name string) time.Time { + if v, ok := cmd.Value(name).(time.Time); ok { + tracef("time.Time available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + return v + } + + tracef("time.Time NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return time.Time{} +} diff --git a/vendor/github.com/urfave/cli/v3/flag_uint.go b/vendor/github.com/urfave/cli/v3/flag_uint.go new file mode 100644 index 00000000..1f3c82da --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_uint.go @@ -0,0 +1,54 @@ +package cli + +import ( + "strconv" +) + +type UintFlag = FlagBase[uint64, IntegerConfig, uintValue] + +// -- uint64 Value +type uintValue struct { + val *uint64 + base int +} + +// Below functions are to satisfy the ValueCreator interface + +func (i uintValue) Create(val uint64, p *uint64, c IntegerConfig) Value { + *p = val + return &uintValue{ + val: p, + base: c.Base, + } +} + +func (i uintValue) ToString(b uint64) string { + return strconv.FormatUint(b, 10) +} + +// Below functions are to satisfy the flag.Value interface + +func (i *uintValue) Set(s string) error { + v, err := strconv.ParseUint(s, i.base, 64) + if err != nil { + return err + } + *i.val = v + return err +} + +func (i *uintValue) Get() any { return uint64(*i.val) } + +func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i.val), 10) } + +// Uint looks up the value of a local Uint64Flag, returns +// 0 if not found +func (cmd *Command) Uint(name string) uint64 { + if v, ok := cmd.Value(name).(uint64); ok { + tracef("uint available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + return v + } + + tracef("uint NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return 0 +} diff --git a/vendor/github.com/urfave/cli/v3/flag_uint_slice.go b/vendor/github.com/urfave/cli/v3/flag_uint_slice.go new file mode 100644 index 00000000..ef7d4db4 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_uint_slice.go @@ -0,0 +1,20 @@ +package cli + +type ( + UintSlice = SliceBase[uint64, IntegerConfig, uintValue] + UintSliceFlag = FlagBase[[]uint64, IntegerConfig, UintSlice] +) + +var NewUintSlice = NewSliceBase[uint64, IntegerConfig, uintValue] + +// UintSlice looks up the value of a local UintSliceFlag, returns +// nil if not found +func (cmd *Command) UintSlice(name string) []uint64 { + if v, ok := cmd.Value(name).([]uint64); ok { + tracef("uint slice available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + return v + } + + tracef("uint slice NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return nil +} diff --git a/vendor/github.com/urfave/cli/v2/funcs.go b/vendor/github.com/urfave/cli/v3/funcs.go similarity index 59% rename from vendor/github.com/urfave/cli/v2/funcs.go rename to vendor/github.com/urfave/cli/v3/funcs.go index e77b0d0a..9a7361d8 100644 --- a/vendor/github.com/urfave/cli/v2/funcs.go +++ b/vendor/github.com/urfave/cli/v3/funcs.go @@ -1,34 +1,37 @@ package cli -// BashCompleteFunc is an action to execute when the shell completion flag is set -type BashCompleteFunc func(*Context) +import "context" -// BeforeFunc is an action to execute before any subcommands are run, but after -// the context is ready if a non-nil error is returned, no subcommands are run -type BeforeFunc func(*Context) error +// ShellCompleteFunc is an action to execute when the shell completion flag is set +type ShellCompleteFunc func(context.Context, *Command) -// AfterFunc is an action to execute after any subcommands are run, but after the -// subcommand has finished it is run even if Action() panics -type AfterFunc func(*Context) error +// BeforeFunc is an action that executes prior to any subcommands being run once +// the context is ready. If a non-nil error is returned, no subcommands are +// run. +type BeforeFunc func(context.Context, *Command) error + +// AfterFunc is an action that executes after any subcommands are run and have +// finished. The AfterFunc is run even if Action() panics. +type AfterFunc func(context.Context, *Command) error // ActionFunc is the action to execute when no subcommands are specified -type ActionFunc func(*Context) error +type ActionFunc func(context.Context, *Command) error // CommandNotFoundFunc is executed if the proper command cannot be found -type CommandNotFoundFunc func(*Context, string) +type CommandNotFoundFunc func(context.Context, *Command, string) // OnUsageErrorFunc is executed if a usage error occurs. This is useful for displaying // customized usage error messages. This function is able to replace the // original error messages. If this function is not set, the "Incorrect usage" // is displayed and the execution is interrupted. -type OnUsageErrorFunc func(cCtx *Context, err error, isSubcommand bool) error +type OnUsageErrorFunc func(ctx context.Context, cmd *Command, err error, isSubcommand bool) error // InvalidFlagAccessFunc is executed when an invalid flag is accessed from the context. -type InvalidFlagAccessFunc func(*Context, string) +type InvalidFlagAccessFunc func(context.Context, *Command, string) // ExitErrHandlerFunc is executed if provided in order to handle exitError values // returned by Actions and Before/After functions. -type ExitErrHandlerFunc func(cCtx *Context, err error) +type ExitErrHandlerFunc func(context.Context, *Command, error) // FlagStringFunc is used by the help generation to display a flag, which is // expected to be a single line. diff --git a/vendor/github.com/urfave/cli/v3/godoc-current.txt b/vendor/github.com/urfave/cli/v3/godoc-current.txt new file mode 100644 index 00000000..2d120038 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/godoc-current.txt @@ -0,0 +1,1038 @@ +package cli // import "github.com/urfave/cli/v3" + +Package cli provides a minimal framework for creating and organizing command +line Go applications. cli is designed to be easy to understand and write, +the most simple cli application can be written as follows: + + func main() { + (&cli.Command{}).Run(context.Background(), os.Args) + } + +Of course this application does not do much, so let's make this an actual +application: + + func main() { + cmd := &cli.Command{ + Name: "greet", + Usage: "say a greeting", + Action: func(c *cli.Context) error { + fmt.Println("Greetings") + return nil + }, + } + + cmd.Run(context.Background(), os.Args) + } + +VARIABLES + +var ( + SuggestFlag SuggestFlagFunc = suggestFlag + SuggestCommand SuggestCommandFunc = suggestCommand + SuggestDidYouMeanTemplate string = suggestDidYouMeanTemplate +) +var CommandHelpTemplate = `NAME: + {{template "helpNameTemplate" .}} + +USAGE: + {{template "usageTemplate" .}}{{if .Category}} + +CATEGORY: + {{.Category}}{{end}}{{if .Description}} + +DESCRIPTION: + {{template "descriptionTemplate" .}}{{end}}{{if .VisibleFlagCategories}} + +OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}} + +OPTIONS:{{template "visibleFlagTemplate" .}}{{end}}{{if .VisiblePersistentFlags}} + +GLOBAL OPTIONS:{{template "visiblePersistentFlagTemplate" .}}{{end}} +` + CommandHelpTemplate is the text template for the command help topic. cli.go + uses text/template to render templates. You can render custom help text by + setting this variable. + +var DefaultInverseBoolPrefix = "no-" +var ErrWriter io.Writer = os.Stderr + ErrWriter is used to write errors to the user. This can be anything + implementing the io.Writer interface and defaults to os.Stderr. + +var FishCompletionTemplate = `# {{ .Command.Name }} fish shell completion + +function __fish_{{ .Command.Name }}_no_subcommand --description 'Test if there has been any subcommand yet' + for i in (commandline -opc) + if contains -- $i{{ range $v := .AllCommands }} {{ $v }}{{ end }} + return 1 + end + end + return 0 +end + +{{ range $v := .Completions }}{{ $v }} +{{ end }}` +var NewFloatSlice = NewSliceBase[float64, NoConfig, floatValue] +var NewIntSlice = NewSliceBase[int64, IntegerConfig, intValue] +var NewStringMap = NewMapBase[string, StringConfig, stringValue] +var NewStringSlice = NewSliceBase[string, StringConfig, stringValue] +var NewUintSlice = NewSliceBase[uint64, IntegerConfig, uintValue] +var OsExiter = os.Exit + OsExiter is the function used when the app exits. If not set defaults to + os.Exit. + +var RootCommandHelpTemplate = `NAME: + {{template "helpNameTemplate" .}} + +USAGE: + {{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.FullName}} {{if .VisibleFlags}}[global options]{{end}}{{if .VisibleCommands}} [command [command options]]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Version}}{{if not .HideVersion}} + +VERSION: + {{.Version}}{{end}}{{end}}{{if .Description}} + +DESCRIPTION: + {{template "descriptionTemplate" .}}{{end}} +{{- if len .Authors}} + +AUTHOR{{template "authorsTemplate" .}}{{end}}{{if .VisibleCommands}} + +COMMANDS:{{template "visibleCommandCategoryTemplate" .}}{{end}}{{if .VisibleFlagCategories}} + +GLOBAL OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}} + +GLOBAL OPTIONS:{{template "visibleFlagTemplate" .}}{{end}}{{if .Copyright}} + +COPYRIGHT: + {{template "copyrightTemplate" .}}{{end}} +` + RootCommandHelpTemplate is the text template for the Default help topic. + cli.go uses text/template to render templates. You can render custom help + text by setting this variable. + +var SubcommandHelpTemplate = `NAME: + {{template "helpNameTemplate" .}} + +USAGE: + {{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.FullName}} {{if .VisibleCommands}}[command [command options]] {{end}}{{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Category}} + +CATEGORY: + {{.Category}}{{end}}{{if .Description}} + +DESCRIPTION: + {{template "descriptionTemplate" .}}{{end}}{{if .VisibleCommands}} + +COMMANDS:{{template "visibleCommandTemplate" .}}{{end}}{{if .VisibleFlagCategories}} + +OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}} + +OPTIONS:{{template "visibleFlagTemplate" .}}{{end}} +` + SubcommandHelpTemplate is the text template for the subcommand help topic. + cli.go uses text/template to render templates. You can render custom help + text by setting this variable. + +var VersionPrinter = printVersion + VersionPrinter prints the version for the App + +var HelpPrinter helpPrinter = printHelp + HelpPrinter is a function that writes the help output. If not set + explicitly, this calls HelpPrinterCustom using only the default template + functions. + + If custom logic for printing help is required, this function can be + overridden. If the ExtraInfo field is defined on an App, this function + should not be modified, as HelpPrinterCustom will be used directly in order + to capture the extra information. + +var HelpPrinterCustom helpPrinterCustom = printHelpCustom + HelpPrinterCustom is a function that writes the help output. It is used as + the default implementation of HelpPrinter, and may be called directly if the + ExtraInfo field is set on an App. + + In the default implementation, if the customFuncs argument contains a + "wrapAt" key, which is a function which takes no arguments and returns an + int, this int value will be used to produce a "wrap" function used by the + default template to wrap long lines. + + +FUNCTIONS + +func DefaultAppComplete(ctx context.Context, cmd *Command) + DefaultAppComplete prints the list of subcommands as the default app + completion method + +func DefaultCompleteWithFlags(ctx context.Context, cmd *Command) +func FlagNames(name string, aliases []string) []string +func HandleExitCoder(err error) + HandleExitCoder handles errors implementing ExitCoder by printing their + message and calling OsExiter with the given exit code. + + If the given error instead implements MultiError, each error will be checked + for the ExitCoder interface, and OsExiter will be called with the last exit + code found, or exit code 1 if no ExitCoder is found. + + This function is the default error-handling behavior for an App. + +func ShowAppHelp(cmd *Command) error + ShowAppHelp is an action that displays the help. + +func ShowAppHelpAndExit(cmd *Command, exitCode int) + ShowAppHelpAndExit - Prints the list of subcommands for the app and exits + with exit code. + +func ShowCommandHelp(ctx context.Context, cmd *Command, commandName string) error + ShowCommandHelp prints help for the given command + +func ShowCommandHelpAndExit(ctx context.Context, cmd *Command, command string, code int) + ShowCommandHelpAndExit - exits with code after showing help + +func ShowSubcommandHelp(cmd *Command) error + ShowSubcommandHelp prints help for the given subcommand + +func ShowSubcommandHelpAndExit(cmd *Command, exitCode int) + ShowSubcommandHelpAndExit - Prints help for the given subcommand and exits + with exit code. + +func ShowVersion(cmd *Command) + ShowVersion prints the version number of the App + + +TYPES + +type ActionFunc func(context.Context, *Command) error + ActionFunc is the action to execute when no subcommands are specified + +type ActionableFlag interface { + RunAction(context.Context, *Command) error +} + ActionableFlag is an interface that wraps Flag interface and RunAction + operation. + +type AfterFunc func(context.Context, *Command) error + AfterFunc is an action that executes after any subcommands are run and have + finished. The AfterFunc is run even if Action() panics. + +type Args interface { + // Get returns the nth argument, or else a blank string + Get(n int) string + // First returns the first argument, or else a blank string + First() string + // Tail returns the rest of the arguments (not the first one) + // or else an empty string slice + Tail() []string + // Len returns the length of the wrapped slice + Len() int + // Present checks if there are any arguments present + Present() bool + // Slice returns a copy of the internal slice + Slice() []string +} + +type Argument interface { + Parse([]string) ([]string, error) + Usage() string +} + +type ArgumentBase[T any, C any, VC ValueCreator[T, C]] struct { + Name string `json:"name"` // the name of this argument + Value T `json:"value"` // the default value of this argument + Destination *T `json:"-"` // the destination point for this argument + Values *[]T `json:"-"` // all the values of this argument, only if multiple are supported + UsageText string `json:"usageText"` // the usage text to show + Min int `json:"minTimes"` // the min num of occurrences of this argument + Max int `json:"maxTimes"` // the max num of occurrences of this argument, set to -1 for unlimited + Config C `json:"config"` // config for this argument similar to Flag Config +} + +func (a *ArgumentBase[T, C, VC]) Parse(s []string) ([]string, error) + +func (a *ArgumentBase[T, C, VC]) Usage() string + +type BeforeFunc func(context.Context, *Command) error + BeforeFunc is an action that executes prior to any subcommands being run + once the context is ready. If a non-nil error is returned, no subcommands + are run. + +type BoolConfig struct { + Count *int +} + BoolConfig defines the configuration for bool flags + +type BoolFlag = FlagBase[bool, BoolConfig, boolValue] + +type BoolWithInverseFlag struct { + // The BoolFlag which the positive and negative flags are generated from + *BoolFlag + + // The prefix used to indicate a negative value + // Default: `env` becomes `no-env` + InversePrefix string + + // Has unexported fields. +} + +func (parent *BoolWithInverseFlag) Apply(set *flag.FlagSet) error + +func (parent *BoolWithInverseFlag) Flags() []Flag + +func (parent *BoolWithInverseFlag) IsSet() bool + +func (parent *BoolWithInverseFlag) Names() []string + +func (parent *BoolWithInverseFlag) RunAction(ctx context.Context, cmd *Command) error + +func (parent *BoolWithInverseFlag) String() string + String implements the standard Stringer interface. + + Example for BoolFlag{Name: "env"} --[no-]env (default: false) + +func (parent *BoolWithInverseFlag) Value() bool + +type CategorizableFlag interface { + // Returns the category of the flag + GetCategory() string + + // Sets the category of the flag + SetCategory(string) +} + CategorizableFlag is an interface that allows us to potentially use a flag + in a categorized representation. + +type Command struct { + // The name of the command + Name string `json:"name"` + // A list of aliases for the command + Aliases []string `json:"aliases"` + // A short description of the usage of this command + Usage string `json:"usage"` + // Text to override the USAGE section of help + UsageText string `json:"usageText"` + // A short description of the arguments of this command + ArgsUsage string `json:"argsUsage"` + // Version of the command + Version string `json:"version"` + // Longer explanation of how the command works + Description string `json:"description"` + // DefaultCommand is the (optional) name of a command + // to run if no command names are passed as CLI arguments. + DefaultCommand string `json:"defaultCommand"` + // The category the command is part of + Category string `json:"category"` + // List of child commands + Commands []*Command `json:"commands"` + // List of flags to parse + Flags []Flag `json:"flags"` + // Boolean to hide built-in help command and help flag + HideHelp bool `json:"hideHelp"` + // Ignored if HideHelp is true. + HideHelpCommand bool `json:"hideHelpCommand"` + // Boolean to hide built-in version flag and the VERSION section of help + HideVersion bool `json:"hideVersion"` + // Boolean to enable shell completion commands + EnableShellCompletion bool `json:"-"` + // Shell Completion generation command name + ShellCompletionCommandName string `json:"-"` + // The function to call when checking for shell command completions + ShellComplete ShellCompleteFunc `json:"-"` + // An action to execute before any subcommands are run, but after the context is ready + // If a non-nil error is returned, no subcommands are run + Before BeforeFunc `json:"-"` + // An action to execute after any subcommands are run, but after the subcommand has finished + // It is run even if Action() panics + After AfterFunc `json:"-"` + // The function to call when this command is invoked + Action ActionFunc `json:"-"` + // Execute this function if the proper command cannot be found + CommandNotFound CommandNotFoundFunc `json:"-"` + // Execute this function if a usage error occurs. + OnUsageError OnUsageErrorFunc `json:"-"` + // Execute this function when an invalid flag is accessed from the context + InvalidFlagAccessHandler InvalidFlagAccessFunc `json:"-"` + // Boolean to hide this command from help or completion + Hidden bool `json:"hidden"` + // List of all authors who contributed (string or fmt.Stringer) + // TODO: ~string | fmt.Stringer when interface unions are available + Authors []any `json:"authors"` + // Copyright of the binary if any + Copyright string `json:"copyright"` + // Reader reader to write input to (useful for tests) + Reader io.Reader `json:"-"` + // Writer writer to write output to + Writer io.Writer `json:"-"` + // ErrWriter writes error output + ErrWriter io.Writer `json:"-"` + // ExitErrHandler processes any error encountered while running an App before + // it is returned to the caller. If no function is provided, HandleExitCoder + // is used as the default behavior. + ExitErrHandler ExitErrHandlerFunc `json:"-"` + // Other custom info + Metadata map[string]interface{} `json:"metadata"` + // Carries a function which returns app specific info. + ExtraInfo func() map[string]string `json:"-"` + // CustomRootCommandHelpTemplate the text template for app help topic. + // cli.go uses text/template to render templates. You can + // render custom help text by setting this variable. + CustomRootCommandHelpTemplate string `json:"-"` + // SliceFlagSeparator is used to customize the separator for SliceFlag, the default is "," + SliceFlagSeparator string `json:"sliceFlagSeparator"` + // DisableSliceFlagSeparator is used to disable SliceFlagSeparator, the default is false + DisableSliceFlagSeparator bool `json:"disableSliceFlagSeparator"` + // Boolean to enable short-option handling so user can combine several + // single-character bool arguments into one + // i.e. foobar -o -v -> foobar -ov + UseShortOptionHandling bool `json:"useShortOptionHandling"` + // Enable suggestions for commands and flags + Suggest bool `json:"suggest"` + // Allows global flags set by libraries which use flag.XXXVar(...) directly + // to be parsed through this library + AllowExtFlags bool `json:"allowExtFlags"` + // Treat all flags as normal arguments if true + SkipFlagParsing bool `json:"skipFlagParsing"` + // CustomHelpTemplate the text template for the command help topic. + // cli.go uses text/template to render templates. You can + // render custom help text by setting this variable. + CustomHelpTemplate string `json:"-"` + // Use longest prefix match for commands + PrefixMatchCommands bool `json:"prefixMatchCommands"` + // Custom suggest command for matching + SuggestCommandFunc SuggestCommandFunc `json:"-"` + // Flag exclusion group + MutuallyExclusiveFlags []MutuallyExclusiveFlags `json:"mutuallyExclusiveFlags"` + // Arguments to parse for this command + Arguments []Argument `json:"arguments"` + // Whether to read arguments from stdin + // applicable to root command only + ReadArgsFromStdin bool `json:"readArgsFromStdin"` + + // Has unexported fields. +} + Command contains everything needed to run an application that accepts a + string slice of arguments such as os.Args. A given Command may contain Flags + and sub-commands in Commands. + +func (cmd *Command) Args() Args + Args returns the command line arguments associated with the command. + +func (cmd *Command) Bool(name string) bool + +func (cmd *Command) Command(name string) *Command + +func (cmd *Command) Count(name string) int + Count returns the num of occurrences of this flag + +func (cmd *Command) Duration(name string) time.Duration + +func (cmd *Command) FlagNames() []string + FlagNames returns a slice of flag names used by the this command and all of + its parent commands. + +func (cmd *Command) Float(name string) float64 + Float looks up the value of a local FloatFlag, returns 0 if not found + +func (cmd *Command) FloatSlice(name string) []float64 + FloatSlice looks up the value of a local FloatSliceFlag, returns nil if not + found + +func (cmd *Command) FullName() string + FullName returns the full name of the command. For commands with parents + this ensures that the parent commands are part of the command path. + +func (cmd *Command) HasName(name string) bool + HasName returns true if Command.Name matches given name + +func (cmd *Command) Int(name string) int64 + Int looks up the value of a local Int64Flag, returns 0 if not found + +func (cmd *Command) IntSlice(name string) []int64 + IntSlice looks up the value of a local IntSliceFlag, returns nil if not + found + +func (cmd *Command) IsSet(name string) bool + IsSet determines if the flag was actually set + +func (cmd *Command) Lineage() []*Command + Lineage returns *this* command and all of its ancestor commands in order + from child to parent + +func (cmd *Command) LocalFlagNames() []string + LocalFlagNames returns a slice of flag names used in this command. + +func (cmd *Command) NArg() int + NArg returns the number of the command line arguments. + +func (cmd *Command) Names() []string + Names returns the names including short names and aliases. + +func (cmd *Command) NumFlags() int + NumFlags returns the number of flags set + +func (cmd *Command) Root() *Command + Root returns the Command at the root of the graph + +func (cmd *Command) Run(ctx context.Context, osArgs []string) (deferErr error) + Run is the entry point to the command graph. The positional arguments are + parsed according to the Flag and Command definitions and the matching Action + functions are run. + +func (cmd *Command) Set(name, value string) error + Set sets a context flag to a value. + +func (cmd *Command) String(name string) string + +func (cmd *Command) StringMap(name string) map[string]string + StringMap looks up the value of a local StringMapFlag, returns nil if not + found + +func (cmd *Command) StringSlice(name string) []string + StringSlice looks up the value of a local StringSliceFlag, returns nil if + not found + +func (cmd *Command) Timestamp(name string) time.Time + Timestamp gets the timestamp from a flag name + +func (cmd *Command) ToFishCompletion() (string, error) + ToFishCompletion creates a fish completion string for the `*App` The + function errors if either parsing or writing of the string fails. + +func (cmd *Command) Uint(name string) uint64 + Uint looks up the value of a local Uint64Flag, returns 0 if not found + +func (cmd *Command) UintSlice(name string) []uint64 + UintSlice looks up the value of a local UintSliceFlag, returns nil if not + found + +func (cmd *Command) Value(name string) interface{} + Value returns the value of the flag corresponding to `name` + +func (cmd *Command) VisibleCategories() []CommandCategory + VisibleCategories returns a slice of categories and commands that are + Hidden=false + +func (cmd *Command) VisibleCommands() []*Command + VisibleCommands returns a slice of the Commands with Hidden=false + +func (cmd *Command) VisibleFlagCategories() []VisibleFlagCategory + VisibleFlagCategories returns a slice containing all the visible flag + categories with the flags they contain + +func (cmd *Command) VisibleFlags() []Flag + VisibleFlags returns a slice of the Flags with Hidden=false + +func (cmd *Command) VisiblePersistentFlags() []Flag + VisiblePersistentFlags returns a slice of LocalFlag with Persistent=true and + Hidden=false. + +type CommandCategories interface { + // AddCommand adds a command to a category, creating a new category if necessary. + AddCommand(category string, command *Command) + // Categories returns a slice of categories sorted by name + Categories() []CommandCategory +} + CommandCategories interface allows for category manipulation + +type CommandCategory interface { + // Name returns the category name string + Name() string + // VisibleCommands returns a slice of the Commands with Hidden=false + VisibleCommands() []*Command +} + CommandCategory is a category containing commands. + +type CommandNotFoundFunc func(context.Context, *Command, string) + CommandNotFoundFunc is executed if the proper command cannot be found + +type Countable interface { + Count() int +} + Countable is an interface to enable detection of flag values which support + repetitive flags + +type DocGenerationFlag interface { + // TakesValue returns true if the flag takes a value, otherwise false + TakesValue() bool + + // GetUsage returns the usage string for the flag + GetUsage() string + + // GetValue returns the flags value as string representation and an empty + // string if the flag takes no value at all. + GetValue() string + + // GetDefaultText returns the default text for this flag + GetDefaultText() string + + // GetEnvVars returns the env vars for this flag + GetEnvVars() []string + + // IsDefaultVisible returns whether the default value should be shown in + // help text + IsDefaultVisible() bool +} + DocGenerationFlag is an interface that allows documentation generation for + the flag + +type DocGenerationMultiValueFlag interface { + DocGenerationFlag + + // IsMultiValueFlag returns true for flags that can be given multiple times. + IsMultiValueFlag() bool +} + DocGenerationMultiValueFlag extends DocGenerationFlag for slice/map based + flags. + +type DurationFlag = FlagBase[time.Duration, NoConfig, durationValue] + +type ErrorFormatter interface { + Format(s fmt.State, verb rune) +} + ErrorFormatter is the interface that will suitably format the error output + +type ExitCoder interface { + error + ExitCode() int +} + ExitCoder is the interface checked by `App` and `Command` for a custom exit + code + +func Exit(message interface{}, exitCode int) ExitCoder + Exit wraps a message and exit code into an error, which by default is + handled with a call to os.Exit during default error handling. + + This is the simplest way to trigger a non-zero exit code for an App + without having to call os.Exit manually. During testing, this behavior + can be avoided by overriding the ExitErrHandler function on an App or the + package-global OsExiter function. + +type ExitErrHandlerFunc func(context.Context, *Command, error) + ExitErrHandlerFunc is executed if provided in order to handle exitError + values returned by Actions and Before/After functions. + +type Flag interface { + fmt.Stringer + + // Apply Flag settings to the given flag set + Apply(*flag.FlagSet) error + + // All possible names for this flag + Names() []string + + // Whether the flag has been set or not + IsSet() bool +} + Flag is a common interface related to parsing flags in cli. For more + advanced flag parsing techniques, it is recommended that this interface be + implemented. + +var GenerateShellCompletionFlag Flag = &BoolFlag{ + Name: "generate-shell-completion", + Hidden: true, +} + GenerateShellCompletionFlag enables shell completion + +var HelpFlag Flag = &BoolFlag{ + Name: "help", + Aliases: []string{"h"}, + Usage: "show help", + HideDefault: true, + Local: true, +} + HelpFlag prints the help for all commands and subcommands. Set to nil to + disable the flag. The subcommand will still be added unless HideHelp or + HideHelpCommand is set to true. + +var VersionFlag Flag = &BoolFlag{ + Name: "version", + Aliases: []string{"v"}, + Usage: "print the version", + HideDefault: true, + Local: true, +} + VersionFlag prints the version for the application + +type FlagBase[T any, C any, VC ValueCreator[T, C]] struct { + Name string `json:"name"` // name of the flag + Category string `json:"category"` // category of the flag, if any + DefaultText string `json:"defaultText"` // default text of the flag for usage purposes + HideDefault bool `json:"hideDefault"` // whether to hide the default value in output + Usage string `json:"usage"` // usage string for help output + Sources ValueSourceChain `json:"-"` // sources to load flag value from + Required bool `json:"required"` // whether the flag is required or not + Hidden bool `json:"hidden"` // whether to hide the flag in help output + Local bool `json:"local"` // whether the flag needs to be applied to subcommands as well + Value T `json:"defaultValue"` // default value for this flag if not set by from any source + Destination *T `json:"-"` // destination pointer for value when set + Aliases []string `json:"aliases"` // Aliases that are allowed for this flag + TakesFile bool `json:"takesFileArg"` // whether this flag takes a file argument, mainly for shell completion purposes + Action func(context.Context, *Command, T) error `json:"-"` // Action callback to be called when flag is set + Config C `json:"config"` // Additional/Custom configuration associated with this flag type + OnlyOnce bool `json:"onlyOnce"` // whether this flag can be duplicated on the command line + Validator func(T) error `json:"-"` // custom function to validate this flag value + ValidateDefaults bool `json:"validateDefaults"` // whether to validate defaults or not + + // Has unexported fields. +} + FlagBase [T,C,VC] is a generic flag base which can be used as a boilerplate + to implement the most common interfaces used by urfave/cli. + + T specifies the type + C specifies the configuration required(if any for that flag type) + VC specifies the value creator which creates the flag.Value emulation + +func (f *FlagBase[T, C, V]) Apply(set *flag.FlagSet) error + Apply populates the flag given the flag set and environment + +func (f *FlagBase[T, C, V]) Get(cmd *Command) T + Get returns the flag’s value in the given Command. + +func (f *FlagBase[T, C, V]) GetCategory() string + GetCategory returns the category of the flag + +func (f *FlagBase[T, C, V]) GetDefaultText() string + GetDefaultText returns the default text for this flag + +func (f *FlagBase[T, C, V]) GetEnvVars() []string + GetEnvVars returns the env vars for this flag + +func (f *FlagBase[T, C, V]) GetUsage() string + GetUsage returns the usage string for the flag + +func (f *FlagBase[T, C, V]) GetValue() string + GetValue returns the flags value as string representation and an empty + string if the flag takes no value at all. + +func (f *FlagBase[T, C, V]) IsDefaultVisible() bool + IsDefaultVisible returns true if the flag is not hidden, otherwise false + +func (f *FlagBase[T, C, VC]) IsLocal() bool + IsLocal returns false if flag needs to be persistent across subcommands + +func (f *FlagBase[T, C, VC]) IsMultiValueFlag() bool + IsMultiValueFlag returns true if the value type T can take multiple values + from cmd line. This is true for slice and map type flags + +func (f *FlagBase[T, C, V]) IsRequired() bool + IsRequired returns whether or not the flag is required + +func (f *FlagBase[T, C, V]) IsSet() bool + IsSet returns whether or not the flag has been set through env or file + +func (f *FlagBase[T, C, V]) IsVisible() bool + IsVisible returns true if the flag is not hidden, otherwise false + +func (f *FlagBase[T, C, V]) Names() []string + Names returns the names of the flag + +func (f *FlagBase[T, C, V]) RunAction(ctx context.Context, cmd *Command) error + RunAction executes flag action if set + +func (f *FlagBase[T, C, V]) SetCategory(c string) + +func (f *FlagBase[T, C, V]) String() string + String returns a readable representation of this value (for usage defaults) + +func (f *FlagBase[T, C, V]) TakesValue() bool + TakesValue returns true if the flag takes a value, otherwise false + +type FlagCategories interface { + // AddFlags adds a flag to a category, creating a new category if necessary. + AddFlag(category string, fl Flag) + // VisibleCategories returns a slice of visible flag categories sorted by name + VisibleCategories() []VisibleFlagCategory +} + FlagCategories interface allows for category manipulation + +type FlagEnvHintFunc func(envVars []string, str string) string + FlagEnvHintFunc is used by the default FlagStringFunc to annotate flag help + with the environment variable details. + +var FlagEnvHinter FlagEnvHintFunc = withEnvHint + FlagEnvHinter annotates flag help message with the environment variable + details. This is used by the default FlagStringer. + +type FlagFileHintFunc func(filePath, str string) string + FlagFileHintFunc is used by the default FlagStringFunc to annotate flag help + with the file path details. + +var FlagFileHinter FlagFileHintFunc = withFileHint + FlagFileHinter annotates flag help message with the environment variable + details. This is used by the default FlagStringer. + +type FlagNamePrefixFunc func(fullName []string, placeholder string) string + FlagNamePrefixFunc is used by the default FlagStringFunc to create prefix + text for a flag's full name. + +var FlagNamePrefixer FlagNamePrefixFunc = prefixedNames + FlagNamePrefixer converts a full flag name and its placeholder into the help + message flag prefix. This is used by the default FlagStringer. + +type FlagStringFunc func(Flag) string + FlagStringFunc is used by the help generation to display a flag, which is + expected to be a single line. + +var FlagStringer FlagStringFunc = stringifyFlag + FlagStringer converts a flag definition to a string. This is used by help to + display a flag. + +type FlagsByName []Flag + FlagsByName is a slice of Flag. + +func (f FlagsByName) Len() int + +func (f FlagsByName) Less(i, j int) bool + +func (f FlagsByName) Swap(i, j int) + +type FloatArg = ArgumentBase[float64, NoConfig, floatValue] + +type FloatFlag = FlagBase[float64, NoConfig, floatValue] + +type FloatSlice = SliceBase[float64, NoConfig, floatValue] + +type FloatSliceFlag = FlagBase[[]float64, NoConfig, FloatSlice] + +type IntArg = ArgumentBase[int64, IntegerConfig, intValue] + +type IntFlag = FlagBase[int64, IntegerConfig, intValue] + +type IntSlice = SliceBase[int64, IntegerConfig, intValue] + +type IntSliceFlag = FlagBase[[]int64, IntegerConfig, IntSlice] + +type IntegerConfig struct { + Base int +} + IntegerConfig is the configuration for all integer type flags + +type InvalidFlagAccessFunc func(context.Context, *Command, string) + InvalidFlagAccessFunc is executed when an invalid flag is accessed from the + context. + +type LocalFlag interface { + IsLocal() bool +} + LocalFlag is an interface to enable detection of flags which are local to + current command + +type MapBase[T any, C any, VC ValueCreator[T, C]] struct { + // Has unexported fields. +} + MapBase wraps map[string]T to satisfy flag.Value + +func NewMapBase[T any, C any, VC ValueCreator[T, C]](defaults map[string]T) *MapBase[T, C, VC] + NewMapBase makes a *MapBase with default values + +func (i MapBase[T, C, VC]) Create(val map[string]T, p *map[string]T, c C) Value + +func (i *MapBase[T, C, VC]) Get() interface{} + Get returns the mapping of values set by this flag + +func (i *MapBase[T, C, VC]) Serialize() string + Serialize allows MapBase to fulfill Serializer + +func (i *MapBase[T, C, VC]) Set(value string) error + Set parses the value and appends it to the list of values + +func (i *MapBase[T, C, VC]) String() string + String returns a readable representation of this value (for usage defaults) + +func (i MapBase[T, C, VC]) ToString(t map[string]T) string + +func (i *MapBase[T, C, VC]) Value() map[string]T + Value returns the mapping of values set by this flag + +type MultiError interface { + error + Errors() []error +} + MultiError is an error that wraps multiple errors. + +type MutuallyExclusiveFlags struct { + // Flag list + Flags [][]Flag + + // whether this group is required + Required bool + + // Category to apply to all flags within group + Category string +} + MutuallyExclusiveFlags defines a mutually exclusive flag group Multiple + option paths can be provided out of which only one can be defined on cmdline + So for example [ --foo | [ --bar something --darth somethingelse ] ] + +type NoConfig struct{} + NoConfig is for flags which dont need a custom configuration + +type OnUsageErrorFunc func(ctx context.Context, cmd *Command, err error, isSubcommand bool) error + OnUsageErrorFunc is executed if a usage error occurs. This is useful for + displaying customized usage error messages. This function is able to replace + the original error messages. If this function is not set, the "Incorrect + usage" is displayed and the execution is interrupted. + +type RequiredFlag interface { + // whether the flag is a required flag or not + IsRequired() bool +} + RequiredFlag is an interface that allows us to mark flags as required + it allows flags required flags to be backwards compatible with the Flag + interface + +type Serializer interface { + Serialize() string +} + Serializer is used to circumvent the limitations of flag.FlagSet.Set + +type ShellCompleteFunc func(context.Context, *Command) + ShellCompleteFunc is an action to execute when the shell completion flag is + set + +type SliceBase[T any, C any, VC ValueCreator[T, C]] struct { + // Has unexported fields. +} + SliceBase wraps []T to satisfy flag.Value + +func NewSliceBase[T any, C any, VC ValueCreator[T, C]](defaults ...T) *SliceBase[T, C, VC] + NewSliceBase makes a *SliceBase with default values + +func (i SliceBase[T, C, VC]) Create(val []T, p *[]T, c C) Value + +func (i *SliceBase[T, C, VC]) Get() interface{} + Get returns the slice of values set by this flag + +func (i *SliceBase[T, C, VC]) Serialize() string + Serialize allows SliceBase to fulfill Serializer + +func (i *SliceBase[T, C, VC]) Set(value string) error + Set parses the value and appends it to the list of values + +func (i *SliceBase[T, C, VC]) SetOne(value T) + SetOne directly adds a value to the list of values + +func (i *SliceBase[T, C, VC]) String() string + String returns a readable representation of this value (for usage defaults) + +func (i SliceBase[T, C, VC]) ToString(t []T) string + +func (i *SliceBase[T, C, VC]) Value() []T + Value returns the slice of values set by this flag + +type StringArg = ArgumentBase[string, StringConfig, stringValue] + +type StringConfig struct { + // Whether to trim whitespace of parsed value + TrimSpace bool +} + StringConfig defines the configuration for string flags + +type StringFlag = FlagBase[string, StringConfig, stringValue] + +type StringMap = MapBase[string, StringConfig, stringValue] + +type StringMapArg = ArgumentBase[map[string]string, StringConfig, StringMap] + +type StringMapFlag = FlagBase[map[string]string, StringConfig, StringMap] + +type StringSlice = SliceBase[string, StringConfig, stringValue] + +type StringSliceFlag = FlagBase[[]string, StringConfig, StringSlice] + +type SuggestCommandFunc func(commands []*Command, provided string) string + +type SuggestFlagFunc func(flags []Flag, provided string, hideHelp bool) string + +type TimestampArg = ArgumentBase[time.Time, TimestampConfig, timestampValue] + +type TimestampConfig struct { + Timezone *time.Location + // Available layouts for flag value. + // + // Note that value for formats with missing year/date will be interpreted as current year/date respectively. + // + // Read more about time layouts: https://pkg.go.dev/time#pkg-constants + Layouts []string +} + TimestampConfig defines the config for timestamp flags + +type TimestampFlag = FlagBase[time.Time, TimestampConfig, timestampValue] + +type UintArg = ArgumentBase[uint64, IntegerConfig, uintValue] + +type UintFlag = FlagBase[uint64, IntegerConfig, uintValue] + +type UintSlice = SliceBase[uint64, IntegerConfig, uintValue] + +type UintSliceFlag = FlagBase[[]uint64, IntegerConfig, UintSlice] + +type Value interface { + flag.Value + flag.Getter +} + Value represents a value as used by cli. For now it implements the golang + flag.Value interface + +type ValueCreator[T any, C any] interface { + Create(T, *T, C) Value + ToString(T) string +} + ValueCreator is responsible for creating a flag.Value emulation as well as + custom formatting + + T specifies the type + C specifies the config for the type + +type ValueSource interface { + fmt.Stringer + fmt.GoStringer + + // Lookup returns the value from the source and if it was found + // or returns an empty string and false + Lookup() (string, bool) +} + ValueSource is a source which can be used to look up a value, typically for + use with a cli.Flag + +func EnvVar(key string) ValueSource + +func File(path string) ValueSource + +type ValueSourceChain struct { + Chain []ValueSource +} + ValueSourceChain contains an ordered series of ValueSource that allows for + lookup where the first ValueSource to resolve is returned + +func EnvVars(keys ...string) ValueSourceChain + EnvVars is a helper function to encapsulate a number of envVarValueSource + together as a ValueSourceChain + +func Files(paths ...string) ValueSourceChain + Files is a helper function to encapsulate a number of fileValueSource + together as a ValueSourceChain + +func NewValueSourceChain(src ...ValueSource) ValueSourceChain + +func (vsc *ValueSourceChain) Append(other ValueSourceChain) + +func (vsc *ValueSourceChain) EnvKeys() []string + +func (vsc *ValueSourceChain) GoString() string + +func (vsc *ValueSourceChain) Lookup() (string, bool) + +func (vsc *ValueSourceChain) LookupWithSource() (string, ValueSource, bool) + +func (vsc *ValueSourceChain) String() string + +type VisibleFlag interface { + // IsVisible returns true if the flag is not hidden, otherwise false + IsVisible() bool +} + VisibleFlag is an interface that allows to check if a flag is visible + +type VisibleFlagCategory interface { + // Name returns the category name string + Name() string + // Flags returns a slice of VisibleFlag sorted by name + Flags() []Flag +} + VisibleFlagCategory is a category containing flags. + diff --git a/vendor/github.com/urfave/cli/v3/help.go b/vendor/github.com/urfave/cli/v3/help.go new file mode 100644 index 00000000..4a31a49e --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/help.go @@ -0,0 +1,588 @@ +package cli + +import ( + "context" + "fmt" + "io" + "os" + "strings" + "text/tabwriter" + "text/template" + "unicode/utf8" +) + +const ( + helpName = "help" + helpAlias = "h" +) + +// Prints help for the App or Command +type helpPrinter func(w io.Writer, templ string, data interface{}) + +// Prints help for the App or Command with custom template function. +type helpPrinterCustom func(w io.Writer, templ string, data interface{}, customFunc map[string]interface{}) + +// HelpPrinter is a function that writes the help output. If not set explicitly, +// this calls HelpPrinterCustom using only the default template functions. +// +// If custom logic for printing help is required, this function can be +// overridden. If the ExtraInfo field is defined on an App, this function +// should not be modified, as HelpPrinterCustom will be used directly in order +// to capture the extra information. +var HelpPrinter helpPrinter = printHelp + +// HelpPrinterCustom is a function that writes the help output. It is used as +// the default implementation of HelpPrinter, and may be called directly if +// the ExtraInfo field is set on an App. +// +// In the default implementation, if the customFuncs argument contains a +// "wrapAt" key, which is a function which takes no arguments and returns +// an int, this int value will be used to produce a "wrap" function used +// by the default template to wrap long lines. +var HelpPrinterCustom helpPrinterCustom = printHelpCustom + +// VersionPrinter prints the version for the App +var VersionPrinter = printVersion + +func buildHelpCommand(withAction bool) *Command { + cmd := &Command{ + Name: helpName, + Aliases: []string{helpAlias}, + Usage: "Shows a list of commands or help for one command", + ArgsUsage: "[command]", + HideHelp: true, + } + + if withAction { + cmd.Action = helpCommandAction + } + + return cmd +} + +func helpCommandAction(ctx context.Context, cmd *Command) error { + args := cmd.Args() + firstArg := args.First() + + tracef("doing help for cmd %[1]q with args %[2]q", cmd, args) + + // This action can be triggered by a "default" action of a command + // or via cmd.Run when cmd == helpCmd. So we have following possibilities + // + // 1 $ app + // 2 $ app help + // 3 $ app foo + // 4 $ app help foo + // 5 $ app foo help + + // Case 4. when executing a help command set the context to parent + // to allow resolution of subsequent args. This will transform + // $ app help foo + // to + // $ app foo + // which will then be handled as case 3 + if cmd.parent != nil && (cmd.HasName(helpName) || cmd.HasName(helpAlias)) { + tracef("setting cmd to cmd.parent") + cmd = cmd.parent + } + + // Case 4. $ app help foo + // foo is the command for which help needs to be shown + if firstArg != "" { + tracef("returning ShowCommandHelp with %[1]q", firstArg) + return ShowCommandHelp(ctx, cmd, firstArg) + } + + // Case 1 & 2 + // Special case when running help on main app itself as opposed to individual + // commands/subcommands + if cmd.parent == nil { + tracef("returning ShowAppHelp") + _ = ShowAppHelp(cmd) + return nil + } + + // Case 3, 5 + if (len(cmd.Commands) == 1 && !cmd.HideHelp) || + (len(cmd.Commands) == 0 && cmd.HideHelp) { + + tmpl := cmd.CustomHelpTemplate + if tmpl == "" { + tmpl = CommandHelpTemplate + } + + tracef("running HelpPrinter with command %[1]q", cmd.Name) + HelpPrinter(cmd.Root().Writer, tmpl, cmd) + + return nil + } + + tracef("running ShowSubcommandHelp") + return ShowSubcommandHelp(cmd) +} + +// ShowAppHelpAndExit - Prints the list of subcommands for the app and exits with exit code. +func ShowAppHelpAndExit(cmd *Command, exitCode int) { + _ = ShowAppHelp(cmd) + os.Exit(exitCode) +} + +// ShowAppHelp is an action that displays the help. +func ShowAppHelp(cmd *Command) error { + tmpl := cmd.CustomRootCommandHelpTemplate + if tmpl == "" { + tracef("using RootCommandHelpTemplate") + tmpl = RootCommandHelpTemplate + } + + if cmd.ExtraInfo == nil { + HelpPrinter(cmd.Root().Writer, tmpl, cmd.Root()) + return nil + } + + tracef("setting ExtraInfo in customAppData") + customAppData := func() map[string]any { + return map[string]any{ + "ExtraInfo": cmd.ExtraInfo, + } + } + HelpPrinterCustom(cmd.Root().Writer, tmpl, cmd.Root(), customAppData()) + + return nil +} + +// DefaultAppComplete prints the list of subcommands as the default app completion method +func DefaultAppComplete(ctx context.Context, cmd *Command) { + DefaultCompleteWithFlags(ctx, cmd) +} + +func printCommandSuggestions(commands []*Command, writer io.Writer) { + for _, command := range commands { + if command.Hidden { + continue + } + if strings.HasSuffix(os.Getenv("0"), "zsh") { + _, _ = fmt.Fprintf(writer, "%s:%s\n", command.Name, command.Usage) + } else { + _, _ = fmt.Fprintf(writer, "%s\n", command.Name) + } + } +} + +func cliArgContains(flagName string) bool { + for _, name := range strings.Split(flagName, ",") { + name = strings.TrimSpace(name) + count := utf8.RuneCountInString(name) + if count > 2 { + count = 2 + } + flag := fmt.Sprintf("%s%s", strings.Repeat("-", count), name) + for _, a := range os.Args { + if a == flag { + return true + } + } + } + return false +} + +func printFlagSuggestions(lastArg string, flags []Flag, writer io.Writer) { + cur := strings.TrimPrefix(lastArg, "-") + cur = strings.TrimPrefix(cur, "-") + for _, flag := range flags { + if bflag, ok := flag.(*BoolFlag); ok && bflag.Hidden { + continue + } + + usage := "" + if docFlag, ok := flag.(DocGenerationFlag); ok { + usage = docFlag.GetUsage() + } + + name := strings.TrimSpace(flag.Names()[0]) + // this will get total count utf8 letters in flag name + count := utf8.RuneCountInString(name) + if count > 2 { + count = 2 // reuse this count to generate single - or -- in flag completion + } + // if flag name has more than one utf8 letter and last argument in cli has -- prefix then + // skip flag completion for short flags example -v or -x + if strings.HasPrefix(lastArg, "--") && count == 1 { + continue + } + // match if last argument matches this flag and it is not repeated + if strings.HasPrefix(name, cur) && cur != name && !cliArgContains(name) { + flagCompletion := fmt.Sprintf("%s%s", strings.Repeat("-", count), name) + if usage != "" && strings.HasSuffix(os.Getenv("SHELL"), "zsh") { + flagCompletion = fmt.Sprintf("%s:%s", flagCompletion, usage) + } + fmt.Fprintln(writer, flagCompletion) + } + } +} + +func DefaultCompleteWithFlags(ctx context.Context, cmd *Command) { + args := os.Args + if cmd != nil && cmd.flagSet != nil && cmd.parent != nil { + args = cmd.Args().Slice() + tracef("running default complete with flags[%v] on command %[2]q", args, cmd.Name) + } else { + tracef("running default complete with os.Args flags[%v]", args) + } + argsLen := len(args) + lastArg := "" + // parent command will have --generate-shell-completion so we need + // to account for that + if argsLen > 1 { + lastArg = args[argsLen-2] + } else if argsLen > 0 { + lastArg = args[argsLen-1] + } + + if strings.HasPrefix(lastArg, "-") { + tracef("printing flag suggestion for flag[%v] on command %[1]q", lastArg, cmd.Name) + printFlagSuggestions(lastArg, cmd.Flags, cmd.Root().Writer) + return + } + + if cmd != nil { + tracef("printing command suggestions on command %[1]q", cmd.Name) + printCommandSuggestions(cmd.Commands, cmd.Root().Writer) + return + } +} + +// ShowCommandHelpAndExit - exits with code after showing help +func ShowCommandHelpAndExit(ctx context.Context, cmd *Command, command string, code int) { + _ = ShowCommandHelp(ctx, cmd, command) + os.Exit(code) +} + +// ShowCommandHelp prints help for the given command +func ShowCommandHelp(ctx context.Context, cmd *Command, commandName string) error { + for _, subCmd := range cmd.Commands { + if !subCmd.HasName(commandName) { + continue + } + + tmpl := subCmd.CustomHelpTemplate + if tmpl == "" { + if len(subCmd.Commands) == 0 { + tracef("using CommandHelpTemplate") + tmpl = CommandHelpTemplate + } else { + tracef("using SubcommandHelpTemplate") + tmpl = SubcommandHelpTemplate + } + } + + tracef("running HelpPrinter") + HelpPrinter(cmd.Root().Writer, tmpl, subCmd) + + tracef("returning nil after printing help") + return nil + } + + tracef("no matching command found") + + if cmd.CommandNotFound == nil { + errMsg := fmt.Sprintf("No help topic for '%v'", commandName) + + if cmd.Suggest { + if suggestion := SuggestCommand(cmd.Commands, commandName); suggestion != "" { + errMsg += ". " + suggestion + } + } + + tracef("exiting 3 with errMsg %[1]q", errMsg) + return Exit(errMsg, 3) + } + + tracef("running CommandNotFound func for %[1]q", commandName) + cmd.CommandNotFound(ctx, cmd, commandName) + + return nil +} + +// ShowSubcommandHelpAndExit - Prints help for the given subcommand and exits with exit code. +func ShowSubcommandHelpAndExit(cmd *Command, exitCode int) { + _ = ShowSubcommandHelp(cmd) + os.Exit(exitCode) +} + +// ShowSubcommandHelp prints help for the given subcommand +func ShowSubcommandHelp(cmd *Command) error { + if cmd == nil { + return nil + } + + HelpPrinter(cmd.Root().Writer, SubcommandHelpTemplate, cmd) + return nil +} + +// ShowVersion prints the version number of the App +func ShowVersion(cmd *Command) { + tracef("showing version via VersionPrinter (cmd=%[1]q)", cmd.Name) + VersionPrinter(cmd) +} + +func printVersion(cmd *Command) { + _, _ = fmt.Fprintf(cmd.Root().Writer, "%v version %v\n", cmd.Name, cmd.Version) +} + +func handleTemplateError(err error) { + if err != nil { + tracef("error encountered during template parse: %[1]v", err) + // If the writer is closed, t.Execute will fail, and there's nothing + // we can do to recover. + if os.Getenv("CLI_TEMPLATE_ERROR_DEBUG") != "" { + _, _ = fmt.Fprintf(ErrWriter, "CLI TEMPLATE ERROR: %#v\n", err) + } + return + } +} + +// printHelpCustom is the default implementation of HelpPrinterCustom. +// +// The customFuncs map will be combined with a default template.FuncMap to +// allow using arbitrary functions in template rendering. +func printHelpCustom(out io.Writer, templ string, data interface{}, customFuncs map[string]interface{}) { + const maxLineLength = 10000 + + tracef("building default funcMap") + funcMap := template.FuncMap{ + "join": strings.Join, + "subtract": subtract, + "indent": indent, + "nindent": nindent, + "trim": strings.TrimSpace, + "wrap": func(input string, offset int) string { return wrap(input, offset, maxLineLength) }, + "offset": offset, + "offsetCommands": offsetCommands, + } + + if wa, ok := customFuncs["wrapAt"]; ok { + if wrapAtFunc, ok := wa.(func() int); ok { + wrapAt := wrapAtFunc() + customFuncs["wrap"] = func(input string, offset int) string { + return wrap(input, offset, wrapAt) + } + } + } + + for key, value := range customFuncs { + funcMap[key] = value + } + + w := tabwriter.NewWriter(out, 1, 8, 2, ' ', 0) + t := template.Must(template.New("help").Funcs(funcMap).Parse(templ)) + if _, err := t.New("helpNameTemplate").Parse(helpNameTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("argsTemplate").Parse(argsTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("usageTemplate").Parse(usageTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("descriptionTemplate").Parse(descriptionTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("visibleCommandTemplate").Parse(visibleCommandTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("copyrightTemplate").Parse(copyrightTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("versionTemplate").Parse(versionTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("visibleFlagCategoryTemplate").Parse(visibleFlagCategoryTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("visibleFlagTemplate").Parse(visibleFlagTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("visiblePersistentFlagTemplate").Parse(visiblePersistentFlagTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("visibleGlobalFlagCategoryTemplate").Parse(strings.Replace(visibleFlagCategoryTemplate, "OPTIONS", "GLOBAL OPTIONS", -1)); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("authorsTemplate").Parse(authorsTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("visibleCommandCategoryTemplate").Parse(visibleCommandCategoryTemplate); err != nil { + handleTemplateError(err) + } + + tracef("executing template") + handleTemplateError(t.Execute(w, data)) + + _ = w.Flush() +} + +func printHelp(out io.Writer, templ string, data interface{}) { + HelpPrinterCustom(out, templ, data, nil) +} + +func checkVersion(cmd *Command) bool { + found := false + for _, name := range VersionFlag.Names() { + if cmd.Bool(name) { + found = true + } + } + return found +} + +func checkShellCompleteFlag(c *Command, arguments []string) (bool, []string) { + if (c.parent == nil && !c.EnableShellCompletion) || (c.parent != nil && !c.Root().shellCompletion) { + return false, arguments + } + + pos := len(arguments) - 1 + lastArg := arguments[pos] + + if lastArg != "--generate-shell-completion" { + return false, arguments + } + + for _, arg := range arguments { + // If arguments include "--", shell completion is disabled + // because after "--" only positional arguments are accepted. + // https://unix.stackexchange.com/a/11382 + if arg == "--" { + return false, arguments + } + } + + return true, arguments[:pos] +} + +func checkCompletions(ctx context.Context, cmd *Command) bool { + tracef("checking completions on command %[1]q", cmd.Name) + + if !cmd.Root().shellCompletion { + return false + } + + if argsArguments := cmd.Args(); argsArguments.Present() { + name := argsArguments.First() + if cmd := cmd.Command(name); cmd != nil { + // let the command handle the completion + return false + } + } + + if cmd.ShellComplete != nil { + tracef("running shell completion func for command %[1]q", cmd.Name) + cmd.ShellComplete(ctx, cmd) + } + + return true +} + +func subtract(a, b int) int { + return a - b +} + +func indent(spaces int, v string) string { + pad := strings.Repeat(" ", spaces) + return pad + strings.Replace(v, "\n", "\n"+pad, -1) +} + +func nindent(spaces int, v string) string { + return "\n" + indent(spaces, v) +} + +func wrap(input string, offset int, wrapAt int) string { + var ss []string + + lines := strings.Split(input, "\n") + + padding := strings.Repeat(" ", offset) + + for i, line := range lines { + if line == "" { + ss = append(ss, line) + } else { + wrapped := wrapLine(line, offset, wrapAt, padding) + if i == 0 { + ss = append(ss, wrapped) + } else { + ss = append(ss, padding+wrapped) + } + + } + } + + return strings.Join(ss, "\n") +} + +func wrapLine(input string, offset int, wrapAt int, padding string) string { + if wrapAt <= offset || len(input) <= wrapAt-offset { + return input + } + + lineWidth := wrapAt - offset + words := strings.Fields(input) + if len(words) == 0 { + return input + } + + wrapped := words[0] + spaceLeft := lineWidth - len(wrapped) + for _, word := range words[1:] { + if len(word)+1 > spaceLeft { + wrapped += "\n" + padding + word + spaceLeft = lineWidth - len(word) + } else { + wrapped += " " + word + spaceLeft -= 1 + len(word) + } + } + + return wrapped +} + +func offset(input string, fixed int) int { + return len(input) + fixed +} + +// this function tries to find the max width of the names column +// so say we have the following rows for help +// +// foo1, foo2, foo3 some string here +// bar1, b2 some other string here +// +// We want to offset the 2nd row usage by some amount so that everything +// is aligned +// +// foo1, foo2, foo3 some string here +// bar1, b2 some other string here +// +// to find that offset we find the length of all the rows and use the max +// to calculate the offset +func offsetCommands(cmds []*Command, fixed int) int { + max := 0 + for _, cmd := range cmds { + s := strings.Join(cmd.Names(), ", ") + if len(s) > max { + max = len(s) + } + } + return max + fixed +} diff --git a/vendor/github.com/urfave/cli/v3/mkdocs-reqs.txt b/vendor/github.com/urfave/cli/v3/mkdocs-reqs.txt new file mode 100644 index 00000000..7043b559 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/mkdocs-reqs.txt @@ -0,0 +1,5 @@ +mkdocs-git-revision-date-localized-plugin~=1.2 +mkdocs-material-extensions~=1.3 +mkdocs-material~=8.5 +mkdocs~=1.6 +pygments~=2.18 diff --git a/vendor/github.com/urfave/cli/v2/mkdocs.yml b/vendor/github.com/urfave/cli/v3/mkdocs.yml similarity index 96% rename from vendor/github.com/urfave/cli/v2/mkdocs.yml rename to vendor/github.com/urfave/cli/v3/mkdocs.yml index f7bfd419..84391dbd 100644 --- a/vendor/github.com/urfave/cli/v2/mkdocs.yml +++ b/vendor/github.com/urfave/cli/v3/mkdocs.yml @@ -92,8 +92,8 @@ markdown_extensions: - pymdownx.caret - pymdownx.details - pymdownx.emoji: - emoji_index: !!python/name:materialx.emoji.twemoji - emoji_generator: !!python/name:materialx.emoji.to_svg + emoji_index: !!python/name:material.extensions.emoji.twemoji + emoji_generator: !!python/name:material.extensions.emoji.to_svg - pymdownx.highlight - pymdownx.inlinehilite - pymdownx.keys diff --git a/vendor/github.com/urfave/cli/v2/parse.go b/vendor/github.com/urfave/cli/v3/parse.go similarity index 75% rename from vendor/github.com/urfave/cli/v2/parse.go rename to vendor/github.com/urfave/cli/v3/parse.go index d79f15a1..8ec5d4c6 100644 --- a/vendor/github.com/urfave/cli/v2/parse.go +++ b/vendor/github.com/urfave/cli/v3/parse.go @@ -6,7 +6,6 @@ import ( ) type iterativeParser interface { - newFlagSet() (*flag.FlagSet, error) useShortOptionHandling() bool } @@ -18,34 +17,50 @@ type iterativeParser interface { // completion when, the user-supplied options may be incomplete. func parseIter(set *flag.FlagSet, ip iterativeParser, args []string, shellComplete bool) error { for { + tracef("parsing args %[1]q with %[2]T (name=%[3]q)", args, set, set.Name()) + err := set.Parse(args) if !ip.useShortOptionHandling() || err == nil { if shellComplete { + tracef("returning nil due to shellComplete=true") + return nil } + + tracef("returning err %[1]q", err) + return err } + tracef("finding flag from error %[1]q", err) + trimmed, trimErr := flagFromError(err) if trimErr != nil { return err } - // regenerate the initial args with the split short opts + tracef("regenerating the initial args with the split short opts") + argsWereSplit := false for i, arg := range args { - // skip args that are not part of the error message + tracef("skipping args that are not part of the error message (i=%[1]v arg=%[2]q)", i, arg) + if name := strings.TrimLeft(arg, "-"); name != trimmed { continue } - // if we can't split, the error was accurate + tracef("trying to split short option (arg=%[1]q)", arg) + shortOpts := splitShortOptions(set, arg) if len(shortOpts) == 1 { return err } - // swap current argument with the split version + tracef( + "swapping current argument with the split version (shortOpts=%[1]q args=%[2]q)", + shortOpts, args, + ) + // do not include args that parsed correctly so far as it would // trigger Value.Set() on those args and would result in // duplicates for slice type flags @@ -54,8 +69,9 @@ func parseIter(set *flag.FlagSet, ip iterativeParser, args []string, shellComple break } - // This should be an impossible to reach code path, but in case the arg - // splitting failed to happen, this will prevent infinite loops + tracef("this should be an impossible to reach code path") + // but in case the arg splitting failed to happen, this + // will prevent infinite loops if !argsWereSplit { return err } @@ -65,7 +81,7 @@ func parseIter(set *flag.FlagSet, ip iterativeParser, args []string, shellComple const providedButNotDefinedErrMsg = "flag provided but not defined: -" // flagFromError tries to parse a provided flag from an error message. If the -// parsing fials, it returns the input error and an empty string +// parsing fails, it returns the input error and an empty string func flagFromError(err error) (string, error) { errStr := err.Error() trimmed := strings.TrimPrefix(errStr, providedButNotDefinedErrMsg) diff --git a/vendor/github.com/urfave/cli/sort.go b/vendor/github.com/urfave/cli/v3/sort.go similarity index 100% rename from vendor/github.com/urfave/cli/sort.go rename to vendor/github.com/urfave/cli/v3/sort.go diff --git a/vendor/github.com/urfave/cli/v3/staticcheck.conf b/vendor/github.com/urfave/cli/v3/staticcheck.conf new file mode 100644 index 00000000..233d9e73 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/staticcheck.conf @@ -0,0 +1 @@ +checks=["all"] diff --git a/vendor/github.com/urfave/cli/v3/suggestions.go b/vendor/github.com/urfave/cli/v3/suggestions.go new file mode 100644 index 00000000..6f29f122 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/suggestions.go @@ -0,0 +1,147 @@ +package cli + +import ( + "math" +) + +const suggestDidYouMeanTemplate = "Did you mean %q?" + +var ( + SuggestFlag SuggestFlagFunc = suggestFlag + SuggestCommand SuggestCommandFunc = suggestCommand + SuggestDidYouMeanTemplate string = suggestDidYouMeanTemplate +) + +type SuggestFlagFunc func(flags []Flag, provided string, hideHelp bool) string + +type SuggestCommandFunc func(commands []*Command, provided string) string + +// jaroDistance is the measure of similarity between two strings. It returns a +// value between 0 and 1, where 1 indicates identical strings and 0 indicates +// completely different strings. +// +// Adapted from https://github.com/xrash/smetrics/blob/5f08fbb34913bc8ab95bb4f2a89a0637ca922666/jaro.go. +func jaroDistance(a, b string) float64 { + if len(a) == 0 && len(b) == 0 { + return 1 + } + if len(a) == 0 || len(b) == 0 { + return 0 + } + + lenA := float64(len(a)) + lenB := float64(len(b)) + hashA := make([]bool, len(a)) + hashB := make([]bool, len(b)) + maxDistance := int(math.Max(0, math.Floor(math.Max(lenA, lenB)/2.0)-1)) + + var matches float64 + for i := 0; i < len(a); i++ { + start := int(math.Max(0, float64(i-maxDistance))) + end := int(math.Min(lenB-1, float64(i+maxDistance))) + + for j := start; j <= end; j++ { + if hashB[j] { + continue + } + if a[i] == b[j] { + hashA[i] = true + hashB[j] = true + matches++ + break + } + } + } + if matches == 0 { + return 0 + } + + var transpositions float64 + var j int + for i := 0; i < len(a); i++ { + if !hashA[i] { + continue + } + for !hashB[j] { + j++ + } + if a[i] != b[j] { + transpositions++ + } + j++ + } + + transpositions /= 2 + return ((matches / lenA) + (matches / lenB) + ((matches - transpositions) / matches)) / 3.0 +} + +// jaroWinkler is more accurate when strings have a common prefix up to a +// defined maximum length. +// +// Adapted from https://github.com/xrash/smetrics/blob/5f08fbb34913bc8ab95bb4f2a89a0637ca922666/jaro-winkler.go. +func jaroWinkler(a, b string) float64 { + const ( + boostThreshold = 0.7 + prefixSize = 4 + ) + jaroDist := jaroDistance(a, b) + if jaroDist <= boostThreshold { + return jaroDist + } + + prefix := int(math.Min(float64(len(a)), math.Min(float64(prefixSize), float64(len(b))))) + + var prefixMatch float64 + for i := 0; i < prefix; i++ { + if a[i] == b[i] { + prefixMatch++ + } else { + break + } + } + return jaroDist + 0.1*prefixMatch*(1.0-jaroDist) +} + +func suggestFlag(flags []Flag, provided string, hideHelp bool) string { + distance := 0.0 + suggestion := "" + + for _, flag := range flags { + flagNames := flag.Names() + if !hideHelp && HelpFlag != nil { + flagNames = append(flagNames, HelpFlag.Names()...) + } + for _, name := range flagNames { + newDistance := jaroWinkler(name, provided) + if newDistance > distance { + distance = newDistance + suggestion = name + } + } + } + + if len(suggestion) == 1 { + suggestion = "-" + suggestion + } else if len(suggestion) > 1 { + suggestion = "--" + suggestion + } + + return suggestion +} + +// suggestCommand takes a list of commands and a provided string to suggest a +// command name +func suggestCommand(commands []*Command, provided string) (suggestion string) { + distance := 0.0 + for _, command := range commands { + for _, name := range append(command.Names(), helpName, helpAlias) { + newDistance := jaroWinkler(name, provided) + if newDistance > distance { + distance = newDistance + suggestion = name + } + } + } + + return suggestion +} diff --git a/vendor/github.com/urfave/cli/v2/template.go b/vendor/github.com/urfave/cli/v3/template.go similarity index 59% rename from vendor/github.com/urfave/cli/v2/template.go rename to vendor/github.com/urfave/cli/v3/template.go index 5748f4c2..d809dd78 100644 --- a/vendor/github.com/urfave/cli/v2/template.go +++ b/vendor/github.com/urfave/cli/v3/template.go @@ -1,16 +1,23 @@ package cli -var helpNameTemplate = `{{$v := offset .HelpName 6}}{{wrap .HelpName 3}}{{if .Usage}} - {{wrap .Usage $v}}{{end}}` -var usageTemplate = `{{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.HelpName}}{{if .VisibleFlags}} [command options]{{end}}{{if .ArgsUsage}}{{.ArgsUsage}}{{else}}{{if .Args}} [arguments...]{{end}}{{end}}{{end}}` -var descriptionTemplate = `{{wrap .Description 3}}` -var authorsTemplate = `{{with $length := len .Authors}}{{if ne 1 $length}}S{{end}}{{end}}: +var ( + helpNameTemplate = `{{$v := offset .FullName 6}}{{wrap .FullName 3}}{{if .Usage}} - {{wrap .Usage $v}}{{end}}` + argsTemplate = `{{if .Arguments}}{{range .Arguments}}{{.Usage}}{{end}}{{end}}` + usageTemplate = `{{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.FullName}}{{if .VisibleFlags}} [command [command options]]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}{{template "argsTemplate" .}}{{end}}{{end}}` + descriptionTemplate = `{{wrap .Description 3}}` + authorsTemplate = `{{with $length := len .Authors}}{{if ne 1 $length}}S{{end}}{{end}}: {{range $index, $author := .Authors}}{{if $index}} {{end}}{{$author}}{{end}}` +) + var visibleCommandTemplate = `{{ $cv := offsetCommands .VisibleCommands 5}}{{range .VisibleCommands}} {{$s := join .Names ", "}}{{$s}}{{ $sp := subtract $cv (offset $s 3) }}{{ indent $sp ""}}{{wrap .Usage $cv}}{{end}}` + var visibleCommandCategoryTemplate = `{{range .VisibleCategories}}{{if .Name}} + {{.Name}}:{{range .VisibleCommands}} {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{else}}{{template "visibleCommandTemplate" .}}{{end}}{{end}}` + var visibleFlagCategoryTemplate = `{{range .VisibleFlagCategories}} {{if .Name}}{{.Name}} @@ -21,6 +28,9 @@ var visibleFlagCategoryTemplate = `{{range .VisibleFlagCategories}} var visibleFlagTemplate = `{{range $i, $e := .VisibleFlags}} {{wrap $e.String 6}}{{end}}` +var visiblePersistentFlagTemplate = `{{range $i, $e := .VisiblePersistentFlags}} + {{wrap $e.String 6}}{{end}}` + var versionTemplate = `{{if .Version}}{{if not .HideVersion}} VERSION: @@ -28,14 +38,14 @@ VERSION: var copyrightTemplate = `{{wrap .Copyright 3}}` -// AppHelpTemplate is the text template for the Default help topic. +// RootCommandHelpTemplate is the text template for the Default help topic. // cli.go uses text/template to render templates. You can // render custom help text by setting this variable. -var AppHelpTemplate = `NAME: +var RootCommandHelpTemplate = `NAME: {{template "helpNameTemplate" .}} USAGE: - {{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}{{if .Args}}[arguments...]{{end}}{{end}}{{end}}{{if .Version}}{{if not .HideVersion}} + {{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.FullName}} {{if .VisibleFlags}}[global options]{{end}}{{if .VisibleCommands}} [command [command options]]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Version}}{{if not .HideVersion}} VERSION: {{.Version}}{{end}}{{end}}{{if .Description}} @@ -73,7 +83,9 @@ DESCRIPTION: OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}} -OPTIONS:{{template "visibleFlagTemplate" .}}{{end}} +OPTIONS:{{template "visibleFlagTemplate" .}}{{end}}{{if .VisiblePersistentFlags}} + +GLOBAL OPTIONS:{{template "visiblePersistentFlagTemplate" .}}{{end}} ` // SubcommandHelpTemplate is the text template for the subcommand help topic. @@ -83,54 +95,24 @@ var SubcommandHelpTemplate = `NAME: {{template "helpNameTemplate" .}} USAGE: - {{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.HelpName}} {{if .VisibleFlags}}command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}{{if .Args}}[arguments...]{{end}}{{end}}{{end}}{{if .Description}} + {{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.FullName}} {{if .VisibleCommands}}[command [command options]] {{end}}{{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Category}} + +CATEGORY: + {{.Category}}{{end}}{{if .Description}} DESCRIPTION: {{template "descriptionTemplate" .}}{{end}}{{if .VisibleCommands}} -COMMANDS:{{template "visibleCommandCategoryTemplate" .}}{{end}}{{if .VisibleFlagCategories}} +COMMANDS:{{template "visibleCommandTemplate" .}}{{end}}{{if .VisibleFlagCategories}} OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}} OPTIONS:{{template "visibleFlagTemplate" .}}{{end}} ` -var MarkdownDocTemplate = `{{if gt .SectionNum 0}}% {{ .App.Name }} {{ .SectionNum }} +var FishCompletionTemplate = `# {{ .Command.Name }} fish shell completion -{{end}}# NAME - -{{ .App.Name }}{{ if .App.Usage }} - {{ .App.Usage }}{{ end }} - -# SYNOPSIS - -{{ .App.Name }} -{{ if .SynopsisArgs }} -` + "```" + ` -{{ range $v := .SynopsisArgs }}{{ $v }}{{ end }}` + "```" + ` -{{ end }}{{ if .App.Description }} -# DESCRIPTION - -{{ .App.Description }} -{{ end }} -**Usage**: - -` + "```" + `{{ if .App.UsageText }} -{{ .App.UsageText }} -{{ else }} -{{ .App.Name }} [GLOBAL OPTIONS] command [COMMAND OPTIONS] [ARGUMENTS...] -{{ end }}` + "```" + ` -{{ if .GlobalArgs }} -# GLOBAL OPTIONS -{{ range $v := .GlobalArgs }} -{{ $v }}{{ end }} -{{ end }}{{ if .Commands }} -# COMMANDS -{{ range $v := .Commands }} -{{ $v }}{{ end }}{{ end }}` - -var FishCompletionTemplate = `# {{ .App.Name }} fish shell completion - -function __fish_{{ .App.Name }}_no_subcommand --description 'Test if there has been any subcommand yet' +function __fish_{{ .Command.Name }}_no_subcommand --description 'Test if there has been any subcommand yet' for i in (commandline -opc) if contains -- $i{{ range $v := .AllCommands }} {{ $v }}{{ end }} return 1 diff --git a/vendor/github.com/urfave/cli/v3/value_source.go b/vendor/github.com/urfave/cli/v3/value_source.go new file mode 100644 index 00000000..7d3f7ee4 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/value_source.go @@ -0,0 +1,145 @@ +package cli + +import ( + "fmt" + "os" + "strings" +) + +// ValueSource is a source which can be used to look up a value, +// typically for use with a cli.Flag +type ValueSource interface { + fmt.Stringer + fmt.GoStringer + + // Lookup returns the value from the source and if it was found + // or returns an empty string and false + Lookup() (string, bool) +} + +// ValueSourceChain contains an ordered series of ValueSource that +// allows for lookup where the first ValueSource to resolve is +// returned +type ValueSourceChain struct { + Chain []ValueSource +} + +func NewValueSourceChain(src ...ValueSource) ValueSourceChain { + return ValueSourceChain{ + Chain: src, + } +} + +func (vsc *ValueSourceChain) Append(other ValueSourceChain) { + vsc.Chain = append(vsc.Chain, other.Chain...) +} + +func (vsc *ValueSourceChain) EnvKeys() []string { + vals := []string{} + + for _, src := range vsc.Chain { + if v, ok := src.(*envVarValueSource); ok { + vals = append(vals, v.Key) + } + } + + return vals +} + +func (vsc *ValueSourceChain) String() string { + s := []string{} + + for _, vs := range vsc.Chain { + s = append(s, vs.String()) + } + + return strings.Join(s, ",") +} + +func (vsc *ValueSourceChain) GoString() string { + s := []string{} + + for _, vs := range vsc.Chain { + s = append(s, vs.GoString()) + } + + return fmt.Sprintf("&ValueSourceChain{Chain:{%[1]s}}", strings.Join(s, ",")) +} + +func (vsc *ValueSourceChain) Lookup() (string, bool) { + s, _, ok := vsc.LookupWithSource() + return s, ok +} + +func (vsc *ValueSourceChain) LookupWithSource() (string, ValueSource, bool) { + for _, src := range vsc.Chain { + if value, found := src.Lookup(); found { + return value, src, true + } + } + + return "", nil, false +} + +// envVarValueSource encapsulates a ValueSource from an environment variable +type envVarValueSource struct { + Key string +} + +func (e *envVarValueSource) Lookup() (string, bool) { + return os.LookupEnv(strings.TrimSpace(string(e.Key))) +} + +func (e *envVarValueSource) String() string { return fmt.Sprintf("environment variable %[1]q", e.Key) } +func (e *envVarValueSource) GoString() string { + return fmt.Sprintf("&envVarValueSource{Key:%[1]q}", e.Key) +} + +func EnvVar(key string) ValueSource { + return &envVarValueSource{ + Key: key, + } +} + +// EnvVars is a helper function to encapsulate a number of +// envVarValueSource together as a ValueSourceChain +func EnvVars(keys ...string) ValueSourceChain { + vsc := ValueSourceChain{Chain: []ValueSource{}} + + for _, key := range keys { + vsc.Chain = append(vsc.Chain, &envVarValueSource{Key: key}) + } + + return vsc +} + +// fileValueSource encapsulates a ValueSource from a file +type fileValueSource struct { + Path string +} + +func (f *fileValueSource) Lookup() (string, bool) { + data, err := os.ReadFile(f.Path) + return string(data), err == nil +} + +func (f *fileValueSource) String() string { return fmt.Sprintf("file %[1]q", f.Path) } +func (f *fileValueSource) GoString() string { + return fmt.Sprintf("&fileValueSource{Path:%[1]q}", f.Path) +} + +func File(path string) ValueSource { + return &fileValueSource{Path: path} +} + +// Files is a helper function to encapsulate a number of +// fileValueSource together as a ValueSourceChain +func Files(paths ...string) ValueSourceChain { + vsc := ValueSourceChain{Chain: []ValueSource{}} + + for _, path := range paths { + vsc.Chain = append(vsc.Chain, &fileValueSource{Path: path}) + } + + return vsc +} diff --git a/vendor/github.com/xeipuuv/gojsonschema/schema.go b/vendor/github.com/xeipuuv/gojsonschema/schema.go index 4150ad90..9e93cd79 100644 --- a/vendor/github.com/xeipuuv/gojsonschema/schema.go +++ b/vendor/github.com/xeipuuv/gojsonschema/schema.go @@ -73,6 +73,7 @@ func (d *Schema) SetRootSchemaName(name string) { // Pretty long function ( sorry :) )... but pretty straight forward, repetitive and boring // Not much magic involved here, most of the job is to validate the key names and their values, // then the values are copied into subSchema struct +// func (d *Schema) parseSchema(documentNode interface{}, currentSchema *subSchema) error { if currentSchema.draft == nil { diff --git a/vendor/github.com/xeipuuv/gojsonschema/schemaLoader.go b/vendor/github.com/xeipuuv/gojsonschema/schemaLoader.go index 09ff0305..20db0c1f 100644 --- a/vendor/github.com/xeipuuv/gojsonschema/schemaLoader.go +++ b/vendor/github.com/xeipuuv/gojsonschema/schemaLoader.go @@ -119,7 +119,7 @@ func (sl *SchemaLoader) AddSchemas(loaders ...JSONLoader) error { return nil } -// AddSchema adds a schema under the provided URL to the schema cache +//AddSchema adds a schema under the provided URL to the schema cache func (sl *SchemaLoader) AddSchema(url string, loader JSONLoader) error { ref, err := gojsonreference.NewJsonReference(url) diff --git a/vendor/github.com/xrash/smetrics/.travis.yml b/vendor/github.com/xrash/smetrics/.travis.yml deleted file mode 100644 index d1cd67ff..00000000 --- a/vendor/github.com/xrash/smetrics/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: go -go: - - 1.11 - - 1.12 - - 1.13 - - 1.14.x - - master -script: - - cd tests && make diff --git a/vendor/github.com/xrash/smetrics/LICENSE b/vendor/github.com/xrash/smetrics/LICENSE deleted file mode 100644 index 80445682..00000000 --- a/vendor/github.com/xrash/smetrics/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (C) 2016 Felipe da Cunha Gonçalves -All Rights Reserved. - -MIT LICENSE - -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/xrash/smetrics/README.md b/vendor/github.com/xrash/smetrics/README.md deleted file mode 100644 index 5e0c1a46..00000000 --- a/vendor/github.com/xrash/smetrics/README.md +++ /dev/null @@ -1,49 +0,0 @@ -[![Build Status](https://travis-ci.org/xrash/smetrics.svg?branch=master)](http://travis-ci.org/xrash/smetrics) - -# smetrics - -`smetrics` is "string metrics". - -Package smetrics provides a bunch of algorithms for calculating the distance between strings. - -There are implementations for calculating the popular Levenshtein distance (aka Edit Distance or Wagner-Fischer), as well as the Jaro distance, the Jaro-Winkler distance, and more. - -# How to import - -```go -import "github.com/xrash/smetrics" -``` - -# Documentation - -Go to [https://pkg.go.dev/github.com/xrash/smetrics](https://pkg.go.dev/github.com/xrash/smetrics) for complete documentation. - -# Example - -```go -package main - -import ( - "github.com/xrash/smetrics" -) - -func main() { - smetrics.WagnerFischer("POTATO", "POTATTO", 1, 1, 2) - smetrics.WagnerFischer("MOUSE", "HOUSE", 2, 2, 4) - - smetrics.Ukkonen("POTATO", "POTATTO", 1, 1, 2) - smetrics.Ukkonen("MOUSE", "HOUSE", 2, 2, 4) - - smetrics.Jaro("AL", "AL") - smetrics.Jaro("MARTHA", "MARHTA") - - smetrics.JaroWinkler("AL", "AL", 0.7, 4) - smetrics.JaroWinkler("MARTHA", "MARHTA", 0.7, 4) - - smetrics.Soundex("Euler") - smetrics.Soundex("Ellery") - - smetrics.Hamming("aaa", "aaa") - smetrics.Hamming("aaa", "aab") -} -``` diff --git a/vendor/github.com/xrash/smetrics/doc.go b/vendor/github.com/xrash/smetrics/doc.go deleted file mode 100644 index 21bc986c..00000000 --- a/vendor/github.com/xrash/smetrics/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Package smetrics provides a bunch of algorithms for calculating -the distance between strings. - -There are implementations for calculating the popular Levenshtein -distance (aka Edit Distance or Wagner-Fischer), as well as the Jaro -distance, the Jaro-Winkler distance, and more. - -For the Levenshtein distance, you can use the functions WagnerFischer() -and Ukkonen(). Read the documentation on these functions. - -For the Jaro and Jaro-Winkler algorithms, check the functions -Jaro() and JaroWinkler(). Read the documentation on these functions. - -For the Soundex algorithm, check the function Soundex(). - -For the Hamming distance algorithm, check the function Hamming(). -*/ -package smetrics diff --git a/vendor/github.com/xrash/smetrics/hamming.go b/vendor/github.com/xrash/smetrics/hamming.go deleted file mode 100644 index 505d3e5d..00000000 --- a/vendor/github.com/xrash/smetrics/hamming.go +++ /dev/null @@ -1,25 +0,0 @@ -package smetrics - -import ( - "fmt" -) - -// The Hamming distance is the minimum number of substitutions required to change string A into string B. Both strings must have the same size. If the strings have different sizes, the function returns an error. -func Hamming(a, b string) (int, error) { - al := len(a) - bl := len(b) - - if al != bl { - return -1, fmt.Errorf("strings are not equal (len(a)=%d, len(b)=%d)", al, bl) - } - - var difference = 0 - - for i := range a { - if a[i] != b[i] { - difference = difference + 1 - } - } - - return difference, nil -} diff --git a/vendor/github.com/xrash/smetrics/jaro-winkler.go b/vendor/github.com/xrash/smetrics/jaro-winkler.go deleted file mode 100644 index abdb2888..00000000 --- a/vendor/github.com/xrash/smetrics/jaro-winkler.go +++ /dev/null @@ -1,28 +0,0 @@ -package smetrics - -import ( - "math" -) - -// The Jaro-Winkler distance. The result is 1 for equal strings, and 0 for completely different strings. It is commonly used on Record Linkage stuff, thus it tries to be accurate for common typos when writing real names such as person names and street names. -// Jaro-Winkler is a modification of the Jaro algorithm. It works by first running Jaro, then boosting the score of exact matches at the beginning of the strings. Because of that, it introduces two more parameters: the boostThreshold and the prefixSize. These are commonly set to 0.7 and 4, respectively. -func JaroWinkler(a, b string, boostThreshold float64, prefixSize int) float64 { - j := Jaro(a, b) - - if j <= boostThreshold { - return j - } - - prefixSize = int(math.Min(float64(len(a)), math.Min(float64(prefixSize), float64(len(b))))) - - var prefixMatch float64 - for i := 0; i < prefixSize; i++ { - if a[i] == b[i] { - prefixMatch++ - } else { - break - } - } - - return j + 0.1*prefixMatch*(1.0-j) -} diff --git a/vendor/github.com/xrash/smetrics/jaro.go b/vendor/github.com/xrash/smetrics/jaro.go deleted file mode 100644 index 75f924e1..00000000 --- a/vendor/github.com/xrash/smetrics/jaro.go +++ /dev/null @@ -1,86 +0,0 @@ -package smetrics - -import ( - "math" -) - -// The Jaro distance. The result is 1 for equal strings, and 0 for completely different strings. -func Jaro(a, b string) float64 { - // If both strings are zero-length, they are completely equal, - // therefore return 1. - if len(a) == 0 && len(b) == 0 { - return 1 - } - - // If one string is zero-length, strings are completely different, - // therefore return 0. - if len(a) == 0 || len(b) == 0 { - return 0 - } - - // Define the necessary variables for the algorithm. - la := float64(len(a)) - lb := float64(len(b)) - matchRange := int(math.Max(0, math.Floor(math.Max(la, lb)/2.0)-1)) - matchesA := make([]bool, len(a)) - matchesB := make([]bool, len(b)) - var matches float64 = 0 - - // Step 1: Matches - // Loop through each character of the first string, - // looking for a matching character in the second string. - for i := 0; i < len(a); i++ { - start := int(math.Max(0, float64(i-matchRange))) - end := int(math.Min(lb-1, float64(i+matchRange))) - - for j := start; j <= end; j++ { - if matchesB[j] { - continue - } - - if a[i] == b[j] { - matchesA[i] = true - matchesB[j] = true - matches++ - break - } - } - } - - // If there are no matches, strings are completely different, - // therefore return 0. - if matches == 0 { - return 0 - } - - // Step 2: Transpositions - // Loop through the matches' arrays, looking for - // unaligned matches. Count the number of unaligned matches. - unaligned := 0 - j := 0 - for i := 0; i < len(a); i++ { - if !matchesA[i] { - continue - } - - for !matchesB[j] { - j++ - } - - if a[i] != b[j] { - unaligned++ - } - - j++ - } - - // The number of unaligned matches divided by two, is the number of _transpositions_. - transpositions := math.Floor(float64(unaligned / 2)) - - // Jaro distance is the average between these three numbers: - // 1. matches / length of string A - // 2. matches / length of string B - // 3. (matches - transpositions/matches) - // So, all that divided by three is the final result. - return ((matches / la) + (matches / lb) + ((matches - transpositions) / matches)) / 3.0 -} diff --git a/vendor/github.com/xrash/smetrics/soundex.go b/vendor/github.com/xrash/smetrics/soundex.go deleted file mode 100644 index 18c3aef7..00000000 --- a/vendor/github.com/xrash/smetrics/soundex.go +++ /dev/null @@ -1,63 +0,0 @@ -package smetrics - -import ( - "strings" -) - -// The Soundex encoding. It is a phonetic algorithm that considers how the words sound in English. Soundex maps a string to a 4-byte code consisting of the first letter of the original string and three numbers. Strings that sound similar should map to the same code. -func Soundex(s string) string { - b := strings.Builder{} - b.Grow(4) - - p := s[0] - if p <= 'z' && p >= 'a' { - p -= 32 // convert to uppercase - } - b.WriteByte(p) - - n := 0 - for i := 1; i < len(s); i++ { - c := s[i] - - if c <= 'z' && c >= 'a' { - c -= 32 // convert to uppercase - } else if c < 'A' || c > 'Z' { - continue - } - - if c == p { - continue - } - - p = c - - switch c { - case 'B', 'P', 'F', 'V': - c = '1' - case 'C', 'S', 'K', 'G', 'J', 'Q', 'X', 'Z': - c = '2' - case 'D', 'T': - c = '3' - case 'L': - c = '4' - case 'M', 'N': - c = '5' - case 'R': - c = '6' - default: - continue - } - - b.WriteByte(c) - n++ - if n == 3 { - break - } - } - - for i := n; i < 3; i++ { - b.WriteByte('0') - } - - return b.String() -} diff --git a/vendor/github.com/xrash/smetrics/ukkonen.go b/vendor/github.com/xrash/smetrics/ukkonen.go deleted file mode 100644 index 3c5579cd..00000000 --- a/vendor/github.com/xrash/smetrics/ukkonen.go +++ /dev/null @@ -1,94 +0,0 @@ -package smetrics - -import ( - "math" -) - -// The Ukkonen algorithm for calculating the Levenshtein distance. The algorithm is described in http://www.cs.helsinki.fi/u/ukkonen/InfCont85.PDF, or in docs/InfCont85.PDF. It runs on O(t . min(m, n)) where t is the actual distance between strings a and b. It needs O(min(t, m, n)) space. This function might be preferred over WagnerFischer() for *very* similar strings. But test it out yourself. -// The first two parameters are the two strings to be compared. The last three parameters are the insertion cost, the deletion cost and the substitution cost. These are normally defined as 1, 1 and 2 respectively. -func Ukkonen(a, b string, icost, dcost, scost int) int { - var lowerCost int - - if icost < dcost && icost < scost { - lowerCost = icost - } else if dcost < scost { - lowerCost = dcost - } else { - lowerCost = scost - } - - infinite := math.MaxInt32 / 2 - - var r []int - var k, kprime, p, t int - var ins, del, sub int - - if len(a) > len(b) { - t = (len(a) - len(b) + 1) * lowerCost - } else { - t = (len(b) - len(a) + 1) * lowerCost - } - - for { - if (t / lowerCost) < (len(b) - len(a)) { - continue - } - - // This is the right damn thing since the original Ukkonen - // paper minimizes the expression result only, but the uncommented version - // doesn't need to deal with floats so it's faster. - // p = int(math.Floor(0.5*((float64(t)/float64(lowerCost)) - float64(len(b) - len(a))))) - p = ((t / lowerCost) - (len(b) - len(a))) / 2 - - k = -p - kprime = k - - rowlength := (len(b) - len(a)) + (2 * p) - - r = make([]int, rowlength+2) - - for i := 0; i < rowlength+2; i++ { - r[i] = infinite - } - - for i := 0; i <= len(a); i++ { - for j := 0; j <= rowlength; j++ { - if i == j+k && i == 0 { - r[j] = 0 - } else { - if j-1 < 0 { - ins = infinite - } else { - ins = r[j-1] + icost - } - - del = r[j+1] + dcost - sub = r[j] + scost - - if i-1 < 0 || i-1 >= len(a) || j+k-1 >= len(b) || j+k-1 < 0 { - sub = infinite - } else if a[i-1] == b[j+k-1] { - sub = r[j] - } - - if ins < del && ins < sub { - r[j] = ins - } else if del < sub { - r[j] = del - } else { - r[j] = sub - } - } - } - k++ - } - - if r[(len(b)-len(a))+(2*p)+kprime] <= t { - break - } else { - t *= 2 - } - } - - return r[(len(b)-len(a))+(2*p)+kprime] -} diff --git a/vendor/github.com/xrash/smetrics/wagner-fischer.go b/vendor/github.com/xrash/smetrics/wagner-fischer.go deleted file mode 100644 index 9883aea0..00000000 --- a/vendor/github.com/xrash/smetrics/wagner-fischer.go +++ /dev/null @@ -1,48 +0,0 @@ -package smetrics - -// The Wagner-Fischer algorithm for calculating the Levenshtein distance. -// The first two parameters are the two strings to be compared. The last three parameters are the insertion cost, the deletion cost and the substitution cost. These are normally defined as 1, 1 and 2 respectively. -func WagnerFischer(a, b string, icost, dcost, scost int) int { - - // Allocate both rows. - row1 := make([]int, len(b)+1) - row2 := make([]int, len(b)+1) - var tmp []int - - // Initialize the first row. - for i := 1; i <= len(b); i++ { - row1[i] = i * icost - } - - // For each row... - for i := 1; i <= len(a); i++ { - row2[0] = i * dcost - - // For each column... - for j := 1; j <= len(b); j++ { - if a[i-1] == b[j-1] { - row2[j] = row1[j-1] - } else { - ins := row2[j-1] + icost - del := row1[j] + dcost - sub := row1[j-1] + scost - - if ins < del && ins < sub { - row2[j] = ins - } else if del < sub { - row2[j] = del - } else { - row2[j] = sub - } - } - } - - // Swap the rows at the end of each row. - tmp = row1 - row1 = row2 - row2 = tmp - } - - // Because we swapped the rows, the final result is in row1 instead of row2. - return row1[len(row1)-1] -} diff --git a/vendor/go.opentelemetry.io/proto/otlp/metrics/v1/metrics.pb.go b/vendor/go.opentelemetry.io/proto/otlp/metrics/v1/metrics.pb.go index b7dfed6d..bca86dc4 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/metrics/v1/metrics.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/metrics/v1/metrics.pb.go @@ -153,7 +153,8 @@ func (AggregationTemporality) EnumDescriptor() ([]byte, []int) { // enum is a bit-mask. To test the presence of a single flag in the flags of // a data point, for example, use an expression like: // -// (point.flags & DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK) == DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK +// (point.flags & DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK) == DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK +// type DataPointFlags int32 const ( @@ -414,68 +415,66 @@ func (x *ScopeMetrics) GetSchemaUrl() string { // Defines a Metric which has one or more timeseries. The following is a // brief summary of the Metric data model. For more details, see: // -// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/data-model.md +// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/data-model.md +// // // The data model and relation between entities is shown in the // diagram below. Here, "DataPoint" is the term used to refer to any // one of the specific data point value types, and "points" is the term used // to refer to any one of the lists of points contained in the Metric. // -// - Metric is composed of a metadata and data. -// -// - Metadata part contains a name, description, unit. -// -// - Data is one of the possible types (Sum, Gauge, Histogram, Summary). -// -// - DataPoint contains timestamps, attributes, and one of the possible value type -// fields. +// - Metric is composed of a metadata and data. +// - Metadata part contains a name, description, unit. +// - Data is one of the possible types (Sum, Gauge, Histogram, Summary). +// - DataPoint contains timestamps, attributes, and one of the possible value type +// fields. // // Metric -// +------------+ -// |name | -// |description | -// |unit | +------------------------------------+ -// |data |---> |Gauge, Sum, Histogram, Summary, ... | -// +------------+ +------------------------------------+ +// +------------+ +// |name | +// |description | +// |unit | +------------------------------------+ +// |data |---> |Gauge, Sum, Histogram, Summary, ... | +// +------------+ +------------------------------------+ // -// Data [One of Gauge, Sum, Histogram, Summary, ...] -// +-----------+ -// |... | // Metadata about the Data. -// |points |--+ -// +-----------+ | -// | +---------------------------+ -// | |DataPoint 1 | -// v |+------+------+ +------+ | -// +-----+ ||label |label |...|label | | -// | 1 |-->||value1|value2|...|valueN| | -// +-----+ |+------+------+ +------+ | -// | . | |+-----+ | -// | . | ||value| | -// | . | |+-----+ | -// | . | +---------------------------+ -// | . | . -// | . | . -// | . | . -// | . | +---------------------------+ -// | . | |DataPoint M | -// +-----+ |+------+------+ +------+ | -// | M |-->||label |label |...|label | | -// +-----+ ||value1|value2|...|valueN| | -// |+------+------+ +------+ | -// |+-----+ | -// ||value| | -// |+-----+ | -// +---------------------------+ +// Data [One of Gauge, Sum, Histogram, Summary, ...] +// +-----------+ +// |... | // Metadata about the Data. +// |points |--+ +// +-----------+ | +// | +---------------------------+ +// | |DataPoint 1 | +// v |+------+------+ +------+ | +// +-----+ ||label |label |...|label | | +// | 1 |-->||value1|value2|...|valueN| | +// +-----+ |+------+------+ +------+ | +// | . | |+-----+ | +// | . | ||value| | +// | . | |+-----+ | +// | . | +---------------------------+ +// | . | . +// | . | . +// | . | . +// | . | +---------------------------+ +// | . | |DataPoint M | +// +-----+ |+------+------+ +------+ | +// | M |-->||label |label |...|label | | +// +-----+ ||value1|value2|...|valueN| | +// |+------+------+ +------+ | +// |+-----+ | +// ||value| | +// |+-----+ | +// +---------------------------+ // // Each distinct type of DataPoint represents the output of a specific // aggregation function, the result of applying the DataPoint's // associated function of to one or more measurements. // // All DataPoint types have three common fields: -// - Attributes includes key-value pairs associated with the data point -// - TimeUnixNano is required, set to the end time of the aggregation -// - StartTimeUnixNano is optional, but strongly encouraged for DataPoints -// having an AggregationTemporality field, as discussed below. +// - Attributes includes key-value pairs associated with the data point +// - TimeUnixNano is required, set to the end time of the aggregation +// - StartTimeUnixNano is optional, but strongly encouraged for DataPoints +// having an AggregationTemporality field, as discussed below. // // Both TimeUnixNano and StartTimeUnixNano values are expressed as // UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January 1970. @@ -1295,6 +1294,7 @@ func (x *HistogramDataPoint) GetMax() float64 { // time-varying values of a ExponentialHistogram of double values. A ExponentialHistogram contains // summary statistics for a population of values, it may optionally contain the // distribution of those values across a set of buckets. +// type ExponentialHistogramDataPoint struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go b/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go index 2d0e1d2f..d7099c35 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go @@ -42,7 +42,7 @@ const ( // a bit-mask. To extract the bit-field, for example, use an // expression like: // -// (span.flags & SPAN_FLAGS_TRACE_FLAGS_MASK) +// (span.flags & SPAN_FLAGS_TRACE_FLAGS_MASK) // // See https://www.w3.org/TR/trace-context-2/#trace-flags for the flag definitions. // diff --git a/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go b/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go index f97296d2..312ae6ac 100644 --- a/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go @@ -816,10 +816,10 @@ func Lstat(path string, stat *Stat_t) (err error) { // for checking symlinks begins with $VERSION/ $SYSNAME/ $SYSSYMR/ $SYSSYMA/ func isSpecialPath(path []byte) (v bool) { var special = [4][8]byte{ - {'V', 'E', 'R', 'S', 'I', 'O', 'N', '/'}, - {'S', 'Y', 'S', 'N', 'A', 'M', 'E', '/'}, - {'S', 'Y', 'S', 'S', 'Y', 'M', 'R', '/'}, - {'S', 'Y', 'S', 'S', 'Y', 'M', 'A', '/'}} + [8]byte{'V', 'E', 'R', 'S', 'I', 'O', 'N', '/'}, + [8]byte{'S', 'Y', 'S', 'N', 'A', 'M', 'E', '/'}, + [8]byte{'S', 'Y', 'S', 'S', 'Y', 'M', 'R', '/'}, + [8]byte{'S', 'Y', 'S', 'S', 'Y', 'M', 'A', '/'}} var i, j int for i = 0; i < len(special); i++ { diff --git a/vendor/golang.org/x/text/internal/language/lookup.go b/vendor/golang.org/x/text/internal/language/lookup.go index f1443966..231b4fbd 100644 --- a/vendor/golang.org/x/text/internal/language/lookup.go +++ b/vendor/golang.org/x/text/internal/language/lookup.go @@ -360,39 +360,39 @@ var ( // grandfatheredMap holds a mapping from legacy and grandfathered tags to // their base language or index to more elaborate tag. grandfatheredMap = map[[maxLen]byte]int16{ - {'a', 'r', 't', '-', 'l', 'o', 'j', 'b', 'a', 'n'}: _jbo, // art-lojban - {'i', '-', 'a', 'm', 'i'}: _ami, // i-ami - {'i', '-', 'b', 'n', 'n'}: _bnn, // i-bnn - {'i', '-', 'h', 'a', 'k'}: _hak, // i-hak - {'i', '-', 'k', 'l', 'i', 'n', 'g', 'o', 'n'}: _tlh, // i-klingon - {'i', '-', 'l', 'u', 'x'}: _lb, // i-lux - {'i', '-', 'n', 'a', 'v', 'a', 'j', 'o'}: _nv, // i-navajo - {'i', '-', 'p', 'w', 'n'}: _pwn, // i-pwn - {'i', '-', 't', 'a', 'o'}: _tao, // i-tao - {'i', '-', 't', 'a', 'y'}: _tay, // i-tay - {'i', '-', 't', 's', 'u'}: _tsu, // i-tsu - {'n', 'o', '-', 'b', 'o', 'k'}: _nb, // no-bok - {'n', 'o', '-', 'n', 'y', 'n'}: _nn, // no-nyn - {'s', 'g', 'n', '-', 'b', 'e', '-', 'f', 'r'}: _sfb, // sgn-BE-FR - {'s', 'g', 'n', '-', 'b', 'e', '-', 'n', 'l'}: _vgt, // sgn-BE-NL - {'s', 'g', 'n', '-', 'c', 'h', '-', 'd', 'e'}: _sgg, // sgn-CH-DE - {'z', 'h', '-', 'g', 'u', 'o', 'y', 'u'}: _cmn, // zh-guoyu - {'z', 'h', '-', 'h', 'a', 'k', 'k', 'a'}: _hak, // zh-hakka - {'z', 'h', '-', 'm', 'i', 'n', '-', 'n', 'a', 'n'}: _nan, // zh-min-nan - {'z', 'h', '-', 'x', 'i', 'a', 'n', 'g'}: _hsn, // zh-xiang + [maxLen]byte{'a', 'r', 't', '-', 'l', 'o', 'j', 'b', 'a', 'n'}: _jbo, // art-lojban + [maxLen]byte{'i', '-', 'a', 'm', 'i'}: _ami, // i-ami + [maxLen]byte{'i', '-', 'b', 'n', 'n'}: _bnn, // i-bnn + [maxLen]byte{'i', '-', 'h', 'a', 'k'}: _hak, // i-hak + [maxLen]byte{'i', '-', 'k', 'l', 'i', 'n', 'g', 'o', 'n'}: _tlh, // i-klingon + [maxLen]byte{'i', '-', 'l', 'u', 'x'}: _lb, // i-lux + [maxLen]byte{'i', '-', 'n', 'a', 'v', 'a', 'j', 'o'}: _nv, // i-navajo + [maxLen]byte{'i', '-', 'p', 'w', 'n'}: _pwn, // i-pwn + [maxLen]byte{'i', '-', 't', 'a', 'o'}: _tao, // i-tao + [maxLen]byte{'i', '-', 't', 'a', 'y'}: _tay, // i-tay + [maxLen]byte{'i', '-', 't', 's', 'u'}: _tsu, // i-tsu + [maxLen]byte{'n', 'o', '-', 'b', 'o', 'k'}: _nb, // no-bok + [maxLen]byte{'n', 'o', '-', 'n', 'y', 'n'}: _nn, // no-nyn + [maxLen]byte{'s', 'g', 'n', '-', 'b', 'e', '-', 'f', 'r'}: _sfb, // sgn-BE-FR + [maxLen]byte{'s', 'g', 'n', '-', 'b', 'e', '-', 'n', 'l'}: _vgt, // sgn-BE-NL + [maxLen]byte{'s', 'g', 'n', '-', 'c', 'h', '-', 'd', 'e'}: _sgg, // sgn-CH-DE + [maxLen]byte{'z', 'h', '-', 'g', 'u', 'o', 'y', 'u'}: _cmn, // zh-guoyu + [maxLen]byte{'z', 'h', '-', 'h', 'a', 'k', 'k', 'a'}: _hak, // zh-hakka + [maxLen]byte{'z', 'h', '-', 'm', 'i', 'n', '-', 'n', 'a', 'n'}: _nan, // zh-min-nan + [maxLen]byte{'z', 'h', '-', 'x', 'i', 'a', 'n', 'g'}: _hsn, // zh-xiang // Grandfathered tags with no modern replacement will be converted as // follows: - {'c', 'e', 'l', '-', 'g', 'a', 'u', 'l', 'i', 's', 'h'}: -1, // cel-gaulish - {'e', 'n', '-', 'g', 'b', '-', 'o', 'e', 'd'}: -2, // en-GB-oed - {'i', '-', 'd', 'e', 'f', 'a', 'u', 'l', 't'}: -3, // i-default - {'i', '-', 'e', 'n', 'o', 'c', 'h', 'i', 'a', 'n'}: -4, // i-enochian - {'i', '-', 'm', 'i', 'n', 'g', 'o'}: -5, // i-mingo - {'z', 'h', '-', 'm', 'i', 'n'}: -6, // zh-min + [maxLen]byte{'c', 'e', 'l', '-', 'g', 'a', 'u', 'l', 'i', 's', 'h'}: -1, // cel-gaulish + [maxLen]byte{'e', 'n', '-', 'g', 'b', '-', 'o', 'e', 'd'}: -2, // en-GB-oed + [maxLen]byte{'i', '-', 'd', 'e', 'f', 'a', 'u', 'l', 't'}: -3, // i-default + [maxLen]byte{'i', '-', 'e', 'n', 'o', 'c', 'h', 'i', 'a', 'n'}: -4, // i-enochian + [maxLen]byte{'i', '-', 'm', 'i', 'n', 'g', 'o'}: -5, // i-mingo + [maxLen]byte{'z', 'h', '-', 'm', 'i', 'n'}: -6, // zh-min // CLDR-specific tag. - {'r', 'o', 'o', 't'}: 0, // root - {'e', 'n', '-', 'u', 's', '-', 'p', 'o', 's', 'i', 'x'}: -7, // en_US_POSIX" + [maxLen]byte{'r', 'o', 'o', 't'}: 0, // root + [maxLen]byte{'e', 'n', '-', 'u', 's', '-', 'p', 'o', 's', 'i', 'x'}: -7, // en_US_POSIX" } altTagIndex = [...]uint8{0, 17, 31, 45, 61, 74, 86, 102} diff --git a/vendor/golang.org/x/text/language/tables.go b/vendor/golang.org/x/text/language/tables.go index d2cb0f0a..a6573dcb 100644 --- a/vendor/golang.org/x/text/language/tables.go +++ b/vendor/golang.org/x/text/language/tables.go @@ -102,9 +102,9 @@ var regionToGroups = []uint8{ // 359 elements } // Size: 383 bytes var paradigmLocales = [][3]uint16{ // 3 elements - 0: {0x139, 0x0, 0x7c}, - 1: {0x13e, 0x0, 0x1f}, - 2: {0x3c0, 0x41, 0xef}, + 0: [3]uint16{0x139, 0x0, 0x7c}, + 1: [3]uint16{0x13e, 0x0, 0x1f}, + 2: [3]uint16{0x3c0, 0x41, 0xef}, } // Size: 42 bytes type mutualIntelligibility struct { diff --git a/vendor/google.golang.org/protobuf/internal/impl/merge_gen.go b/vendor/google.golang.org/protobuf/internal/impl/merge_gen.go index 81982688..8816c274 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/merge_gen.go +++ b/vendor/google.golang.org/protobuf/internal/impl/merge_gen.go @@ -6,6 +6,8 @@ package impl +import () + func mergeBool(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { *dst.Bool() = *src.Bool() } diff --git a/vendor/gopkg.in/warnings.v0/warnings.go b/vendor/gopkg.in/warnings.v0/warnings.go index ee5cebc2..b849d1e3 100644 --- a/vendor/gopkg.in/warnings.v0/warnings.go +++ b/vendor/gopkg.in/warnings.v0/warnings.go @@ -2,19 +2,19 @@ // // A recurring pattern in Go programming is the following: // -// func myfunc(params) error { -// if err := doSomething(...); err != nil { -// return err -// } -// if err := doSomethingElse(...); err != nil { -// return err -// } -// if ok := doAnotherThing(...); !ok { -// return errors.New("my error") -// } -// ... -// return nil -// } +// func myfunc(params) error { +// if err := doSomething(...); err != nil { +// return err +// } +// if err := doSomethingElse(...); err != nil { +// return err +// } +// if ok := doAnotherThing(...); !ok { +// return errors.New("my error") +// } +// ... +// return nil +// } // // This pattern allows interrupting the flow on any received error. But what if // there are errors that should be noted but still not fatal, for which the flow @@ -27,56 +27,57 @@ // along the way. The only requirement is that fatal and non-fatal errors can be // distinguished programmatically; that is a function such as // -// IsFatal(error) bool +// IsFatal(error) bool // // must be implemented. The following is an example of what the above snippet // could look like using the warnings package: // -// import "gopkg.in/warnings.v0" +// import "gopkg.in/warnings.v0" // -// func isFatal(err error) bool { -// _, ok := err.(WarningType) -// return !ok -// } +// func isFatal(err error) bool { +// _, ok := err.(WarningType) +// return !ok +// } // -// func myfunc(params) error { -// c := warnings.NewCollector(isFatal) -// c.FatalWithWarnings = true -// if err := c.Collect(doSomething()); err != nil { -// return err -// } -// if err := c.Collect(doSomethingElse(...)); err != nil { -// return err -// } -// if ok := doAnotherThing(...); !ok { -// if err := c.Collect(errors.New("my error")); err != nil { -// return err -// } -// } -// ... -// return c.Done() -// } +// func myfunc(params) error { +// c := warnings.NewCollector(isFatal) +// c.FatalWithWarnings = true +// if err := c.Collect(doSomething()); err != nil { +// return err +// } +// if err := c.Collect(doSomethingElse(...)); err != nil { +// return err +// } +// if ok := doAnotherThing(...); !ok { +// if err := c.Collect(errors.New("my error")); err != nil { +// return err +// } +// } +// ... +// return c.Done() +// } // // For an example of a non-trivial code base using this library, see // gopkg.in/gcfg.v1 // // Rules for using warnings // -// - ensure that warnings are programmatically distinguishable from fatal -// errors (i.e. implement an isFatal function and any necessary error types) -// - ensure that there is a single Collector instance for a call of each -// exported function -// - ensure that all errors (fatal or warning) are fed through Collect -// - ensure that every time an error is returned, it is one returned by a -// Collector (from Collect or Done) -// - ensure that Collect is never called after Done +// - ensure that warnings are programmatically distinguishable from fatal +// errors (i.e. implement an isFatal function and any necessary error types) +// - ensure that there is a single Collector instance for a call of each +// exported function +// - ensure that all errors (fatal or warning) are fed through Collect +// - ensure that every time an error is returned, it is one returned by a +// Collector (from Collect or Done) +// - ensure that Collect is never called after Done // // TODO // -// - optionally limit the number of warnings (e.g. stop after 20 warnings) (?) -// - consider interaction with contexts -// - go vet-style invocations verifier -// - semi-automatic code converter +// - optionally limit the number of warnings (e.g. stop after 20 warnings) (?) +// - consider interaction with contexts +// - go vet-style invocations verifier +// - semi-automatic code converter +// package warnings // import "gopkg.in/warnings.v0" import ( diff --git a/vendor/gopkg.in/yaml.v2/apic.go b/vendor/gopkg.in/yaml.v2/apic.go index fb2821e1..acf71402 100644 --- a/vendor/gopkg.in/yaml.v2/apic.go +++ b/vendor/gopkg.in/yaml.v2/apic.go @@ -143,7 +143,7 @@ func yaml_emitter_set_canonical(emitter *yaml_emitter_t, canonical bool) { emitter.canonical = canonical } -// // Set the indentation increment. +//// Set the indentation increment. func yaml_emitter_set_indent(emitter *yaml_emitter_t, indent int) { if indent < 2 || indent > 9 { indent = 2 diff --git a/vendor/gopkg.in/yaml.v2/emitterc.go b/vendor/gopkg.in/yaml.v2/emitterc.go index 638a268c..a1c2cc52 100644 --- a/vendor/gopkg.in/yaml.v2/emitterc.go +++ b/vendor/gopkg.in/yaml.v2/emitterc.go @@ -130,9 +130,10 @@ func yaml_emitter_emit(emitter *yaml_emitter_t, event *yaml_event_t) bool { // Check if we need to accumulate more events before emitting. // // We accumulate extra -// - 1 event for DOCUMENT-START -// - 2 events for SEQUENCE-START -// - 3 events for MAPPING-START +// - 1 event for DOCUMENT-START +// - 2 events for SEQUENCE-START +// - 3 events for MAPPING-START +// func yaml_emitter_need_more_events(emitter *yaml_emitter_t) bool { if emitter.events_head == len(emitter.events) { return true diff --git a/vendor/gopkg.in/yaml.v2/parserc.go b/vendor/gopkg.in/yaml.v2/parserc.go index 2883e5c5..81d05dfe 100644 --- a/vendor/gopkg.in/yaml.v2/parserc.go +++ b/vendor/gopkg.in/yaml.v2/parserc.go @@ -170,8 +170,7 @@ func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool // Parse the production: // stream ::= STREAM-START implicit_document? explicit_document* STREAM-END -// -// ************ +// ************ func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -193,12 +192,9 @@ func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) // Parse the productions: // implicit_document ::= block_node DOCUMENT-END* -// -// * -// +// * // explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// -// ************************* +// ************************* func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t, implicit bool) bool { token := peek_token(parser) @@ -281,8 +277,8 @@ func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t // Parse the productions: // explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// *********** // -// *********** func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -303,10 +299,9 @@ func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event // Parse the productions: // implicit_document ::= block_node DOCUMENT-END* -// -// ************* -// +// ************* // explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -337,41 +332,30 @@ func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) // Parse the productions: // block_node_or_indentless_sequence ::= -// -// ALIAS -// ***** -// | properties (block_content | indentless_block_sequence)? -// ********** * -// | block_content | indentless_block_sequence -// * -// +// ALIAS +// ***** +// | properties (block_content | indentless_block_sequence)? +// ********** * +// | block_content | indentless_block_sequence +// * // block_node ::= ALIAS -// -// ***** -// | properties block_content? -// ********** * -// | block_content -// * -// +// ***** +// | properties block_content? +// ********** * +// | block_content +// * // flow_node ::= ALIAS -// -// ***** -// | properties flow_content? -// ********** * -// | flow_content -// * -// +// ***** +// | properties flow_content? +// ********** * +// | flow_content +// * // properties ::= TAG ANCHOR? | ANCHOR TAG? -// -// ************************* -// +// ************************* // block_content ::= block_collection | flow_collection | SCALAR -// -// ****** -// +// ****** // flow_content ::= flow_collection | SCALAR -// -// ****** +// ****** func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, indentless_sequence bool) bool { //defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() @@ -590,8 +574,8 @@ func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, i // Parse the productions: // block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END +// ******************** *********** * ********* // -// ******************** *********** * ********* func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) @@ -643,8 +627,7 @@ func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_e // Parse the productions: // indentless_sequence ::= (BLOCK-ENTRY block_node?)+ -// -// *********** * +// *********** * func yaml_parser_parse_indentless_sequence_entry(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -681,14 +664,14 @@ func yaml_parser_parse_indentless_sequence_entry(parser *yaml_parser_t, event *y // Parse the productions: // block_mapping ::= BLOCK-MAPPING_START +// ******************* +// ((KEY block_node_or_indentless_sequence?)? +// *** * +// (VALUE block_node_or_indentless_sequence?)?)* // -// ******************* -// ((KEY block_node_or_indentless_sequence?)? -// *** * -// (VALUE block_node_or_indentless_sequence?)?)* +// BLOCK-END +// ********* // -// BLOCK-END -// ********* func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) @@ -740,11 +723,13 @@ func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_even // Parse the productions: // block_mapping ::= BLOCK-MAPPING_START // -// ((KEY block_node_or_indentless_sequence?)? +// ((KEY block_node_or_indentless_sequence?)? +// +// (VALUE block_node_or_indentless_sequence?)?)* +// ***** * +// BLOCK-END +// // -// (VALUE block_node_or_indentless_sequence?)?)* -// ***** * -// BLOCK-END func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -772,18 +757,16 @@ func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_ev // Parse the productions: // flow_sequence ::= FLOW-SEQUENCE-START -// -// ******************* -// (flow_sequence_entry FLOW-ENTRY)* -// * ********** -// flow_sequence_entry? -// * -// FLOW-SEQUENCE-END -// ***************** -// +// ******************* +// (flow_sequence_entry FLOW-ENTRY)* +// * ********** +// flow_sequence_entry? +// * +// FLOW-SEQUENCE-END +// ***************** // flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * // -// * func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) @@ -842,10 +825,11 @@ func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_ev return true } +// // Parse the productions: // flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// *** * // -// *** * func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -865,8 +849,8 @@ func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, ev // Parse the productions: // flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// ***** * // -// ***** * func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -889,8 +873,8 @@ func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, // Parse the productions: // flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * // -// * func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -907,17 +891,16 @@ func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, ev // Parse the productions: // flow_mapping ::= FLOW-MAPPING-START -// -// ****************** -// (flow_mapping_entry FLOW-ENTRY)* -// * ********** -// flow_mapping_entry? -// ****************** -// FLOW-MAPPING-END -// **************** -// +// ****************** +// (flow_mapping_entry FLOW-ENTRY)* +// * ********** +// flow_mapping_entry? +// ****************** +// FLOW-MAPPING-END +// **************** // flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// - *** * +// * *** * +// func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) @@ -982,7 +965,8 @@ func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event // Parse the productions: // flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// - ***** * +// * ***** * +// func yaml_parser_parse_flow_mapping_value(parser *yaml_parser_t, event *yaml_event_t, empty bool) bool { token := peek_token(parser) if token == nil { diff --git a/vendor/gopkg.in/yaml.v2/readerc.go b/vendor/gopkg.in/yaml.v2/readerc.go index b0c436c4..7c1f5fac 100644 --- a/vendor/gopkg.in/yaml.v2/readerc.go +++ b/vendor/gopkg.in/yaml.v2/readerc.go @@ -95,7 +95,7 @@ func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { // [Go] This function was changed to guarantee the requested length size at EOF. // The fact we need to do this is pretty awful, but the description above implies - // for that to be the case, and there are tests + // for that to be the case, and there are tests // If the EOF flag is set and the raw buffer is empty, do nothing. if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) { diff --git a/vendor/gopkg.in/yaml.v2/resolve.go b/vendor/gopkg.in/yaml.v2/resolve.go index e29c364b..4120e0c9 100644 --- a/vendor/gopkg.in/yaml.v2/resolve.go +++ b/vendor/gopkg.in/yaml.v2/resolve.go @@ -180,7 +180,7 @@ func resolve(tag string, in string) (rtag string, out interface{}) { return yaml_INT_TAG, uintv } } else if strings.HasPrefix(plain, "-0b") { - intv, err := strconv.ParseInt("-"+plain[3:], 2, 64) + intv, err := strconv.ParseInt("-" + plain[3:], 2, 64) if err == nil { if true || intv == int64(int(intv)) { return yaml_INT_TAG, int(intv) diff --git a/vendor/gopkg.in/yaml.v2/scannerc.go b/vendor/gopkg.in/yaml.v2/scannerc.go index d634dca4..0b9bb603 100644 --- a/vendor/gopkg.in/yaml.v2/scannerc.go +++ b/vendor/gopkg.in/yaml.v2/scannerc.go @@ -1500,11 +1500,11 @@ func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { // Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token. // // Scope: +// %YAML 1.1 # a comment \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // -// %YAML 1.1 # a comment \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool { // Eat '%'. start_mark := parser.mark @@ -1601,11 +1601,11 @@ func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool // Scan the directive name. // // Scope: +// %YAML 1.1 # a comment \n +// ^^^^ +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^ // -// %YAML 1.1 # a comment \n -// ^^^^ -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^ func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark_t, name *[]byte) bool { // Consume the directive name. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { @@ -1640,9 +1640,8 @@ func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark // Scan the value of VERSION-DIRECTIVE. // // Scope: -// -// %YAML 1.1 # a comment \n -// ^^^^^^ +// %YAML 1.1 # a comment \n +// ^^^^^^ func yaml_parser_scan_version_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, major, minor *int8) bool { // Eat whitespaces. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { @@ -1680,11 +1679,10 @@ const max_number_length = 2 // Scan the version number of VERSION-DIRECTIVE. // // Scope: -// -// %YAML 1.1 # a comment \n -// ^ -// %YAML 1.1 # a comment \n -// ^ +// %YAML 1.1 # a comment \n +// ^ +// %YAML 1.1 # a comment \n +// ^ func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool { // Repeat while the next character is digit. @@ -1718,9 +1716,9 @@ func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark // Scan the value of a TAG-DIRECTIVE token. // // Scope: +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ func yaml_parser_scan_tag_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, handle, prefix *[]byte) bool { var handle_value, prefix_value []byte diff --git a/vendor/gopkg.in/yaml.v2/sorter.go b/vendor/gopkg.in/yaml.v2/sorter.go index 2edd7340..4c45e660 100644 --- a/vendor/gopkg.in/yaml.v2/sorter.go +++ b/vendor/gopkg.in/yaml.v2/sorter.go @@ -52,7 +52,7 @@ func (l keyList) Less(i, j int) bool { var ai, bi int var an, bn int64 if ar[i] == '0' || br[i] == '0' { - for j := i - 1; j >= 0 && unicode.IsDigit(ar[j]); j-- { + for j := i-1; j >= 0 && unicode.IsDigit(ar[j]); j-- { if ar[j] != '0' { an = 1 bn = 1 diff --git a/vendor/gopkg.in/yaml.v2/yaml.go b/vendor/gopkg.in/yaml.v2/yaml.go index 03756f6b..30813884 100644 --- a/vendor/gopkg.in/yaml.v2/yaml.go +++ b/vendor/gopkg.in/yaml.v2/yaml.go @@ -2,7 +2,8 @@ // // Source code and other details for the project are available at GitHub: // -// https://github.com/go-yaml/yaml +// https://github.com/go-yaml/yaml +// package yaml import ( @@ -66,15 +67,16 @@ type Marshaler interface { // // For example: // -// type T struct { -// F int `yaml:"a,omitempty"` -// B int -// } -// var t T -// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) +// type T struct { +// F int `yaml:"a,omitempty"` +// B int +// } +// var t T +// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) // // See the documentation of Marshal for the format of tags and a list of // supported tag options. +// func Unmarshal(in []byte, out interface{}) (err error) { return unmarshal(in, out, false) } @@ -164,35 +166,36 @@ func unmarshal(in []byte, out interface{}, strict bool) (err error) { // // The field tag format accepted is: // -// `(...) yaml:"[][,[,]]" (...)` +// `(...) yaml:"[][,[,]]" (...)` // // The following flags are currently supported: // -// omitempty Only include the field if it's not set to the zero -// value for the type or to empty slices or maps. -// Zero valued structs will be omitted if all their public -// fields are zero, unless they implement an IsZero -// method (see the IsZeroer interface type), in which -// case the field will be excluded if IsZero returns true. +// omitempty Only include the field if it's not set to the zero +// value for the type or to empty slices or maps. +// Zero valued structs will be omitted if all their public +// fields are zero, unless they implement an IsZero +// method (see the IsZeroer interface type), in which +// case the field will be excluded if IsZero returns true. // -// flow Marshal using a flow style (useful for structs, -// sequences and maps). +// flow Marshal using a flow style (useful for structs, +// sequences and maps). // -// inline Inline the field, which must be a struct or a map, -// causing all of its fields or keys to be processed as if -// they were part of the outer struct. For maps, keys must -// not conflict with the yaml keys of other struct fields. +// inline Inline the field, which must be a struct or a map, +// causing all of its fields or keys to be processed as if +// they were part of the outer struct. For maps, keys must +// not conflict with the yaml keys of other struct fields. // // In addition, if the key is "-", the field is ignored. // // For example: // -// type T struct { -// F int `yaml:"a,omitempty"` -// B int -// } -// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" -// yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n" +// type T struct { +// F int `yaml:"a,omitempty"` +// B int +// } +// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" +// yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n" +// func Marshal(in interface{}) (out []byte, err error) { defer handleErr(&err) e := newEncoder() diff --git a/vendor/gopkg.in/yaml.v2/yamlh.go b/vendor/gopkg.in/yaml.v2/yamlh.go index 640f9d95..f6a9c8e3 100644 --- a/vendor/gopkg.in/yaml.v2/yamlh.go +++ b/vendor/gopkg.in/yaml.v2/yamlh.go @@ -408,9 +408,7 @@ type yaml_document_t struct { // The number of written bytes should be set to the size_read variable. // // [in,out] data A pointer to an application data specified by -// -// yaml_parser_set_input(). -// +// yaml_parser_set_input(). // [out] buffer The buffer to write the data from the source. // [in] size The size of the buffer. // [out] size_read The actual number of bytes read from the source. @@ -606,14 +604,13 @@ type yaml_parser_t struct { // @a buffer to the output. // // @param[in,out] data A pointer to an application data specified by -// -// yaml_emitter_set_output(). -// +// yaml_emitter_set_output(). // @param[in] buffer The buffer with bytes to be written. // @param[in] size The size of the buffer. // // @returns On success, the handler should return @c 1. If the handler failed, // the returned value should be @c 0. +// type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error type yaml_emitter_state_t int diff --git a/vendor/gopkg.in/yaml.v3/apic.go b/vendor/gopkg.in/yaml.v3/apic.go index 05fd305d..ae7d049f 100644 --- a/vendor/gopkg.in/yaml.v3/apic.go +++ b/vendor/gopkg.in/yaml.v3/apic.go @@ -1,17 +1,17 @@ -// +// // Copyright (c) 2011-2019 Canonical Ltd // Copyright (c) 2006-2010 Kirill Simonov -// +// // 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 diff --git a/vendor/gopkg.in/yaml.v3/emitterc.go b/vendor/gopkg.in/yaml.v3/emitterc.go index dde20e50..0f47c9ca 100644 --- a/vendor/gopkg.in/yaml.v3/emitterc.go +++ b/vendor/gopkg.in/yaml.v3/emitterc.go @@ -162,9 +162,10 @@ func yaml_emitter_emit(emitter *yaml_emitter_t, event *yaml_event_t) bool { // Check if we need to accumulate more events before emitting. // // We accumulate extra -// - 1 event for DOCUMENT-START -// - 2 events for SEQUENCE-START -// - 3 events for MAPPING-START +// - 1 event for DOCUMENT-START +// - 2 events for SEQUENCE-START +// - 3 events for MAPPING-START +// func yaml_emitter_need_more_events(emitter *yaml_emitter_t) bool { if emitter.events_head == len(emitter.events) { return true @@ -240,7 +241,7 @@ func yaml_emitter_increase_indent(emitter *yaml_emitter_t, flow, indentless bool emitter.indent += 2 } else { // Everything else aligns to the chosen indentation. - emitter.indent = emitter.best_indent * ((emitter.indent + emitter.best_indent) / emitter.best_indent) + emitter.indent = emitter.best_indent*((emitter.indent+emitter.best_indent)/emitter.best_indent) } } return true diff --git a/vendor/gopkg.in/yaml.v3/parserc.go b/vendor/gopkg.in/yaml.v3/parserc.go index 25fe8236..268558a0 100644 --- a/vendor/gopkg.in/yaml.v3/parserc.go +++ b/vendor/gopkg.in/yaml.v3/parserc.go @@ -227,8 +227,7 @@ func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool // Parse the production: // stream ::= STREAM-START implicit_document? explicit_document* STREAM-END -// -// ************ +// ************ func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -250,12 +249,9 @@ func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) // Parse the productions: // implicit_document ::= block_node DOCUMENT-END* -// -// * -// +// * // explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// -// ************************* +// ************************* func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t, implicit bool) bool { token := peek_token(parser) @@ -360,8 +356,8 @@ func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t // Parse the productions: // explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// *********** // -// *********** func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -383,10 +379,9 @@ func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event // Parse the productions: // implicit_document ::= block_node DOCUMENT-END* -// -// ************* -// +// ************* // explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +// func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -433,41 +428,30 @@ func yaml_parser_set_event_comments(parser *yaml_parser_t, event *yaml_event_t) // Parse the productions: // block_node_or_indentless_sequence ::= -// -// ALIAS -// ***** -// | properties (block_content | indentless_block_sequence)? -// ********** * -// | block_content | indentless_block_sequence -// * -// +// ALIAS +// ***** +// | properties (block_content | indentless_block_sequence)? +// ********** * +// | block_content | indentless_block_sequence +// * // block_node ::= ALIAS -// -// ***** -// | properties block_content? -// ********** * -// | block_content -// * -// +// ***** +// | properties block_content? +// ********** * +// | block_content +// * // flow_node ::= ALIAS -// -// ***** -// | properties flow_content? -// ********** * -// | flow_content -// * -// +// ***** +// | properties flow_content? +// ********** * +// | flow_content +// * // properties ::= TAG ANCHOR? | ANCHOR TAG? -// -// ************************* -// +// ************************* // block_content ::= block_collection | flow_collection | SCALAR -// -// ****** -// +// ****** // flow_content ::= flow_collection | SCALAR -// -// ****** +// ****** func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, indentless_sequence bool) bool { //defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() @@ -698,8 +682,8 @@ func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, i // Parse the productions: // block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END +// ******************** *********** * ********* // -// ******************** *********** * ********* func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) @@ -756,8 +740,7 @@ func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_e // Parse the productions: // indentless_sequence ::= (BLOCK-ENTRY block_node?)+ -// -// *********** * +// *********** * func yaml_parser_parse_indentless_sequence_entry(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -822,14 +805,14 @@ func yaml_parser_split_stem_comment(parser *yaml_parser_t, stem_len int) { // Parse the productions: // block_mapping ::= BLOCK-MAPPING_START +// ******************* +// ((KEY block_node_or_indentless_sequence?)? +// *** * +// (VALUE block_node_or_indentless_sequence?)?)* // -// ******************* -// ((KEY block_node_or_indentless_sequence?)? -// *** * -// (VALUE block_node_or_indentless_sequence?)?)* +// BLOCK-END +// ********* // -// BLOCK-END -// ********* func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) @@ -898,11 +881,13 @@ func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_even // Parse the productions: // block_mapping ::= BLOCK-MAPPING_START // -// ((KEY block_node_or_indentless_sequence?)? +// ((KEY block_node_or_indentless_sequence?)? +// +// (VALUE block_node_or_indentless_sequence?)?)* +// ***** * +// BLOCK-END +// // -// (VALUE block_node_or_indentless_sequence?)?)* -// ***** * -// BLOCK-END func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -930,18 +915,16 @@ func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_ev // Parse the productions: // flow_sequence ::= FLOW-SEQUENCE-START -// -// ******************* -// (flow_sequence_entry FLOW-ENTRY)* -// * ********** -// flow_sequence_entry? -// * -// FLOW-SEQUENCE-END -// ***************** -// +// ******************* +// (flow_sequence_entry FLOW-ENTRY)* +// * ********** +// flow_sequence_entry? +// * +// FLOW-SEQUENCE-END +// ***************** // flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * // -// * func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) @@ -1004,10 +987,11 @@ func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_ev return true } +// // Parse the productions: // flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// *** * // -// *** * func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -1027,8 +1011,8 @@ func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, ev // Parse the productions: // flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// ***** * // -// ***** * func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -1051,8 +1035,8 @@ func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, // Parse the productions: // flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +// * // -// * func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, event *yaml_event_t) bool { token := peek_token(parser) if token == nil { @@ -1069,17 +1053,16 @@ func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, ev // Parse the productions: // flow_mapping ::= FLOW-MAPPING-START -// -// ****************** -// (flow_mapping_entry FLOW-ENTRY)* -// * ********** -// flow_mapping_entry? -// ****************** -// FLOW-MAPPING-END -// **************** -// +// ****************** +// (flow_mapping_entry FLOW-ENTRY)* +// * ********** +// flow_mapping_entry? +// ****************** +// FLOW-MAPPING-END +// **************** // flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// - *** * +// * *** * +// func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { if first { token := peek_token(parser) @@ -1145,7 +1128,8 @@ func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event // Parse the productions: // flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// - ***** * +// * ***** * +// func yaml_parser_parse_flow_mapping_value(parser *yaml_parser_t, event *yaml_event_t, empty bool) bool { token := peek_token(parser) if token == nil { diff --git a/vendor/gopkg.in/yaml.v3/readerc.go b/vendor/gopkg.in/yaml.v3/readerc.go index 56af2453..b7de0a89 100644 --- a/vendor/gopkg.in/yaml.v3/readerc.go +++ b/vendor/gopkg.in/yaml.v3/readerc.go @@ -1,17 +1,17 @@ -// +// // Copyright (c) 2011-2019 Canonical Ltd // Copyright (c) 2006-2010 Kirill Simonov -// +// // 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 diff --git a/vendor/gopkg.in/yaml.v3/scannerc.go b/vendor/gopkg.in/yaml.v3/scannerc.go index 30b1f089..ca007010 100644 --- a/vendor/gopkg.in/yaml.v3/scannerc.go +++ b/vendor/gopkg.in/yaml.v3/scannerc.go @@ -1614,11 +1614,11 @@ func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { // Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token. // // Scope: +// %YAML 1.1 # a comment \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // -// %YAML 1.1 # a comment \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool { // Eat '%'. start_mark := parser.mark @@ -1719,11 +1719,11 @@ func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool // Scan the directive name. // // Scope: +// %YAML 1.1 # a comment \n +// ^^^^ +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^ // -// %YAML 1.1 # a comment \n -// ^^^^ -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^ func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark_t, name *[]byte) bool { // Consume the directive name. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { @@ -1758,9 +1758,8 @@ func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark // Scan the value of VERSION-DIRECTIVE. // // Scope: -// -// %YAML 1.1 # a comment \n -// ^^^^^^ +// %YAML 1.1 # a comment \n +// ^^^^^^ func yaml_parser_scan_version_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, major, minor *int8) bool { // Eat whitespaces. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { @@ -1798,11 +1797,10 @@ const max_number_length = 2 // Scan the version number of VERSION-DIRECTIVE. // // Scope: -// -// %YAML 1.1 # a comment \n -// ^ -// %YAML 1.1 # a comment \n -// ^ +// %YAML 1.1 # a comment \n +// ^ +// %YAML 1.1 # a comment \n +// ^ func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool { // Repeat while the next character is digit. @@ -1836,9 +1834,9 @@ func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark // Scan the value of a TAG-DIRECTIVE token. // // Scope: +// %TAG !yaml! tag:yaml.org,2002: \n +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ func yaml_parser_scan_tag_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, handle, prefix *[]byte) bool { var handle_value, prefix_value []byte @@ -2849,7 +2847,7 @@ func yaml_parser_scan_line_comment(parser *yaml_parser_t, token_mark yaml_mark_t continue } if parser.buffer[parser.buffer_pos+peek] == '#' { - seen := parser.mark.index + peek + seen := parser.mark.index+peek for { if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false @@ -2878,7 +2876,7 @@ func yaml_parser_scan_line_comment(parser *yaml_parser_t, token_mark yaml_mark_t parser.comments = append(parser.comments, yaml_comment_t{ token_mark: token_mark, start_mark: start_mark, - line: text, + line: text, }) } return true @@ -2912,7 +2910,7 @@ func yaml_parser_scan_comments(parser *yaml_parser_t, scan_mark yaml_mark_t) boo // the foot is the line below it. var foot_line = -1 if scan_mark.line > 0 { - foot_line = parser.mark.line - parser.newlines + 1 + foot_line = parser.mark.line-parser.newlines+1 if parser.newlines == 0 && parser.mark.column > 1 { foot_line++ } @@ -2998,7 +2996,7 @@ func yaml_parser_scan_comments(parser *yaml_parser_t, scan_mark yaml_mark_t) boo recent_empty = false // Consume until after the consumed comment line. - seen := parser.mark.index + peek + seen := parser.mark.index+peek for { if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false diff --git a/vendor/gopkg.in/yaml.v3/writerc.go b/vendor/gopkg.in/yaml.v3/writerc.go index 266d0b09..b8a116bf 100644 --- a/vendor/gopkg.in/yaml.v3/writerc.go +++ b/vendor/gopkg.in/yaml.v3/writerc.go @@ -1,17 +1,17 @@ -// +// // Copyright (c) 2011-2019 Canonical Ltd // Copyright (c) 2006-2010 Kirill Simonov -// +// // 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 diff --git a/vendor/gopkg.in/yaml.v3/yaml.go b/vendor/gopkg.in/yaml.v3/yaml.go index f0bedf3d..8cec6da4 100644 --- a/vendor/gopkg.in/yaml.v3/yaml.go +++ b/vendor/gopkg.in/yaml.v3/yaml.go @@ -17,7 +17,8 @@ // // Source code and other details for the project are available at GitHub: // -// https://github.com/go-yaml/yaml +// https://github.com/go-yaml/yaml +// package yaml import ( @@ -74,15 +75,16 @@ type Marshaler interface { // // For example: // -// type T struct { -// F int `yaml:"a,omitempty"` -// B int -// } -// var t T -// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) +// type T struct { +// F int `yaml:"a,omitempty"` +// B int +// } +// var t T +// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) // // See the documentation of Marshal for the format of tags and a list of // supported tag options. +// func Unmarshal(in []byte, out interface{}) (err error) { return unmarshal(in, out, false) } @@ -183,35 +185,36 @@ func unmarshal(in []byte, out interface{}, strict bool) (err error) { // // The field tag format accepted is: // -// `(...) yaml:"[][,[,]]" (...)` +// `(...) yaml:"[][,[,]]" (...)` // // The following flags are currently supported: // -// omitempty Only include the field if it's not set to the zero -// value for the type or to empty slices or maps. -// Zero valued structs will be omitted if all their public -// fields are zero, unless they implement an IsZero -// method (see the IsZeroer interface type), in which -// case the field will be excluded if IsZero returns true. +// omitempty Only include the field if it's not set to the zero +// value for the type or to empty slices or maps. +// Zero valued structs will be omitted if all their public +// fields are zero, unless they implement an IsZero +// method (see the IsZeroer interface type), in which +// case the field will be excluded if IsZero returns true. // -// flow Marshal using a flow style (useful for structs, -// sequences and maps). +// flow Marshal using a flow style (useful for structs, +// sequences and maps). // -// inline Inline the field, which must be a struct or a map, -// causing all of its fields or keys to be processed as if -// they were part of the outer struct. For maps, keys must -// not conflict with the yaml keys of other struct fields. +// inline Inline the field, which must be a struct or a map, +// causing all of its fields or keys to be processed as if +// they were part of the outer struct. For maps, keys must +// not conflict with the yaml keys of other struct fields. // // In addition, if the key is "-", the field is ignored. // // For example: // -// type T struct { -// F int `yaml:"a,omitempty"` -// B int -// } -// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" -// yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n" +// type T struct { +// F int `yaml:"a,omitempty"` +// B int +// } +// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" +// yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n" +// func Marshal(in interface{}) (out []byte, err error) { defer handleErr(&err) e := newEncoder() @@ -355,21 +358,22 @@ const ( // // For example: // -// var person struct { -// Name string -// Address yaml.Node -// } -// err := yaml.Unmarshal(data, &person) -// +// var person struct { +// Name string +// Address yaml.Node +// } +// err := yaml.Unmarshal(data, &person) +// // Or by itself: // -// var person Node -// err := yaml.Unmarshal(data, &person) +// var person Node +// err := yaml.Unmarshal(data, &person) +// type Node struct { // Kind defines whether the node is a document, a mapping, a sequence, // a scalar value, or an alias to another node. The specific data type of // scalar nodes may be obtained via the ShortTag and LongTag methods. - Kind Kind + Kind Kind // Style allows customizing the apperance of the node in the tree. Style Style @@ -417,6 +421,7 @@ func (n *Node) IsZero() bool { n.HeadComment == "" && n.LineComment == "" && n.FootComment == "" && n.Line == 0 && n.Column == 0 } + // LongTag returns the long form of the tag that indicates the data type for // the node. If the Tag field isn't explicitly defined, one will be computed // based on the node properties. diff --git a/vendor/gopkg.in/yaml.v3/yamlh.go b/vendor/gopkg.in/yaml.v3/yamlh.go index ddcd5513..7c6d0077 100644 --- a/vendor/gopkg.in/yaml.v3/yamlh.go +++ b/vendor/gopkg.in/yaml.v3/yamlh.go @@ -438,9 +438,7 @@ type yaml_document_t struct { // The number of written bytes should be set to the size_read variable. // // [in,out] data A pointer to an application data specified by -// -// yaml_parser_set_input(). -// +// yaml_parser_set_input(). // [out] buffer The buffer to write the data from the source. // [in] size The size of the buffer. // [out] size_read The actual number of bytes read from the source. @@ -641,6 +639,7 @@ type yaml_parser_t struct { } type yaml_comment_t struct { + scan_mark yaml_mark_t // Position where scanning for comments started token_mark yaml_mark_t // Position after which tokens will be associated with this comment start_mark yaml_mark_t // Position of '#' comment mark @@ -660,14 +659,13 @@ type yaml_comment_t struct { // @a buffer to the output. // // @param[in,out] data A pointer to an application data specified by -// -// yaml_emitter_set_output(). -// +// yaml_emitter_set_output(). // @param[in] buffer The buffer with bytes to be written. // @param[in] size The size of the buffer. // // @returns On success, the handler should return @c 1. If the handler failed, // the returned value should be @c 0. +// type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error type yaml_emitter_state_t int diff --git a/vendor/gopkg.in/yaml.v3/yamlprivateh.go b/vendor/gopkg.in/yaml.v3/yamlprivateh.go index dea1ba96..e88f9c54 100644 --- a/vendor/gopkg.in/yaml.v3/yamlprivateh.go +++ b/vendor/gopkg.in/yaml.v3/yamlprivateh.go @@ -1,17 +1,17 @@ -// +// // Copyright (c) 2011-2019 Canonical Ltd // Copyright (c) 2006-2010 Kirill Simonov -// +// // 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 @@ -137,8 +137,8 @@ func is_crlf(b []byte, i int) bool { func is_breakz(b []byte, i int) bool { //return is_break(b, i) || is_z(b, i) return ( - // is_break: - b[i] == '\r' || // CR (#xD) + // is_break: + b[i] == '\r' || // CR (#xD) b[i] == '\n' || // LF (#xA) b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) @@ -151,8 +151,8 @@ func is_breakz(b []byte, i int) bool { func is_spacez(b []byte, i int) bool { //return is_space(b, i) || is_breakz(b, i) return ( - // is_space: - b[i] == ' ' || + // is_space: + b[i] == ' ' || // is_breakz: b[i] == '\r' || // CR (#xD) b[i] == '\n' || // LF (#xA) @@ -166,8 +166,8 @@ func is_spacez(b []byte, i int) bool { func is_blankz(b []byte, i int) bool { //return is_blank(b, i) || is_breakz(b, i) return ( - // is_blank: - b[i] == ' ' || b[i] == '\t' || + // is_blank: + b[i] == ' ' || b[i] == '\t' || // is_breakz: b[i] == '\r' || // CR (#xD) b[i] == '\n' || // LF (#xA) diff --git a/vendor/gotest.tools/v3/internal/difflib/difflib.go b/vendor/gotest.tools/v3/internal/difflib/difflib.go index b88560de..9bf506b6 100644 --- a/vendor/gotest.tools/v3/internal/difflib/difflib.go +++ b/vendor/gotest.tools/v3/internal/difflib/difflib.go @@ -1,5 +1,4 @@ -/* -Package difflib is a partial port of Python difflib module. +/*Package difflib is a partial port of Python difflib module. Original source: https://github.com/pmezard/go-difflib @@ -171,15 +170,12 @@ func (m *SequenceMatcher) isBJunk(s string) bool { // If IsJunk is not defined: // // Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where -// -// alo <= i <= i+k <= ahi -// blo <= j <= j+k <= bhi -// +// alo <= i <= i+k <= ahi +// blo <= j <= j+k <= bhi // and for all (i',j',k') meeting those conditions, -// -// k >= k' -// i <= i' -// and if i == i', j <= j' +// k >= k' +// i <= i' +// and if i == i', j <= j' // // In other words, of all maximal matching blocks, return one that // starts earliest in a, and of all those maximal matching blocks that diff --git a/vendor/modules.txt b/vendor/modules.txt index a75b266b..fc4f7d9b 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -107,9 +107,6 @@ github.com/containers/image/transports github.com/containers/image/types # github.com/containers/storage v1.38.2 ## explicit; go 1.14 -# github.com/cpuguy83/go-md2man/v2 v2.0.4 -## explicit; go 1.11 -github.com/cpuguy83/go-md2man/v2/md2man # github.com/cyphar/filepath-securejoin v0.2.5 ## explicit; go 1.13 github.com/cyphar/filepath-securejoin @@ -469,9 +466,6 @@ github.com/prometheus/procfs/internal/util # github.com/rivo/uniseg v0.4.7 ## explicit; go 1.18 github.com/rivo/uniseg -# github.com/russross/blackfriday/v2 v2.1.0 -## explicit -github.com/russross/blackfriday/v2 # github.com/schollz/progressbar/v3 v3.14.4 ## explicit; go 1.13 github.com/schollz/progressbar/v3 @@ -509,9 +503,9 @@ github.com/theupdateframework/notary/tuf/data github.com/theupdateframework/notary/tuf/signed github.com/theupdateframework/notary/tuf/utils github.com/theupdateframework/notary/tuf/validation -# github.com/urfave/cli v1.22.15 -## explicit; go 1.11 -github.com/urfave/cli +# github.com/urfave/cli/v3 v3.0.0-alpha9 => github.com/urfave/cli/v3 v3.0.0-alpha9.1.0.20241019193437-5053ec708a44 +## explicit; go 1.18 +github.com/urfave/cli/v3 # github.com/xanzy/ssh-agent v0.3.3 ## explicit; go 1.16 github.com/xanzy/ssh-agent @@ -782,3 +776,4 @@ gotest.tools/v3/internal/cleanup gotest.tools/v3/internal/difflib gotest.tools/v3/internal/format gotest.tools/v3/internal/source +# github.com/urfave/cli/v3 => github.com/urfave/cli/v3 v3.0.0-alpha9.1.0.20241019193437-5053ec708a44