[
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n- package-ecosystem: gomod\n  directory: /\n  schedule:\n    interval: weekly\n  open-pull-requests-limit: 99\n- package-ecosystem: github-actions\n  directory: /\n  schedule:\n    interval: weekly\n  open-pull-requests-limit: 99\n"
  },
  {
    "path": ".github/labeler.yml",
    "content": "# changes to documentation generation\n\"area/docs-generation\": \n- changed-files:\n  - any-glob-to-any-file: 'doc/**'\n\n# changes to the core cobra command\n\"area/cobra-command\":\n- changed-files:\n  - any-glob-to-any-file: ['./cobra.go', './cobra_test.go', './*command*.go']\n\n# changes made to command flags/args\n\"area/flags\":\n- changed-files:\n  - any-glob-to-any-file: './args*.go'\n\n# changes to Github workflows\n\"area/github\":\n- changed-files:\n  - any-glob-to-any-file: '.github/**'\n\n# changes to shell completions\n\"area/shell-completion\":\n- changed-files:\n  - any-glob-to-any-file: './*completions*'\n"
  },
  {
    "path": ".github/workflows/labeler.yml",
    "content": "name: \"Pull Request Labeler\"\non:\n- pull_request_target\n\npermissions:\n  contents: read\n\njobs:\n  triage:\n    permissions:\n      contents: read  # for actions/labeler to determine modified files\n      pull-requests: write  # for actions/labeler to add labels to PRs\n    runs-on: ubuntu-latest\n    steps:\n    - uses: actions/labeler@v5\n      with:\n        repo-token: \"${{ github.token }}\"\n\n"
  },
  {
    "path": ".github/workflows/test.yml",
    "content": "name: Test\n\non:\n  push:\n  pull_request:\n  workflow_dispatch:\n\nenv:\n  GO111MODULE: on\n\npermissions:\n  contents: read\n\njobs:\n\n\n  lic-headers:\n    runs-on: ubuntu-latest\n    steps:\n\n      - uses: actions/checkout@v4\n\n      - run: >-\n          docker run\n          -v $(pwd):/wrk -w /wrk\n          ghcr.io/google/addlicense\n          -c 'The Cobra Authors'\n          -y '2013-2023'\n          -l apache\n          -ignore '.github/**'\n          -check\n          .\n\n\n  golangci-lint:\n    permissions:\n      contents: read  # for actions/checkout to fetch code\n      pull-requests: read  # for golangci/golangci-lint-action to fetch pull requests\n    runs-on: ubuntu-latest\n    steps:\n\n      - uses: actions/checkout@v4\n\n      - uses: actions/setup-go@v6\n        with:\n          go-version: '^1.22'\n          check-latest: true\n          cache: true\n\n      - uses: golangci/golangci-lint-action@v8.0.0\n        with:\n          version: latest\n          args: --verbose\n\n\n  test-unix:\n    strategy:\n      fail-fast: false\n      matrix:\n        platform:\n        - ubuntu\n        - macOS\n        go:\n        - 17\n        - 18\n        - 19\n        - 20\n        - 21\n        - 22\n        - 23\n        - 24\n    name: '${{ matrix.platform }} | 1.${{ matrix.go }}.x'\n    runs-on: ${{ matrix.platform }}-latest\n    steps:\n\n    - uses: actions/checkout@v4\n\n    - uses: actions/setup-go@v6\n      with:\n        go-version: 1.${{ matrix.go }}.x\n        cache: true\n\n    - run: |\n        export GOBIN=$HOME/go/bin\n        go install github.com/kyoh86/richgo@latest\n        go install github.com/mitchellh/gox@latest\n\n    - run: RICHGO_FORCE_COLOR=1 PATH=$HOME/go/bin/:$PATH make richtest\n\n\n  test-win:\n    name: MINGW64\n    defaults:\n      run:\n        shell: msys2 {0}\n    runs-on: windows-latest\n    steps:\n\n    - shell: bash\n      run: git config --global core.autocrlf input\n\n    - uses: msys2/setup-msys2@v2\n      with:\n        msystem: MINGW64\n        update: true\n        install: >\n          git\n          make\n          unzip\n          mingw-w64-x86_64-go\n\n    - uses: actions/checkout@v4\n\n    - uses: actions/cache@v4\n      with:\n        path: ~/go/pkg/mod\n        key: ${{ runner.os }}-${{ matrix.go }}-${{ hashFiles('**/go.sum') }}\n        restore-keys: ${{ runner.os }}-${{ matrix.go }}-\n\n    - run: |\n        export GOBIN=$HOME/go/bin\n        go install github.com/kyoh86/richgo@latest\n        go install github.com/mitchellh/gox@latest\n\n    - run: RICHGO_FORCE_COLOR=1 PATH=$HOME/go/bin:$PATH make richtest\n"
  },
  {
    "path": ".gitignore",
    "content": "# Compiled Object files, Static and Dynamic libs (Shared Objects)\n*.o\n*.a\n*.so\n\n# Folders\n_obj\n_test\n\n# Architecture specific extensions/prefixes\n*.[568vq]\n[568vq].out\n\n*.cgo1.go\n*.cgo2.c\n_cgo_defun.c\n_cgo_gotypes.go\n_cgo_export.*\n\n_testmain.go\n\n# Vim files https://github.com/github/gitignore/blob/master/Global/Vim.gitignore\n# swap\n[._]*.s[a-w][a-z]\n[._]s[a-w][a-z]\n# session\nSession.vim\n# temporary\n.netrwhist\n*~\n# auto-generated tag files\ntags\n\n*.exe\ncobra.test\nbin\n\n.idea/\n*.iml\n"
  },
  {
    "path": ".golangci.yml",
    "content": "# Copyright 2013-2023 The Cobra Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nversion: \"2\"\n\nrun:\n  timeout: 5m\n\nformatters:\n  enable:\n    - gofmt\n    - goimports\n\nlinters:\n  default: none\n  enable:\n    #- bodyclose\n    #- depguard\n    #- dogsled\n    #- dupl\n    - errcheck\n    #- exhaustive\n    #- funlen\n    #- gochecknoinits\n    - goconst\n    - gocritic\n    #- gocyclo\n    #- goprintffuncname\n    - gosec\n    - govet\n    - ineffassign\n    #- lll\n    - misspell\n    #- mnd\n    #- nakedret\n    #- noctx\n    - nolintlint\n    #- rowserrcheck\n    - staticcheck\n    - unconvert\n    #- unparam\n    - unused\n    #- whitespace\n  exclusions:\n    presets:\n      - common-false-positives\n      - legacy\n      - std-error-handling\n  settings:\n    govet:\n      # Disable buildtag check to allow dual build tag syntax (both //go:build and // +build).\n      # This is necessary for Go 1.15 compatibility since //go:build was introduced in Go 1.17.\n      # This can be removed once Cobra requires Go 1.17 or higher.\n      disable:\n        - buildtag\n"
  },
  {
    "path": ".mailmap",
    "content": "Steve Francia <steve.francia@gmail.com>\nBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>\nFabiano Franz <ffranz@redhat.com>                   <contact@fabianofranz.com>\n"
  },
  {
    "path": "CONDUCT.md",
    "content": "## Cobra User Contract\n\n### Versioning\nCobra will follow a steady release cadence. Non breaking changes will be released as minor versions quarterly. Patch bug releases are at the discretion of the maintainers. Users can expect security patch fixes to be released within relatively short order of a CVE becoming known. For more information on security patch fixes see the CVE section below. Releases will follow [Semantic Versioning](https://semver.org/). Users tracking the Master branch should expect unpredictable breaking changes as the project continues to move forward. For stability, it is highly recommended to use a release.\n\n### Backward Compatibility\nWe will maintain two major releases in a moving window. The N-1 release will only receive bug fixes and security updates and will be dropped once N+1 is released.\n\n### Deprecation\nDeprecation of Go versions or dependent packages will only occur in major releases. To reduce the change of this taking users by surprise, any large deprecation will be preceded by an announcement in the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) and an Issue on Github.\n\n### CVE\nMaintainers will make every effort to release security patches in the case of a medium to high severity CVE directly impacting the library. The speed in which these patches reach a release is up to the discretion of the maintainers. A low severity CVE may be a lower priority than a high severity one.\n\n### Communication\nCobra maintainers will use GitHub issues and the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) as the primary means of communication with the community. This is to foster open communication with all users and contributors.\n\n### Breaking Changes\nBreaking changes are generally allowed in the master branch, as this is the branch used to develop the next release of Cobra.\n\nThere may be times, however, when master is closed for breaking changes. This is likely to happen as we near the release of a new version.\n\nBreaking changes are not allowed in release branches, as these represent minor versions that have already been released. These version have consumers who expect the APIs, behaviors, etc, to remain stable during the lifetime of the patch stream for the minor release.\n\nExamples of breaking changes include:\n- Removing or renaming exported constant, variable, type, or function.\n- Updating the version of critical libraries such as `spf13/pflag`, `spf13/viper` etc...\n  - Some version updates may be acceptable for picking up bug fixes, but maintainers must exercise caution when reviewing.\n\nThere may, at times, need to be exceptions where breaking changes are allowed in release branches. These are at the discretion of the project's maintainers, and must be carefully considered before merging.\n\n### CI Testing\nMaintainers will ensure the Cobra test suite utilizes the current supported versions of Golang.\n\n### Disclaimer\nChanges to this document and the contents therein are at the discretion of the maintainers.\nNone of the contents of this document are legally binding in any way to the maintainers or the users.\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to Cobra\n\nThank you so much for contributing to Cobra. We appreciate your time and help.\nHere are some guidelines to help you get started.\n\n## Code of Conduct\n\nBe kind and respectful to the members of the community. Take time to educate\nothers who are seeking help. Harassment of any kind will not be tolerated.\n\n## Questions\n\nIf you have questions regarding Cobra, feel free to ask it in the community\n[#cobra Slack channel][cobra-slack]\n\n## Filing a bug or feature\n\n1. Before filing an issue, please check the existing issues to see if a\n   similar one was already opened. If there is one already opened, feel free\n   to comment on it.\n1. If you believe you've found a bug, please provide detailed steps of\n   reproduction, the version of Cobra and anything else you believe will be\n   useful to help troubleshoot it (e.g. OS environment, environment variables,\n   etc...). Also state the current behavior vs. the expected behavior.\n1. If you'd like to see a feature or an enhancement please open an issue with\n   a clear title and description of what the feature is and why it would be\n   beneficial to the project and its users.\n\n## Submitting changes\n\n1. CLA: Upon submitting a Pull Request (PR), contributors will be prompted to\n   sign a CLA. Please sign the CLA :slightly_smiling_face:\n1. Tests: If you are submitting code, please ensure you have adequate tests\n   for the feature. Tests can be run via `go test ./...` or `make test`.\n1. Since this is golang project, ensure the new code is properly formatted to\n   ensure code consistency. Run `make all`.\n\n### Quick steps to contribute\n\n1. Fork the project.\n1. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`)\n1. Create your feature branch (`git checkout -b my-new-feature`)\n1. Make changes and run tests (`make test`)\n1. Add them to staging (`git add .`)\n1. Commit your changes (`git commit -m 'Add some feature'`)\n1. Push to the branch (`git push origin my-new-feature`)\n1. Create new pull request\n\n<!-- Links -->\n[cobra-slack]: https://gophers.slack.com/archives/CD3LP1199\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "                                Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n"
  },
  {
    "path": "MAINTAINERS",
    "content": "maintainers:\n- spf13\n- johnSchnake\n- jpmcb\n- marckhouzam\ninactive:\n- anthonyfok\n- bep\n- bogem\n- broady\n- eparis\n- jharshman\n- wfernandes\n"
  },
  {
    "path": "Makefile",
    "content": "BIN=\"./bin\"\nSRC=$(shell find . -name \"*.go\")\n\nifeq (, $(shell which golangci-lint))\n$(warning \"could not find golangci-lint in $(PATH), run: curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh\")\nendif\n\n.PHONY: fmt lint test install_deps clean\n\ndefault: all\n\nall: fmt test\n\nfmt:\n\t$(info ******************** checking formatting ********************)\n\t@test -z $(shell gofmt -l $(SRC)) || (gofmt -d $(SRC); exit 1)\n\nlint:\n\t$(info ******************** running lint tools ********************)\n\tgolangci-lint run -v\n\ntest: install_deps\n\t$(info ******************** running tests ********************)\n\tgo test -v ./...\n\nrichtest: install_deps\n\t$(info ******************** running tests with kyoh86/richgo ********************)\n\trichgo test -v ./...\n\ninstall_deps:\n\t$(info ******************** downloading dependencies ********************)\n\tgo get -v ./...\n\nclean:\n\trm -rf $(BIN)\n"
  },
  {
    "path": "README.md",
    "content": "<div align=\"center\">\n<a href=\"https://cobra.dev\">\n<img width=\"512\" height=\"535\" alt=\"cobra-logo\" src=\"https://github.com/user-attachments/assets/c8bf9aad-b5ae-41d3-8899-d83baec10af8\" />\n</a>\n</div>\n\nCobra is a library for creating powerful modern CLI applications.\n\n<a href=\"https://cobra.dev\">Visit Cobra.dev for extensive documentation</a> \n\n\nCobra is used in many Go projects such as [Kubernetes](https://kubernetes.io/),\n[Hugo](https://gohugo.io), and [GitHub CLI](https://github.com/cli/cli) to\nname a few. [This list](site/content/projects_using_cobra.md) contains a more extensive list of projects using Cobra.\n\n[![](https://img.shields.io/github/actions/workflow/status/spf13/cobra/test.yml?branch=main&longCache=true&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest)\n[![Go Reference](https://pkg.go.dev/badge/github.com/spf13/cobra.svg)](https://pkg.go.dev/github.com/spf13/cobra)\n[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra)\n[![Slack](https://img.shields.io/badge/Slack-cobra-brightgreen)](https://gophers.slack.com/archives/CD3LP1199)\n<hr>\n<div align=\"center\" markdown=\"1\">\n   <sup>Supported by:</sup>\n   <br>\n   <br>\n   <a href=\"https://www.warp.dev/cobra\">\n      <img alt=\"Warp sponsorship\" width=\"400\" src=\"https://github.com/user-attachments/assets/ab8dd143-b0fd-4904-bdc5-dd7ecac94eae\">\n   </a>\n\n### [Warp, the AI terminal for devs](https://www.warp.dev/cobra)\n[Try Cobra in Warp today](https://www.warp.dev/cobra)<br>\n\n</div>\n<hr>\n\n# Overview\n\nCobra is a library providing a simple interface to create powerful modern CLI\ninterfaces similar to git & go tools.\n\nCobra provides:\n* Easy subcommand-based CLIs: `app server`, `app fetch`, etc.\n* Fully POSIX-compliant flags (including short & long versions)\n* Nested subcommands\n* Global, local and cascading flags\n* Intelligent suggestions (`app srver`... did you mean `app server`?)\n* Automatic help generation for commands and flags\n* Grouping help for subcommands\n* Automatic help flag recognition of `-h`, `--help`, etc.\n* Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell)\n* Automatically generated man pages for your application\n* Command aliases so you can change things without breaking them\n* The flexibility to define your own help, usage, etc.\n* Optional seamless integration with [viper](https://github.com/spf13/viper) for 12-factor apps\n\n# Concepts\n\nCobra is built on a structure of commands, arguments & flags.\n\n**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions.\n\nThe best applications read like sentences when used, and as a result, users\nintuitively know how to interact with them.\n\nThe pattern to follow is\n`APPNAME VERB NOUN --ADJECTIVE`\n    or\n`APPNAME COMMAND ARG --FLAG`.\n\nA few good real world examples may better illustrate this point.\n\nIn the following example, 'server' is a command, and 'port' is a flag:\n\n    hugo server --port=1313\n\nIn this command we are telling Git to clone the url bare.\n\n    git clone URL --bare\n\n## Commands\n\nCommand is the central point of the application. Each interaction that\nthe application supports will be contained in a Command. A command can\nhave children commands and optionally run an action.\n\nIn the example above, 'server' is the command.\n\n[More about cobra.Command](https://pkg.go.dev/github.com/spf13/cobra#Command)\n\n## Flags\n\nA flag is a way to modify the behavior of a command. Cobra supports\nfully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/).\nA Cobra command can define flags that persist through to children commands\nand flags that are only available to that command.\n\nIn the example above, 'port' is the flag.\n\nFlag functionality is provided by the [pflag\nlibrary](https://github.com/spf13/pflag), a fork of the flag standard library\nwhich maintains the same interface while adding POSIX compliance.\n\n# Installing\nUsing Cobra is easy. First, use `go get` to install the latest version\nof the library.\n\n```\ngo get -u github.com/spf13/cobra@latest\n```\n\nNext, include Cobra in your application:\n\n```go\nimport \"github.com/spf13/cobra\"\n```\n\n# Usage\n`cobra-cli` is a command line program to generate cobra applications and command files.\nIt will bootstrap your application scaffolding to rapidly\ndevelop a Cobra-based application. It is the easiest way to incorporate Cobra into your application.\n\nIt can be installed by running:\n\n```\ngo install github.com/spf13/cobra-cli@latest\n```\n\nFor complete details on using the Cobra-CLI generator, please read [The Cobra Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md)\n\nFor complete details on using the Cobra library, please read [The Cobra User Guide](site/content/user_guide.md).\n\n# License\n\nCobra is released under the Apache 2.0 license. See [LICENSE.txt](LICENSE.txt)\n"
  },
  {
    "path": "SECURITY.md",
    "content": "# Security Policy\n\n## Reporting a Vulnerability\n\nThe `cobra` maintainers take security issues seriously and\nwe appreciate your efforts to _**responsibly**_ disclose your findings.\nWe will make every effort to swiftly respond and address concerns.\n\nTo report a security vulnerability:\n\n1. **DO NOT** create a public GitHub issue for the vulnerability!\n2. **DO NOT** create a public GitHub Pull Request with a fix for the vulnerability!\n3. Send an email to `cobra-security@googlegroups.com`.\n4. Include the following details in your report:\n   - Description of the vulnerability\n   - Steps to reproduce\n   - Potential impact of the vulnerability (to your downstream project, to the Go ecosystem, etc.)\n   - Any potential mitigations you've already identified\n5. Allow up to 7 days for an initial response.\n   You should receive an acknowledgment of your report and an estimated timeline for a fix.\n6. (Optional) If you have a fix and would like to contribute your patch, please work\n   directly with the maintainers via `cobra-security@googlegroups.com` to\n   coordinate pushing the patch to GitHub, cutting a new release, and disclosing the change.\n\n## Response Process\n\nWhen a security vulnerability report is received, the `cobra` maintainers will:\n\n1. Confirm receipt of the vulnerability report within 7 days.\n2. Assess the report to determine if it constitutes a security vulnerability.\n3. If confirmed, assign the vulnerability a severity level and create a timeline for addressing it.\n4. Develop and test a fix.\n5. Patch the vulnerability and make a new GitHub release: the maintainers will coordinate disclosure with the reporter.\n6. Create a new GitHub Security Advisory to inform the broader Go ecosystem\n\n## Disclosure Policy\n\nThe `cobra` maintainers follow a coordinated disclosure process:\n\n1. Security vulnerabilities will be addressed as quickly as possible.\n2. A CVE (Common Vulnerabilities and Exposures) identifier will be requested for significant vulnerabilities\n   that are within `cobra` itself.\n3. Once a fix is ready, the maintainers will:\n   - Release a new version containing the fix.\n   - Update the security advisory with details about the vulnerability.\n   - Credit the reporter (unless they wish to remain anonymous).\n   - Credit the fixer (unless they wish to remain anonymous, this may be the same as the reporter).\n   - Announce the vulnerability through appropriate channels\n     (GitHub Security Advisory, mailing lists, GitHub Releases, etc.)\n\n## Supported Versions\n\nSecurity fixes will typically only be released for the most recent major release.\n\n## Upstream Security Issues\n\n`cobra` generally will not accept vulnerability reports that originate in upstream\ndependencies. I.e., if there is a problem in Go code that `cobra` depends on,\nit is best to engage that project's maintainers and owners.\n\nThis security policy primarily pertains only to `cobra` itself but if you believe you've\nidentified a problem that originates in an upstream dependency and is being widely\ndistributed by `cobra`, please follow the disclosure procedure above: the `cobra`\nmaintainers will work with you to determine the severity and ecosystem impact.\n\n## Security Updates and CVEs\n\nInformation about known security vulnerabilities and CVEs affecting `cobra` will\nbe published as GitHub Security Advisories at\nhttps://github.com/spf13/cobra/security/advisories.\n\nAll users are encouraged to watch the repository and upgrade promptly when\nsecurity releases are published.\n\n## `cobra` Security Best Practices for Users\n\nWhen using `cobra` in your CLIs, the `cobra` maintainers recommend the following:\n\n1. Always use the latest version of `cobra`.\n2. [Use Go modules](https://go.dev/blog/using-go-modules) for dependency management.\n3. Always use the latest possible version of Go.\n\n## Security Best Practices for Contributors\n\nWhen contributing to `cobra`:\n\n1. Be mindful of security implications when adding new features or modifying existing ones.\n2. Be aware of `cobra`'s extremely large reach: it is used in nearly every Go CLI\n   (like Kubernetes, Docker, Prometheus, etc. etc.)\n3. Write tests that explicitly cover edge cases and potential issues.\n4. If you discover a security issue while working on `cobra`, please report it\n   following the process above rather than opening a public pull request or issue that\n   addresses the vulnerability.\n5. Take personal sec-ops seriously and secure your GitHub account: use [two-factor authentication](https://docs.github.com/en/authentication/securing-your-account-with-two-factor-authentication-2fa),\n   [sign your commits with a GPG or SSH key](https://docs.github.com/en/authentication/managing-commit-signature-verification/about-commit-signature-verification),\n   etc.\n\n## Acknowledgments\n\nThe `cobra` maintainers would like to thank all security researchers and\ncommunity members who help keep cobra, its users, and the entire Go ecosystem secure through responsible disclosures!!\n\n---\n\n*This security policy is inspired by the [Open Web Application Security Project (OWASP)](https://owasp.org/) guidelines and security best practices.*\n"
  },
  {
    "path": "active_help.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nconst (\n\tactiveHelpMarker = \"_activeHelp_ \"\n\t// The below values should not be changed: programs will be using them explicitly\n\t// in their user documentation, and users will be using them explicitly.\n\tactiveHelpEnvVarSuffix  = \"ACTIVE_HELP\"\n\tactiveHelpGlobalEnvVar  = configEnvVarGlobalPrefix + \"_\" + activeHelpEnvVarSuffix\n\tactiveHelpGlobalDisable = \"0\"\n)\n\n// AppendActiveHelp adds the specified string to the specified array to be used as ActiveHelp.\n// Such strings will be processed by the completion script and will be shown as ActiveHelp\n// to the user.\n// The array parameter should be the array that will contain the completions.\n// This function can be called multiple times before and/or after completions are added to\n// the array.  Each time this function is called with the same array, the new\n// ActiveHelp line will be shown below the previous ones when completion is triggered.\nfunc AppendActiveHelp(compArray []Completion, activeHelpStr string) []Completion {\n\treturn append(compArray, fmt.Sprintf(\"%s%s\", activeHelpMarker, activeHelpStr))\n}\n\n// GetActiveHelpConfig returns the value of the ActiveHelp environment variable\n// <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the root command in upper\n// case, with all non-ASCII-alphanumeric characters replaced by `_`.\n// It will always return \"0\" if the global environment variable COBRA_ACTIVE_HELP\n// is set to \"0\".\nfunc GetActiveHelpConfig(cmd *Command) string {\n\tactiveHelpCfg := os.Getenv(activeHelpGlobalEnvVar)\n\tif activeHelpCfg != activeHelpGlobalDisable {\n\t\tactiveHelpCfg = os.Getenv(activeHelpEnvVar(cmd.Root().Name()))\n\t}\n\treturn activeHelpCfg\n}\n\n// activeHelpEnvVar returns the name of the program-specific ActiveHelp environment\n// variable.  It has the format <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the\n// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`.\nfunc activeHelpEnvVar(name string) string {\n\treturn configEnvVar(name, activeHelpEnvVarSuffix)\n}\n"
  },
  {
    "path": "active_help_test.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n)\n\nconst (\n\tactiveHelpMessage  = \"This is an activeHelp message\"\n\tactiveHelpMessage2 = \"This is the rest of the activeHelp message\"\n)\n\nfunc TestActiveHelpAlone(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\n\tactiveHelpFunc := func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\tcomps := AppendActiveHelp(nil, activeHelpMessage)\n\t\treturn comps, ShellCompDirectiveDefault\n\t}\n\n\t// Test that activeHelp can be added to a root command\n\trootCmd.ValidArgsFunction = activeHelpFunc\n\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\tfmt.Sprintf(\"%s%s\", activeHelpMarker, activeHelpMessage),\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\trootCmd.ValidArgsFunction = nil\n\n\t// Test that activeHelp can be added to a child command\n\tchildCmd := &Command{\n\t\tUse:   \"thechild\",\n\t\tShort: \"The child command\",\n\t\tRun:   emptyRun,\n\t}\n\trootCmd.AddCommand(childCmd)\n\n\tchildCmd.ValidArgsFunction = activeHelpFunc\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"thechild\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\tfmt.Sprintf(\"%s%s\", activeHelpMarker, activeHelpMessage),\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestActiveHelpWithComps(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\n\tchildCmd := &Command{\n\t\tUse:   \"thechild\",\n\t\tShort: \"The child command\",\n\t\tRun:   emptyRun,\n\t}\n\trootCmd.AddCommand(childCmd)\n\n\t// Test that activeHelp can be added following other completions\n\tchildCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\tcomps := []string{\"first\", \"second\"}\n\t\tcomps = AppendActiveHelp(comps, activeHelpMessage)\n\t\treturn comps, ShellCompDirectiveDefault\n\t}\n\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"thechild\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"first\",\n\t\t\"second\",\n\t\tfmt.Sprintf(\"%s%s\", activeHelpMarker, activeHelpMessage),\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that activeHelp can be added preceding other completions\n\tchildCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\tvar comps []string\n\t\tcomps = AppendActiveHelp(comps, activeHelpMessage)\n\t\tcomps = append(comps, []string{\"first\", \"second\"}...)\n\t\treturn comps, ShellCompDirectiveDefault\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"thechild\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\tfmt.Sprintf(\"%s%s\", activeHelpMarker, activeHelpMessage),\n\t\t\"first\",\n\t\t\"second\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that activeHelp can be added interleaved with other completions\n\tchildCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\tcomps := []string{\"first\"}\n\t\tcomps = AppendActiveHelp(comps, activeHelpMessage)\n\t\tcomps = append(comps, \"second\")\n\t\treturn comps, ShellCompDirectiveDefault\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"thechild\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"first\",\n\t\tfmt.Sprintf(\"%s%s\", activeHelpMarker, activeHelpMessage),\n\t\t\"second\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestMultiActiveHelp(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\n\tchildCmd := &Command{\n\t\tUse:   \"thechild\",\n\t\tShort: \"The child command\",\n\t\tRun:   emptyRun,\n\t}\n\trootCmd.AddCommand(childCmd)\n\n\t// Test that multiple activeHelp message can be added\n\tchildCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\tcomps := AppendActiveHelp(nil, activeHelpMessage)\n\t\tcomps = AppendActiveHelp(comps, activeHelpMessage2)\n\t\treturn comps, ShellCompDirectiveNoFileComp\n\t}\n\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"thechild\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\tfmt.Sprintf(\"%s%s\", activeHelpMarker, activeHelpMessage),\n\t\tfmt.Sprintf(\"%s%s\", activeHelpMarker, activeHelpMessage2),\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that multiple activeHelp messages can be used along with completions\n\tchildCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\tcomps := []string{\"first\"}\n\t\tcomps = AppendActiveHelp(comps, activeHelpMessage)\n\t\tcomps = append(comps, \"second\")\n\t\tcomps = AppendActiveHelp(comps, activeHelpMessage2)\n\t\treturn comps, ShellCompDirectiveNoFileComp\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"thechild\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"first\",\n\t\tfmt.Sprintf(\"%s%s\", activeHelpMarker, activeHelpMessage),\n\t\t\"second\",\n\t\tfmt.Sprintf(\"%s%s\", activeHelpMarker, activeHelpMessage2),\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestActiveHelpForFlag(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\tflagname := \"flag\"\n\trootCmd.Flags().String(flagname, \"\", \"A flag\")\n\n\t// Test that multiple activeHelp message can be added\n\t_ = rootCmd.RegisterFlagCompletionFunc(flagname, func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\tcomps := []string{\"first\"}\n\t\tcomps = AppendActiveHelp(comps, activeHelpMessage)\n\t\tcomps = append(comps, \"second\")\n\t\tcomps = AppendActiveHelp(comps, activeHelpMessage2)\n\t\treturn comps, ShellCompDirectiveNoFileComp\n\t})\n\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--flag\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"first\",\n\t\tfmt.Sprintf(\"%s%s\", activeHelpMarker, activeHelpMessage),\n\t\t\"second\",\n\t\tfmt.Sprintf(\"%s%s\", activeHelpMarker, activeHelpMessage2),\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestConfigActiveHelp(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\n\tchildCmd := &Command{\n\t\tUse:   \"thechild\",\n\t\tShort: \"The child command\",\n\t\tRun:   emptyRun,\n\t}\n\trootCmd.AddCommand(childCmd)\n\n\tactiveHelpCfg := \"someconfig,anotherconfig\"\n\t// Set the variable that the user would be setting\n\tos.Setenv(activeHelpEnvVar(rootCmd.Name()), activeHelpCfg)\n\n\tchildCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\treceivedActiveHelpCfg := GetActiveHelpConfig(cmd)\n\t\tif receivedActiveHelpCfg != activeHelpCfg {\n\t\t\tt.Errorf(\"expected activeHelpConfig: %q, but got: %q\", activeHelpCfg, receivedActiveHelpCfg)\n\t\t}\n\t\treturn nil, ShellCompDirectiveDefault\n\t}\n\n\t_, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"thechild\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\t// Test active help config for a flag\n\tactiveHelpCfg = \"a config for a flag\"\n\t// Set the variable that the completions scripts will be setting\n\tos.Setenv(activeHelpEnvVar(rootCmd.Name()), activeHelpCfg)\n\n\tflagname := \"flag\"\n\tchildCmd.Flags().String(flagname, \"\", \"A flag\")\n\n\t// Test that multiple activeHelp message can be added\n\t_ = childCmd.RegisterFlagCompletionFunc(flagname, func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\treceivedActiveHelpCfg := GetActiveHelpConfig(cmd)\n\t\tif receivedActiveHelpCfg != activeHelpCfg {\n\t\t\tt.Errorf(\"expected activeHelpConfig: %q, but got: %q\", activeHelpCfg, receivedActiveHelpCfg)\n\t\t}\n\t\treturn nil, ShellCompDirectiveDefault\n\t})\n\n\t_, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"thechild\", \"--flag\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n}\n\nfunc TestDisableActiveHelp(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\n\tchildCmd := &Command{\n\t\tUse:   \"thechild\",\n\t\tShort: \"The child command\",\n\t\tRun:   emptyRun,\n\t}\n\trootCmd.AddCommand(childCmd)\n\n\t// Test the disabling of activeHelp using the specific program\n\t// environment variable that the completions scripts will be setting.\n\t// Make sure the disabling value is \"0\" by hard-coding it in the tests;\n\t// this is for backwards-compatibility as programs will be using this value.\n\tos.Setenv(activeHelpEnvVar(rootCmd.Name()), \"0\")\n\n\tchildCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\tcomps := []string{\"first\"}\n\t\tcomps = AppendActiveHelp(comps, activeHelpMessage)\n\t\treturn comps, ShellCompDirectiveDefault\n\t}\n\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"thechild\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\tos.Unsetenv(activeHelpEnvVar(rootCmd.Name()))\n\n\t// Make sure there is no ActiveHelp in the output\n\texpected := strings.Join([]string{\n\t\t\"first\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Now test the global disabling of ActiveHelp\n\tos.Setenv(activeHelpGlobalEnvVar, \"0\")\n\t// Set the specific variable, to make sure it is ignored when the global env\n\t// var is set properly\n\tos.Setenv(activeHelpEnvVar(rootCmd.Name()), \"1\")\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"thechild\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\t// Make sure there is no ActiveHelp in the output\n\texpected = strings.Join([]string{\n\t\t\"first\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Make sure that if the global env variable is set to anything else than\n\t// the disable value it is ignored\n\tos.Setenv(activeHelpGlobalEnvVar, \"on\")\n\t// Set the specific variable, to make sure it is used (while ignoring the global env var)\n\tactiveHelpCfg := \"1\"\n\tos.Setenv(activeHelpEnvVar(rootCmd.Name()), activeHelpCfg)\n\n\tchildCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\treceivedActiveHelpCfg := GetActiveHelpConfig(cmd)\n\t\tif receivedActiveHelpCfg != activeHelpCfg {\n\t\t\tt.Errorf(\"expected activeHelpConfig: %q, but got: %q\", activeHelpCfg, receivedActiveHelpCfg)\n\t\t}\n\t\treturn nil, ShellCompDirectiveDefault\n\t}\n\n\t_, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"thechild\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n}\n"
  },
  {
    "path": "args.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype PositionalArgs func(cmd *Command, args []string) error\n\n// legacyArgs validation has the following behaviour:\n// - root commands with no subcommands can take arbitrary arguments\n// - root commands with subcommands will do subcommand validity checking\n// - subcommands will always accept arbitrary arguments\nfunc legacyArgs(cmd *Command, args []string) error {\n\t// no subcommand, always take args\n\tif !cmd.HasSubCommands() {\n\t\treturn nil\n\t}\n\n\t// root command with subcommands, do subcommand checking.\n\tif !cmd.HasParent() && len(args) > 0 {\n\t\treturn fmt.Errorf(\"unknown command %q for %q%s\", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0]))\n\t}\n\treturn nil\n}\n\n// NoArgs returns an error if any args are included.\nfunc NoArgs(cmd *Command, args []string) error {\n\tif len(args) > 0 {\n\t\treturn fmt.Errorf(\"unknown command %q for %q\", args[0], cmd.CommandPath())\n\t}\n\treturn nil\n}\n\n// OnlyValidArgs returns an error if there are any positional args that are not in\n// the `ValidArgs` field of `Command`\nfunc OnlyValidArgs(cmd *Command, args []string) error {\n\tif len(cmd.ValidArgs) > 0 {\n\t\t// Remove any description that may be included in ValidArgs.\n\t\t// A description is following a tab character.\n\t\tvalidArgs := make([]string, 0, len(cmd.ValidArgs))\n\t\tfor _, v := range cmd.ValidArgs {\n\t\t\tvalidArgs = append(validArgs, strings.SplitN(v, \"\\t\", 2)[0])\n\t\t}\n\t\tfor _, v := range args {\n\t\t\tif !stringInSlice(v, validArgs) {\n\t\t\t\treturn fmt.Errorf(\"invalid argument %q for %q%s\", v, cmd.CommandPath(), cmd.findSuggestions(args[0]))\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n// ArbitraryArgs never returns an error.\nfunc ArbitraryArgs(cmd *Command, args []string) error {\n\treturn nil\n}\n\n// MinimumNArgs returns an error if there is not at least N args.\nfunc MinimumNArgs(n int) PositionalArgs {\n\treturn func(cmd *Command, args []string) error {\n\t\tif len(args) < n {\n\t\t\treturn fmt.Errorf(\"requires at least %d arg(s), only received %d\", n, len(args))\n\t\t}\n\t\treturn nil\n\t}\n}\n\n// MaximumNArgs returns an error if there are more than N args.\nfunc MaximumNArgs(n int) PositionalArgs {\n\treturn func(cmd *Command, args []string) error {\n\t\tif len(args) > n {\n\t\t\treturn fmt.Errorf(\"accepts at most %d arg(s), received %d\", n, len(args))\n\t\t}\n\t\treturn nil\n\t}\n}\n\n// ExactArgs returns an error if there are not exactly n args.\nfunc ExactArgs(n int) PositionalArgs {\n\treturn func(cmd *Command, args []string) error {\n\t\tif len(args) != n {\n\t\t\treturn fmt.Errorf(\"accepts %d arg(s), received %d\", n, len(args))\n\t\t}\n\t\treturn nil\n\t}\n}\n\n// RangeArgs returns an error if the number of args is not within the expected range.\nfunc RangeArgs(min int, max int) PositionalArgs {\n\treturn func(cmd *Command, args []string) error {\n\t\tif len(args) < min || len(args) > max {\n\t\t\treturn fmt.Errorf(\"accepts between %d and %d arg(s), received %d\", min, max, len(args))\n\t\t}\n\t\treturn nil\n\t}\n}\n\n// MatchAll allows combining several PositionalArgs to work in concert.\nfunc MatchAll(pargs ...PositionalArgs) PositionalArgs {\n\treturn func(cmd *Command, args []string) error {\n\t\tfor _, parg := range pargs {\n\t\t\tif err := parg(cmd, args); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n}\n\n// ExactValidArgs returns an error if there are not exactly N positional args OR\n// there are any positional args that are not in the `ValidArgs` field of `Command`\n//\n// Deprecated: use MatchAll(ExactArgs(n), OnlyValidArgs) instead\nfunc ExactValidArgs(n int) PositionalArgs {\n\treturn MatchAll(ExactArgs(n), OnlyValidArgs)\n}\n"
  },
  {
    "path": "args_test.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc getCommand(args PositionalArgs, withValid bool) *Command {\n\tc := &Command{\n\t\tUse:  \"c\",\n\t\tArgs: args,\n\t\tRun:  emptyRun,\n\t}\n\tif withValid {\n\t\tc.ValidArgs = []string{\"one\", \"two\", \"three\"}\n\t}\n\treturn c\n}\n\nfunc expectSuccess(output string, err error, t *testing.T) {\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t}\n}\n\nfunc validOnlyWithInvalidArgs(err error, t *testing.T) {\n\tif err == nil {\n\t\tt.Fatal(\"Expected an error\")\n\t}\n\tgot := err.Error()\n\texpected := `invalid argument \"a\" for \"c\"`\n\tif got != expected {\n\t\tt.Errorf(\"Expected: %q, got: %q\", expected, got)\n\t}\n}\n\nfunc noArgsWithArgs(err error, t *testing.T, arg string) {\n\tif err == nil {\n\t\tt.Fatal(\"Expected an error\")\n\t}\n\tgot := err.Error()\n\texpected := `unknown command \"` + arg + `\" for \"c\"`\n\tif got != expected {\n\t\tt.Errorf(\"Expected: %q, got: %q\", expected, got)\n\t}\n}\n\nfunc minimumNArgsWithLessArgs(err error, t *testing.T) {\n\tif err == nil {\n\t\tt.Fatal(\"Expected an error\")\n\t}\n\tgot := err.Error()\n\texpected := \"requires at least 2 arg(s), only received 1\"\n\tif got != expected {\n\t\tt.Fatalf(\"Expected %q, got %q\", expected, got)\n\t}\n}\n\nfunc maximumNArgsWithMoreArgs(err error, t *testing.T) {\n\tif err == nil {\n\t\tt.Fatal(\"Expected an error\")\n\t}\n\tgot := err.Error()\n\texpected := \"accepts at most 2 arg(s), received 3\"\n\tif got != expected {\n\t\tt.Fatalf(\"Expected %q, got %q\", expected, got)\n\t}\n}\n\nfunc exactArgsWithInvalidCount(err error, t *testing.T) {\n\tif err == nil {\n\t\tt.Fatal(\"Expected an error\")\n\t}\n\tgot := err.Error()\n\texpected := \"accepts 2 arg(s), received 3\"\n\tif got != expected {\n\t\tt.Fatalf(\"Expected %q, got %q\", expected, got)\n\t}\n}\n\nfunc rangeArgsWithInvalidCount(err error, t *testing.T) {\n\tif err == nil {\n\t\tt.Fatal(\"Expected an error\")\n\t}\n\tgot := err.Error()\n\texpected := \"accepts between 2 and 4 arg(s), received 1\"\n\tif got != expected {\n\t\tt.Fatalf(\"Expected %q, got %q\", expected, got)\n\t}\n}\n\n// NoArgs\n\nfunc TestNoArgs(t *testing.T) {\n\tc := getCommand(NoArgs, false)\n\toutput, err := executeCommand(c)\n\texpectSuccess(output, err, t)\n}\n\nfunc TestNoArgs_WithArgs(t *testing.T) {\n\tc := getCommand(NoArgs, false)\n\t_, err := executeCommand(c, \"one\")\n\tnoArgsWithArgs(err, t, \"one\")\n}\n\nfunc TestNoArgs_WithValid_WithArgs(t *testing.T) {\n\tc := getCommand(NoArgs, true)\n\t_, err := executeCommand(c, \"one\")\n\tnoArgsWithArgs(err, t, \"one\")\n}\n\nfunc TestNoArgs_WithValid_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(NoArgs, true)\n\t_, err := executeCommand(c, \"a\")\n\tnoArgsWithArgs(err, t, \"a\")\n}\n\nfunc TestNoArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(MatchAll(OnlyValidArgs, NoArgs), true)\n\t_, err := executeCommand(c, \"a\")\n\tvalidOnlyWithInvalidArgs(err, t)\n}\n\n// OnlyValidArgs\n\nfunc TestOnlyValidArgs(t *testing.T) {\n\tc := getCommand(OnlyValidArgs, true)\n\toutput, err := executeCommand(c, \"one\", \"two\")\n\texpectSuccess(output, err, t)\n}\n\nfunc TestOnlyValidArgs_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(OnlyValidArgs, true)\n\t_, err := executeCommand(c, \"a\")\n\tvalidOnlyWithInvalidArgs(err, t)\n}\n\n// ArbitraryArgs\n\nfunc TestArbitraryArgs(t *testing.T) {\n\tc := getCommand(ArbitraryArgs, false)\n\toutput, err := executeCommand(c, \"a\", \"b\")\n\texpectSuccess(output, err, t)\n}\n\nfunc TestArbitraryArgs_WithValid(t *testing.T) {\n\tc := getCommand(ArbitraryArgs, true)\n\toutput, err := executeCommand(c, \"one\", \"two\")\n\texpectSuccess(output, err, t)\n}\n\nfunc TestArbitraryArgs_WithValid_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(ArbitraryArgs, true)\n\toutput, err := executeCommand(c, \"a\")\n\texpectSuccess(output, err, t)\n}\n\nfunc TestArbitraryArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(MatchAll(OnlyValidArgs, ArbitraryArgs), true)\n\t_, err := executeCommand(c, \"a\")\n\tvalidOnlyWithInvalidArgs(err, t)\n}\n\n// MinimumNArgs\n\nfunc TestMinimumNArgs(t *testing.T) {\n\tc := getCommand(MinimumNArgs(2), false)\n\toutput, err := executeCommand(c, \"a\", \"b\", \"c\")\n\texpectSuccess(output, err, t)\n}\n\nfunc TestMinimumNArgs_WithValid(t *testing.T) {\n\tc := getCommand(MinimumNArgs(2), true)\n\toutput, err := executeCommand(c, \"one\", \"three\")\n\texpectSuccess(output, err, t)\n}\n\nfunc TestMinimumNArgs_WithValid__WithInvalidArgs(t *testing.T) {\n\tc := getCommand(MinimumNArgs(2), true)\n\toutput, err := executeCommand(c, \"a\", \"b\")\n\texpectSuccess(output, err, t)\n}\n\nfunc TestMinimumNArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(MatchAll(OnlyValidArgs, MinimumNArgs(2)), true)\n\t_, err := executeCommand(c, \"a\", \"b\")\n\tvalidOnlyWithInvalidArgs(err, t)\n}\n\nfunc TestMinimumNArgs_WithLessArgs(t *testing.T) {\n\tc := getCommand(MinimumNArgs(2), false)\n\t_, err := executeCommand(c, \"a\")\n\tminimumNArgsWithLessArgs(err, t)\n}\n\nfunc TestMinimumNArgs_WithLessArgs_WithValid(t *testing.T) {\n\tc := getCommand(MinimumNArgs(2), true)\n\t_, err := executeCommand(c, \"one\")\n\tminimumNArgsWithLessArgs(err, t)\n}\n\nfunc TestMinimumNArgs_WithLessArgs_WithValid_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(MinimumNArgs(2), true)\n\t_, err := executeCommand(c, \"a\")\n\tminimumNArgsWithLessArgs(err, t)\n}\n\nfunc TestMinimumNArgs_WithLessArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(MatchAll(OnlyValidArgs, MinimumNArgs(2)), true)\n\t_, err := executeCommand(c, \"a\")\n\tvalidOnlyWithInvalidArgs(err, t)\n}\n\n// MaximumNArgs\n\nfunc TestMaximumNArgs(t *testing.T) {\n\tc := getCommand(MaximumNArgs(3), false)\n\toutput, err := executeCommand(c, \"a\", \"b\")\n\texpectSuccess(output, err, t)\n}\n\nfunc TestMaximumNArgs_WithValid(t *testing.T) {\n\tc := getCommand(MaximumNArgs(2), true)\n\toutput, err := executeCommand(c, \"one\", \"three\")\n\texpectSuccess(output, err, t)\n}\n\nfunc TestMaximumNArgs_WithValid_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(MaximumNArgs(2), true)\n\toutput, err := executeCommand(c, \"a\", \"b\")\n\texpectSuccess(output, err, t)\n}\n\nfunc TestMaximumNArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(MatchAll(OnlyValidArgs, MaximumNArgs(2)), true)\n\t_, err := executeCommand(c, \"a\", \"b\")\n\tvalidOnlyWithInvalidArgs(err, t)\n}\n\nfunc TestMaximumNArgs_WithMoreArgs(t *testing.T) {\n\tc := getCommand(MaximumNArgs(2), false)\n\t_, err := executeCommand(c, \"a\", \"b\", \"c\")\n\tmaximumNArgsWithMoreArgs(err, t)\n}\n\nfunc TestMaximumNArgs_WithMoreArgs_WithValid(t *testing.T) {\n\tc := getCommand(MaximumNArgs(2), true)\n\t_, err := executeCommand(c, \"one\", \"three\", \"two\")\n\tmaximumNArgsWithMoreArgs(err, t)\n}\n\nfunc TestMaximumNArgs_WithMoreArgs_WithValid_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(MaximumNArgs(2), true)\n\t_, err := executeCommand(c, \"a\", \"b\", \"c\")\n\tmaximumNArgsWithMoreArgs(err, t)\n}\n\nfunc TestMaximumNArgs_WithMoreArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(MatchAll(OnlyValidArgs, MaximumNArgs(2)), true)\n\t_, err := executeCommand(c, \"a\", \"b\", \"c\")\n\tvalidOnlyWithInvalidArgs(err, t)\n}\n\n// ExactArgs\n\nfunc TestExactArgs(t *testing.T) {\n\tc := getCommand(ExactArgs(3), false)\n\toutput, err := executeCommand(c, \"a\", \"b\", \"c\")\n\texpectSuccess(output, err, t)\n}\n\nfunc TestExactArgs_WithValid(t *testing.T) {\n\tc := getCommand(ExactArgs(3), true)\n\toutput, err := executeCommand(c, \"three\", \"one\", \"two\")\n\texpectSuccess(output, err, t)\n}\n\nfunc TestExactArgs_WithValid_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(ExactArgs(3), true)\n\toutput, err := executeCommand(c, \"three\", \"a\", \"two\")\n\texpectSuccess(output, err, t)\n}\n\nfunc TestExactArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(MatchAll(OnlyValidArgs, ExactArgs(3)), true)\n\t_, err := executeCommand(c, \"three\", \"a\", \"two\")\n\tvalidOnlyWithInvalidArgs(err, t)\n}\n\nfunc TestExactArgs_WithInvalidCount(t *testing.T) {\n\tc := getCommand(ExactArgs(2), false)\n\t_, err := executeCommand(c, \"a\", \"b\", \"c\")\n\texactArgsWithInvalidCount(err, t)\n}\n\nfunc TestExactArgs_WithInvalidCount_WithValid(t *testing.T) {\n\tc := getCommand(ExactArgs(2), true)\n\t_, err := executeCommand(c, \"three\", \"one\", \"two\")\n\texactArgsWithInvalidCount(err, t)\n}\n\nfunc TestExactArgs_WithInvalidCount_WithValid_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(ExactArgs(2), true)\n\t_, err := executeCommand(c, \"three\", \"a\", \"two\")\n\texactArgsWithInvalidCount(err, t)\n}\n\nfunc TestExactArgs_WithInvalidCount_WithValidOnly_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(MatchAll(OnlyValidArgs, ExactArgs(2)), true)\n\t_, err := executeCommand(c, \"three\", \"a\", \"two\")\n\tvalidOnlyWithInvalidArgs(err, t)\n}\n\n// RangeArgs\n\nfunc TestRangeArgs(t *testing.T) {\n\tc := getCommand(RangeArgs(2, 4), false)\n\toutput, err := executeCommand(c, \"a\", \"b\", \"c\")\n\texpectSuccess(output, err, t)\n}\n\nfunc TestRangeArgs_WithValid(t *testing.T) {\n\tc := getCommand(RangeArgs(2, 4), true)\n\toutput, err := executeCommand(c, \"three\", \"one\", \"two\")\n\texpectSuccess(output, err, t)\n}\n\nfunc TestRangeArgs_WithValid_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(RangeArgs(2, 4), true)\n\toutput, err := executeCommand(c, \"three\", \"a\", \"two\")\n\texpectSuccess(output, err, t)\n}\n\nfunc TestRangeArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(MatchAll(OnlyValidArgs, RangeArgs(2, 4)), true)\n\t_, err := executeCommand(c, \"three\", \"a\", \"two\")\n\tvalidOnlyWithInvalidArgs(err, t)\n}\n\nfunc TestRangeArgs_WithInvalidCount(t *testing.T) {\n\tc := getCommand(RangeArgs(2, 4), false)\n\t_, err := executeCommand(c, \"a\")\n\trangeArgsWithInvalidCount(err, t)\n}\n\nfunc TestRangeArgs_WithInvalidCount_WithValid(t *testing.T) {\n\tc := getCommand(RangeArgs(2, 4), true)\n\t_, err := executeCommand(c, \"two\")\n\trangeArgsWithInvalidCount(err, t)\n}\n\nfunc TestRangeArgs_WithInvalidCount_WithValid_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(RangeArgs(2, 4), true)\n\t_, err := executeCommand(c, \"a\")\n\trangeArgsWithInvalidCount(err, t)\n}\n\nfunc TestRangeArgs_WithInvalidCount_WithValidOnly_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(MatchAll(OnlyValidArgs, RangeArgs(2, 4)), true)\n\t_, err := executeCommand(c, \"a\")\n\tvalidOnlyWithInvalidArgs(err, t)\n}\n\n// Takes(No)Args\n\nfunc TestRootTakesNoArgs(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchildCmd := &Command{Use: \"child\", Run: emptyRun}\n\trootCmd.AddCommand(childCmd)\n\n\t_, err := executeCommand(rootCmd, \"illegal\", \"args\")\n\tif err == nil {\n\t\tt.Fatal(\"Expected an error\")\n\t}\n\n\tgot := err.Error()\n\texpected := `unknown command \"illegal\" for \"root\"`\n\tif !strings.Contains(got, expected) {\n\t\tt.Errorf(\"expected %q, got %q\", expected, got)\n\t}\n}\n\nfunc TestRootTakesArgs(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: ArbitraryArgs, Run: emptyRun}\n\tchildCmd := &Command{Use: \"child\", Run: emptyRun}\n\trootCmd.AddCommand(childCmd)\n\n\t_, err := executeCommand(rootCmd, \"legal\", \"args\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n}\n\nfunc TestChildTakesNoArgs(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchildCmd := &Command{Use: \"child\", Args: NoArgs, Run: emptyRun}\n\trootCmd.AddCommand(childCmd)\n\n\t_, err := executeCommand(rootCmd, \"child\", \"illegal\", \"args\")\n\tif err == nil {\n\t\tt.Fatal(\"Expected an error\")\n\t}\n\n\tgot := err.Error()\n\texpected := `unknown command \"illegal\" for \"root child\"`\n\tif !strings.Contains(got, expected) {\n\t\tt.Errorf(\"expected %q, got %q\", expected, got)\n\t}\n}\n\nfunc TestChildTakesArgs(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchildCmd := &Command{Use: \"child\", Args: ArbitraryArgs, Run: emptyRun}\n\trootCmd.AddCommand(childCmd)\n\n\t_, err := executeCommand(rootCmd, \"child\", \"legal\", \"args\")\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t}\n}\n\nfunc TestMatchAll(t *testing.T) {\n\t// Somewhat contrived example check that ensures there are exactly 3\n\t// arguments, and each argument is exactly 2 bytes long.\n\tpargs := MatchAll(\n\t\tExactArgs(3),\n\t\tfunc(cmd *Command, args []string) error {\n\t\t\tfor _, arg := range args {\n\t\t\t\tif len([]byte(arg)) != 2 {\n\t\t\t\t\treturn fmt.Errorf(\"expected to be exactly 2 bytes long\")\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t)\n\n\ttestCases := map[string]struct {\n\t\targs []string\n\t\tfail bool\n\t}{\n\t\t\"happy path\": {\n\t\t\t[]string{\"aa\", \"bb\", \"cc\"},\n\t\t\tfalse,\n\t\t},\n\t\t\"incorrect number of args\": {\n\t\t\t[]string{\"aa\", \"bb\", \"cc\", \"dd\"},\n\t\t\ttrue,\n\t\t},\n\t\t\"incorrect number of bytes in one arg\": {\n\t\t\t[]string{\"aa\", \"bb\", \"abc\"},\n\t\t\ttrue,\n\t\t},\n\t}\n\n\trootCmd := &Command{Use: \"root\", Args: pargs, Run: emptyRun}\n\n\tfor name, tc := range testCases {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\t_, err := executeCommand(rootCmd, tc.args...)\n\t\t\tif err != nil && !tc.fail {\n\t\t\t\tt.Errorf(\"unexpected: %v\\n\", err)\n\t\t\t}\n\t\t\tif err == nil && tc.fail {\n\t\t\t\tt.Errorf(\"expected error\")\n\t\t\t}\n\t\t})\n\t}\n}\n\n// DEPRECATED\n\nfunc TestExactValidArgs(t *testing.T) {\n\tc := getCommand(ExactValidArgs(3), true)\n\toutput, err := executeCommand(c, \"three\", \"one\", \"two\")\n\texpectSuccess(output, err, t)\n}\n\nfunc TestExactValidArgs_WithInvalidCount(t *testing.T) {\n\tc := getCommand(ExactValidArgs(2), false)\n\t_, err := executeCommand(c, \"three\", \"one\", \"two\")\n\texactArgsWithInvalidCount(err, t)\n}\n\nfunc TestExactValidArgs_WithInvalidCount_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(ExactValidArgs(2), true)\n\t_, err := executeCommand(c, \"three\", \"a\", \"two\")\n\texactArgsWithInvalidCount(err, t)\n}\n\nfunc TestExactValidArgs_WithInvalidArgs(t *testing.T) {\n\tc := getCommand(ExactValidArgs(2), true)\n\t_, err := executeCommand(c, \"three\", \"a\")\n\tvalidOnlyWithInvalidArgs(err, t)\n}\n\n// This test make sure we keep backwards-compatibility with respect\n// to the legacyArgs() function.\n// It makes sure the root command accepts arguments if it does not have\n// sub-commands.\nfunc TestLegacyArgsRootAcceptsArgs(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: nil, Run: emptyRun}\n\n\t_, err := executeCommand(rootCmd, \"somearg\")\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t}\n}\n\n// This test make sure we keep backwards-compatibility with respect\n// to the legacyArgs() function.\n// It makes sure a sub-command accepts arguments and further sub-commands\nfunc TestLegacyArgsSubcmdAcceptsArgs(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: nil, Run: emptyRun}\n\tchildCmd := &Command{Use: \"child\", Args: nil, Run: emptyRun}\n\tgrandchildCmd := &Command{Use: \"grandchild\", Args: nil, Run: emptyRun}\n\trootCmd.AddCommand(childCmd)\n\tchildCmd.AddCommand(grandchildCmd)\n\n\t_, err := executeCommand(rootCmd, \"child\", \"somearg\")\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t}\n}\n"
  },
  {
    "path": "bash_completions.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com/spf13/pflag\"\n)\n\n// Annotations for Bash completion.\nconst (\n\tBashCompFilenameExt     = \"cobra_annotation_bash_completion_filename_extensions\"\n\tBashCompCustom          = \"cobra_annotation_bash_completion_custom\"\n\tBashCompOneRequiredFlag = \"cobra_annotation_bash_completion_one_required_flag\"\n\tBashCompSubdirsInDir    = \"cobra_annotation_bash_completion_subdirs_in_dir\"\n)\n\nfunc writePreamble(buf io.StringWriter, name string) {\n\tWriteStringAndCheck(buf, fmt.Sprintf(\"# bash completion for %-36s -*- shell-script -*-\\n\", name))\n\tWriteStringAndCheck(buf, fmt.Sprintf(`\n__%[1]s_debug()\n{\n    if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then\n        echo \"$*\" >> \"${BASH_COMP_DEBUG_FILE}\"\n    fi\n}\n\n# Homebrew on Macs have version 1.3 of bash-completion which doesn't include\n# _init_completion. This is a very minimal version of that function.\n__%[1]s_init_completion()\n{\n    COMPREPLY=()\n    _get_comp_words_by_ref \"$@\" cur prev words cword\n}\n\n__%[1]s_index_of_word()\n{\n    local w word=$1\n    shift\n    index=0\n    for w in \"$@\"; do\n        [[ $w = \"$word\" ]] && return\n        index=$((index+1))\n    done\n    index=-1\n}\n\n__%[1]s_contains_word()\n{\n    local w word=$1; shift\n    for w in \"$@\"; do\n        [[ $w = \"$word\" ]] && return\n    done\n    return 1\n}\n\n__%[1]s_handle_go_custom_completion()\n{\n    __%[1]s_debug \"${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}\"\n\n    local shellCompDirectiveError=%[3]d\n    local shellCompDirectiveNoSpace=%[4]d\n    local shellCompDirectiveNoFileComp=%[5]d\n    local shellCompDirectiveFilterFileExt=%[6]d\n    local shellCompDirectiveFilterDirs=%[7]d\n\n    local out requestComp lastParam lastChar comp directive args\n\n    # Prepare the command to request completions for the program.\n    # Calling ${words[0]} instead of directly %[1]s allows handling aliases\n    args=(\"${words[@]:1}\")\n    # Disable ActiveHelp which is not supported for bash completion v1\n    requestComp=\"%[8]s=0 ${words[0]} %[2]s ${args[*]}\"\n\n    lastParam=${words[$((${#words[@]}-1))]}\n    lastChar=${lastParam:$((${#lastParam}-1)):1}\n    __%[1]s_debug \"${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}\"\n\n    if [ -z \"${cur}\" ] && [ \"${lastChar}\" != \"=\" ]; then\n        # If the last parameter is complete (there is a space following it)\n        # We add an extra empty parameter so we can indicate this to the go method.\n        __%[1]s_debug \"${FUNCNAME[0]}: Adding extra empty parameter\"\n        requestComp=\"${requestComp} \\\"\\\"\"\n    fi\n\n    __%[1]s_debug \"${FUNCNAME[0]}: calling ${requestComp}\"\n    # Use eval to handle any environment variables and such\n    out=$(eval \"${requestComp}\" 2>/dev/null)\n\n    # Extract the directive integer at the very end of the output following a colon (:)\n    directive=${out##*:}\n    # Remove the directive\n    out=${out%%:*}\n    if [ \"${directive}\" = \"${out}\" ]; then\n        # There is not directive specified\n        directive=0\n    fi\n    __%[1]s_debug \"${FUNCNAME[0]}: the completion directive is: ${directive}\"\n    __%[1]s_debug \"${FUNCNAME[0]}: the completions are: ${out}\"\n\n    if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then\n        # Error code.  No completion.\n        __%[1]s_debug \"${FUNCNAME[0]}: received error from custom completion go code\"\n        return\n    else\n        if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then\n            if [[ $(type -t compopt) = \"builtin\" ]]; then\n                __%[1]s_debug \"${FUNCNAME[0]}: activating no space\"\n                compopt -o nospace\n            fi\n        fi\n        if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then\n            if [[ $(type -t compopt) = \"builtin\" ]]; then\n                __%[1]s_debug \"${FUNCNAME[0]}: activating no file completion\"\n                compopt +o default\n            fi\n        fi\n    fi\n\n    if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then\n        # File extension filtering\n        local fullFilter filter filteringCmd\n        # Do not use quotes around the $out variable or else newline\n        # characters will be kept.\n        for filter in ${out}; do\n            fullFilter+=\"$filter|\"\n        done\n\n        filteringCmd=\"_filedir $fullFilter\"\n        __%[1]s_debug \"File filtering command: $filteringCmd\"\n        $filteringCmd\n    elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then\n        # File completion for directories only\n        local subdir\n        # Use printf to strip any trailing newline\n        subdir=$(printf \"%%s\" \"${out}\")\n        if [ -n \"$subdir\" ]; then\n            __%[1]s_debug \"Listing directories in $subdir\"\n            __%[1]s_handle_subdirs_in_dir_flag \"$subdir\"\n        else\n            __%[1]s_debug \"Listing directories in .\"\n            _filedir -d\n        fi\n    else\n        while IFS='' read -r comp; do\n            COMPREPLY+=(\"$comp\")\n        done < <(compgen -W \"${out}\" -- \"$cur\")\n    fi\n}\n\n__%[1]s_handle_reply()\n{\n    __%[1]s_debug \"${FUNCNAME[0]}\"\n    local comp\n    case $cur in\n        -*)\n            if [[ $(type -t compopt) = \"builtin\" ]]; then\n                compopt -o nospace\n            fi\n            local allflags\n            if [ ${#must_have_one_flag[@]} -ne 0 ]; then\n                allflags=(\"${must_have_one_flag[@]}\")\n            else\n                allflags=(\"${flags[*]} ${two_word_flags[*]}\")\n            fi\n            while IFS='' read -r comp; do\n                COMPREPLY+=(\"$comp\")\n            done < <(compgen -W \"${allflags[*]}\" -- \"$cur\")\n            if [[ $(type -t compopt) = \"builtin\" ]]; then\n                [[ \"${COMPREPLY[0]}\" == *= ]] || compopt +o nospace\n            fi\n\n            # complete after --flag=abc\n            if [[ $cur == *=* ]]; then\n                if [[ $(type -t compopt) = \"builtin\" ]]; then\n                    compopt +o nospace\n                fi\n\n                local index flag\n                flag=\"${cur%%=*}\"\n                __%[1]s_index_of_word \"${flag}\" \"${flags_with_completion[@]}\"\n                COMPREPLY=()\n                if [[ ${index} -ge 0 ]]; then\n                    PREFIX=\"\"\n                    cur=\"${cur#*=}\"\n                    ${flags_completion[${index}]}\n                    if [ -n \"${ZSH_VERSION:-}\" ]; then\n                        # zsh completion needs --flag= prefix\n                        eval \"COMPREPLY=( \\\"\\${COMPREPLY[@]/#/${flag}=}\\\" )\"\n                    fi\n                fi\n            fi\n\n            if [[ -z \"${flag_parsing_disabled}\" ]]; then\n                # If flag parsing is enabled, we have completed the flags and can return.\n                # If flag parsing is disabled, we may not know all (or any) of the flags, so we fallthrough\n                # to possibly call handle_go_custom_completion.\n                return 0;\n            fi\n            ;;\n    esac\n\n    # check if we are handling a flag with special work handling\n    local index\n    __%[1]s_index_of_word \"${prev}\" \"${flags_with_completion[@]}\"\n    if [[ ${index} -ge 0 ]]; then\n        ${flags_completion[${index}]}\n        return\n    fi\n\n    # we are parsing a flag and don't have a special handler, no completion\n    if [[ ${cur} != \"${words[cword]}\" ]]; then\n        return\n    fi\n\n    local completions\n    completions=(\"${commands[@]}\")\n    if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then\n        completions+=(\"${must_have_one_noun[@]}\")\n    elif [[ -n \"${has_completion_function}\" ]]; then\n        # if a go completion function is provided, defer to that function\n        __%[1]s_handle_go_custom_completion\n    fi\n    if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then\n        completions+=(\"${must_have_one_flag[@]}\")\n    fi\n    while IFS='' read -r comp; do\n        COMPREPLY+=(\"$comp\")\n    done < <(compgen -W \"${completions[*]}\" -- \"$cur\")\n\n    if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then\n        while IFS='' read -r comp; do\n            COMPREPLY+=(\"$comp\")\n        done < <(compgen -W \"${noun_aliases[*]}\" -- \"$cur\")\n    fi\n\n    if [[ ${#COMPREPLY[@]} -eq 0 ]]; then\n        if declare -F __%[1]s_custom_func >/dev/null; then\n            # try command name qualified custom func\n            __%[1]s_custom_func\n        else\n            # otherwise fall back to unqualified for compatibility\n            declare -F __custom_func >/dev/null && __custom_func\n        fi\n    fi\n\n    # available in bash-completion >= 2, not always present on macOS\n    if declare -F __ltrim_colon_completions >/dev/null; then\n        __ltrim_colon_completions \"$cur\"\n    fi\n\n    # If there is only 1 completion and it is a flag with an = it will be completed\n    # but we don't want a space after the =\n    if [[ \"${#COMPREPLY[@]}\" -eq \"1\" ]] && [[ $(type -t compopt) = \"builtin\" ]] && [[ \"${COMPREPLY[0]}\" == --*= ]]; then\n       compopt -o nospace\n    fi\n}\n\n# The arguments should be in the form \"ext1|ext2|extn\"\n__%[1]s_handle_filename_extension_flag()\n{\n    local ext=\"$1\"\n    _filedir \"@(${ext})\"\n}\n\n__%[1]s_handle_subdirs_in_dir_flag()\n{\n    local dir=\"$1\"\n    pushd \"${dir}\" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return\n}\n\n__%[1]s_handle_flag()\n{\n    __%[1]s_debug \"${FUNCNAME[0]}: c is $c words[c] is ${words[c]}\"\n\n    # if a command required a flag, and we found it, unset must_have_one_flag()\n    local flagname=${words[c]}\n    local flagvalue=\"\"\n    # if the word contained an =\n    if [[ ${words[c]} == *\"=\"* ]]; then\n        flagvalue=${flagname#*=} # take in as flagvalue after the =\n        flagname=${flagname%%=*} # strip everything after the =\n        flagname=\"${flagname}=\" # but put the = back\n    fi\n    __%[1]s_debug \"${FUNCNAME[0]}: looking for ${flagname}\"\n    if __%[1]s_contains_word \"${flagname}\" \"${must_have_one_flag[@]}\"; then\n        must_have_one_flag=()\n    fi\n\n    # if you set a flag which only applies to this command, don't show subcommands\n    if __%[1]s_contains_word \"${flagname}\" \"${local_nonpersistent_flags[@]}\"; then\n      commands=()\n    fi\n\n    # keep flag value with flagname as flaghash\n    # flaghash variable is an associative array which is only supported in bash > 3.\n    if [[ -z \"${BASH_VERSION:-}\" || \"${BASH_VERSINFO[0]:-}\" -gt 3 ]]; then\n        if [ -n \"${flagvalue}\" ] ; then\n            flaghash[${flagname}]=${flagvalue}\n        elif [ -n \"${words[ $((c+1)) ]}\" ] ; then\n            flaghash[${flagname}]=${words[ $((c+1)) ]}\n        else\n            flaghash[${flagname}]=\"true\" # pad \"true\" for bool flag\n        fi\n    fi\n\n    # skip the argument to a two word flag\n    if [[ ${words[c]} != *\"=\"* ]] && __%[1]s_contains_word \"${words[c]}\" \"${two_word_flags[@]}\"; then\n        __%[1]s_debug \"${FUNCNAME[0]}: found a flag ${words[c]}, skip the next argument\"\n        c=$((c+1))\n        # if we are looking for a flags value, don't show commands\n        if [[ $c -eq $cword ]]; then\n            commands=()\n        fi\n    fi\n\n    c=$((c+1))\n\n}\n\n__%[1]s_handle_noun()\n{\n    __%[1]s_debug \"${FUNCNAME[0]}: c is $c words[c] is ${words[c]}\"\n\n    if __%[1]s_contains_word \"${words[c]}\" \"${must_have_one_noun[@]}\"; then\n        must_have_one_noun=()\n    elif __%[1]s_contains_word \"${words[c]}\" \"${noun_aliases[@]}\"; then\n        must_have_one_noun=()\n    fi\n\n    nouns+=(\"${words[c]}\")\n    c=$((c+1))\n}\n\n__%[1]s_handle_command()\n{\n    __%[1]s_debug \"${FUNCNAME[0]}: c is $c words[c] is ${words[c]}\"\n\n    local next_command\n    if [[ -n ${last_command} ]]; then\n        next_command=\"_${last_command}_${words[c]//:/__}\"\n    else\n        if [[ $c -eq 0 ]]; then\n            next_command=\"_%[1]s_root_command\"\n        else\n            next_command=\"_${words[c]//:/__}\"\n        fi\n    fi\n    c=$((c+1))\n    __%[1]s_debug \"${FUNCNAME[0]}: looking for ${next_command}\"\n    declare -F \"$next_command\" >/dev/null && $next_command\n}\n\n__%[1]s_handle_word()\n{\n    if [[ $c -ge $cword ]]; then\n        __%[1]s_handle_reply\n        return\n    fi\n    __%[1]s_debug \"${FUNCNAME[0]}: c is $c words[c] is ${words[c]}\"\n    if [[ \"${words[c]}\" == -* ]]; then\n        __%[1]s_handle_flag\n    elif __%[1]s_contains_word \"${words[c]}\" \"${commands[@]}\"; then\n        __%[1]s_handle_command\n    elif [[ $c -eq 0 ]]; then\n        __%[1]s_handle_command\n    elif __%[1]s_contains_word \"${words[c]}\" \"${command_aliases[@]}\"; then\n        # aliashash variable is an associative array which is only supported in bash > 3.\n        if [[ -z \"${BASH_VERSION:-}\" || \"${BASH_VERSINFO[0]:-}\" -gt 3 ]]; then\n            words[c]=${aliashash[${words[c]}]}\n            __%[1]s_handle_command\n        else\n            __%[1]s_handle_noun\n        fi\n    else\n        __%[1]s_handle_noun\n    fi\n    __%[1]s_handle_word\n}\n\n`, name, ShellCompNoDescRequestCmd,\n\t\tShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,\n\t\tShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))\n}\n\nfunc writePostscript(buf io.StringWriter, name string) {\n\tname = strings.ReplaceAll(name, \":\", \"__\")\n\tWriteStringAndCheck(buf, fmt.Sprintf(\"__start_%s()\\n\", name))\n\tWriteStringAndCheck(buf, fmt.Sprintf(`{\n    local cur prev words cword split\n    declare -A flaghash 2>/dev/null || :\n    declare -A aliashash 2>/dev/null || :\n    if declare -F _init_completion >/dev/null 2>&1; then\n        _init_completion -s || return\n    else\n        __%[1]s_init_completion -n \"=\" || return\n    fi\n\n    local c=0\n    local flag_parsing_disabled=\n    local flags=()\n    local two_word_flags=()\n    local local_nonpersistent_flags=()\n    local flags_with_completion=()\n    local flags_completion=()\n    local commands=(\"%[1]s\")\n    local command_aliases=()\n    local must_have_one_flag=()\n    local must_have_one_noun=()\n    local has_completion_function=\"\"\n    local last_command=\"\"\n    local nouns=()\n    local noun_aliases=()\n\n    __%[1]s_handle_word\n}\n\n`, name))\n\tWriteStringAndCheck(buf, fmt.Sprintf(`if [[ $(type -t compopt) = \"builtin\" ]]; then\n    complete -o default -F __start_%s %s\nelse\n    complete -o default -o nospace -F __start_%s %s\nfi\n\n`, name, name, name, name))\n\tWriteStringAndCheck(buf, \"# ex: ts=4 sw=4 et filetype=sh\\n\")\n}\n\nfunc writeCommands(buf io.StringWriter, cmd *Command) {\n\tWriteStringAndCheck(buf, \"    commands=()\\n\")\n\tfor _, c := range cmd.Commands() {\n\t\tif !c.IsAvailableCommand() && c != cmd.helpCommand {\n\t\t\tcontinue\n\t\t}\n\t\tWriteStringAndCheck(buf, fmt.Sprintf(\"    commands+=(%q)\\n\", c.Name()))\n\t\twriteCmdAliases(buf, c)\n\t}\n\tWriteStringAndCheck(buf, \"\\n\")\n}\n\nfunc writeFlagHandler(buf io.StringWriter, name string, annotations map[string][]string, cmd *Command) {\n\tfor key, value := range annotations {\n\t\tswitch key {\n\t\tcase BashCompFilenameExt:\n\t\t\tWriteStringAndCheck(buf, fmt.Sprintf(\"    flags_with_completion+=(%q)\\n\", name))\n\n\t\t\tvar ext string\n\t\t\tif len(value) > 0 {\n\t\t\t\text = fmt.Sprintf(\"__%s_handle_filename_extension_flag \", cmd.Root().Name()) + strings.Join(value, \"|\")\n\t\t\t} else {\n\t\t\t\text = \"_filedir\"\n\t\t\t}\n\t\t\tWriteStringAndCheck(buf, fmt.Sprintf(\"    flags_completion+=(%q)\\n\", ext))\n\t\tcase BashCompCustom:\n\t\t\tWriteStringAndCheck(buf, fmt.Sprintf(\"    flags_with_completion+=(%q)\\n\", name))\n\n\t\t\tif len(value) > 0 {\n\t\t\t\thandlers := strings.Join(value, \"; \")\n\t\t\t\tWriteStringAndCheck(buf, fmt.Sprintf(\"    flags_completion+=(%q)\\n\", handlers))\n\t\t\t} else {\n\t\t\t\tWriteStringAndCheck(buf, \"    flags_completion+=(:)\\n\")\n\t\t\t}\n\t\tcase BashCompSubdirsInDir:\n\t\t\tWriteStringAndCheck(buf, fmt.Sprintf(\"    flags_with_completion+=(%q)\\n\", name))\n\n\t\t\tvar ext string\n\t\t\tif len(value) == 1 {\n\t\t\t\text = fmt.Sprintf(\"__%s_handle_subdirs_in_dir_flag \", cmd.Root().Name()) + value[0]\n\t\t\t} else {\n\t\t\t\text = \"_filedir -d\"\n\t\t\t}\n\t\t\tWriteStringAndCheck(buf, fmt.Sprintf(\"    flags_completion+=(%q)\\n\", ext))\n\t\t}\n\t}\n}\n\nconst cbn = \"\\\")\\n\"\n\nfunc writeShortFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) {\n\tname := flag.Shorthand\n\tformat := \"    \"\n\tif len(flag.NoOptDefVal) == 0 {\n\t\tformat += \"two_word_\"\n\t}\n\tformat += \"flags+=(\\\"-%s\" + cbn\n\tWriteStringAndCheck(buf, fmt.Sprintf(format, name))\n\twriteFlagHandler(buf, \"-\"+name, flag.Annotations, cmd)\n}\n\nfunc writeFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) {\n\tname := flag.Name\n\tformat := \"    flags+=(\\\"--%s\"\n\tif len(flag.NoOptDefVal) == 0 {\n\t\tformat += \"=\"\n\t}\n\tformat += cbn\n\tWriteStringAndCheck(buf, fmt.Sprintf(format, name))\n\tif len(flag.NoOptDefVal) == 0 {\n\t\tformat = \"    two_word_flags+=(\\\"--%s\" + cbn\n\t\tWriteStringAndCheck(buf, fmt.Sprintf(format, name))\n\t}\n\twriteFlagHandler(buf, \"--\"+name, flag.Annotations, cmd)\n}\n\nfunc writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) {\n\tname := flag.Name\n\tformat := \"    local_nonpersistent_flags+=(\\\"--%[1]s\" + cbn\n\tif len(flag.NoOptDefVal) == 0 {\n\t\tformat += \"    local_nonpersistent_flags+=(\\\"--%[1]s=\" + cbn\n\t}\n\tWriteStringAndCheck(buf, fmt.Sprintf(format, name))\n\tif len(flag.Shorthand) > 0 {\n\t\tWriteStringAndCheck(buf, fmt.Sprintf(\"    local_nonpersistent_flags+=(\\\"-%s\\\")\\n\", flag.Shorthand))\n\t}\n}\n\n// prepareCustomAnnotationsForFlags setup annotations for go completions for registered flags\nfunc prepareCustomAnnotationsForFlags(cmd *Command) {\n\tflagCompletionMutex.RLock()\n\tdefer flagCompletionMutex.RUnlock()\n\tfor flag := range flagCompletionFunctions {\n\t\t// Make sure the completion script calls the __*_go_custom_completion function for\n\t\t// every registered flag.  We need to do this here (and not when the flag was registered\n\t\t// for completion) so that we can know the root command name for the prefix\n\t\t// of __<prefix>_go_custom_completion\n\t\tif flag.Annotations == nil {\n\t\t\tflag.Annotations = map[string][]string{}\n\t\t}\n\t\tflag.Annotations[BashCompCustom] = []string{fmt.Sprintf(\"__%[1]s_handle_go_custom_completion\", cmd.Root().Name())}\n\t}\n}\n\nfunc writeFlags(buf io.StringWriter, cmd *Command) {\n\tprepareCustomAnnotationsForFlags(cmd)\n\tWriteStringAndCheck(buf, `    flags=()\n    two_word_flags=()\n    local_nonpersistent_flags=()\n    flags_with_completion=()\n    flags_completion=()\n\n`)\n\n\tif cmd.DisableFlagParsing {\n\t\tWriteStringAndCheck(buf, \"    flag_parsing_disabled=1\\n\")\n\t}\n\n\tlocalNonPersistentFlags := cmd.LocalNonPersistentFlags()\n\tcmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {\n\t\tif nonCompletableFlag(flag) {\n\t\t\treturn\n\t\t}\n\t\twriteFlag(buf, flag, cmd)\n\t\tif len(flag.Shorthand) > 0 {\n\t\t\twriteShortFlag(buf, flag, cmd)\n\t\t}\n\t\t// localNonPersistentFlags are used to stop the completion of subcommands when one is set\n\t\t// if TraverseChildren is true we should allow to complete subcommands\n\t\tif localNonPersistentFlags.Lookup(flag.Name) != nil && !cmd.Root().TraverseChildren {\n\t\t\twriteLocalNonPersistentFlag(buf, flag)\n\t\t}\n\t})\n\tcmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {\n\t\tif nonCompletableFlag(flag) {\n\t\t\treturn\n\t\t}\n\t\twriteFlag(buf, flag, cmd)\n\t\tif len(flag.Shorthand) > 0 {\n\t\t\twriteShortFlag(buf, flag, cmd)\n\t\t}\n\t})\n\n\tWriteStringAndCheck(buf, \"\\n\")\n}\n\nfunc writeRequiredFlag(buf io.StringWriter, cmd *Command) {\n\tWriteStringAndCheck(buf, \"    must_have_one_flag=()\\n\")\n\tflags := cmd.NonInheritedFlags()\n\tflags.VisitAll(func(flag *pflag.Flag) {\n\t\tif nonCompletableFlag(flag) {\n\t\t\treturn\n\t\t}\n\t\tif _, ok := flag.Annotations[BashCompOneRequiredFlag]; ok {\n\t\t\tformat := \"    must_have_one_flag+=(\\\"--%s\"\n\t\t\tif flag.Value.Type() != \"bool\" {\n\t\t\t\tformat += \"=\"\n\t\t\t}\n\t\t\tformat += cbn\n\t\t\tWriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name))\n\n\t\t\tif len(flag.Shorthand) > 0 {\n\t\t\t\tWriteStringAndCheck(buf, fmt.Sprintf(\"    must_have_one_flag+=(\\\"-%s\"+cbn, flag.Shorthand))\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc writeRequiredNouns(buf io.StringWriter, cmd *Command) {\n\tWriteStringAndCheck(buf, \"    must_have_one_noun=()\\n\")\n\tsort.Strings(cmd.ValidArgs)\n\tfor _, value := range cmd.ValidArgs {\n\t\t// Remove any description that may be included following a tab character.\n\t\t// Descriptions are not supported by bash completion.\n\t\tvalue = strings.SplitN(value, \"\\t\", 2)[0]\n\t\tWriteStringAndCheck(buf, fmt.Sprintf(\"    must_have_one_noun+=(%q)\\n\", value))\n\t}\n\tif cmd.ValidArgsFunction != nil {\n\t\tWriteStringAndCheck(buf, \"    has_completion_function=1\\n\")\n\t}\n}\n\nfunc writeCmdAliases(buf io.StringWriter, cmd *Command) {\n\tif len(cmd.Aliases) == 0 {\n\t\treturn\n\t}\n\n\tsort.Strings(cmd.Aliases)\n\n\tWriteStringAndCheck(buf, fmt.Sprint(`    if [[ -z \"${BASH_VERSION:-}\" || \"${BASH_VERSINFO[0]:-}\" -gt 3 ]]; then`, \"\\n\"))\n\tfor _, value := range cmd.Aliases {\n\t\tWriteStringAndCheck(buf, fmt.Sprintf(\"        command_aliases+=(%q)\\n\", value))\n\t\tWriteStringAndCheck(buf, fmt.Sprintf(\"        aliashash[%q]=%q\\n\", value, cmd.Name()))\n\t}\n\tWriteStringAndCheck(buf, `    fi`)\n\tWriteStringAndCheck(buf, \"\\n\")\n}\nfunc writeArgAliases(buf io.StringWriter, cmd *Command) {\n\tWriteStringAndCheck(buf, \"    noun_aliases=()\\n\")\n\tsort.Strings(cmd.ArgAliases)\n\tfor _, value := range cmd.ArgAliases {\n\t\tWriteStringAndCheck(buf, fmt.Sprintf(\"    noun_aliases+=(%q)\\n\", value))\n\t}\n}\n\nfunc gen(buf io.StringWriter, cmd *Command) {\n\tfor _, c := range cmd.Commands() {\n\t\tif !c.IsAvailableCommand() && c != cmd.helpCommand {\n\t\t\tcontinue\n\t\t}\n\t\tgen(buf, c)\n\t}\n\tcommandName := cmd.CommandPath()\n\tcommandName = strings.ReplaceAll(commandName, \" \", \"_\")\n\tcommandName = strings.ReplaceAll(commandName, \":\", \"__\")\n\n\tif cmd.Root() == cmd {\n\t\tWriteStringAndCheck(buf, fmt.Sprintf(\"_%s_root_command()\\n{\\n\", commandName))\n\t} else {\n\t\tWriteStringAndCheck(buf, fmt.Sprintf(\"_%s()\\n{\\n\", commandName))\n\t}\n\n\tWriteStringAndCheck(buf, fmt.Sprintf(\"    last_command=%q\\n\", commandName))\n\tWriteStringAndCheck(buf, \"\\n\")\n\tWriteStringAndCheck(buf, \"    command_aliases=()\\n\")\n\tWriteStringAndCheck(buf, \"\\n\")\n\n\twriteCommands(buf, cmd)\n\twriteFlags(buf, cmd)\n\twriteRequiredFlag(buf, cmd)\n\twriteRequiredNouns(buf, cmd)\n\twriteArgAliases(buf, cmd)\n\tWriteStringAndCheck(buf, \"}\\n\\n\")\n}\n\n// GenBashCompletion generates bash completion file and writes to the passed writer.\nfunc (c *Command) GenBashCompletion(w io.Writer) error {\n\tbuf := new(bytes.Buffer)\n\twritePreamble(buf, c.Name())\n\tif len(c.BashCompletionFunction) > 0 {\n\t\tbuf.WriteString(c.BashCompletionFunction + \"\\n\")\n\t}\n\tgen(buf, c)\n\twritePostscript(buf, c.Name())\n\n\t_, err := buf.WriteTo(w)\n\treturn err\n}\n\nfunc nonCompletableFlag(flag *pflag.Flag) bool {\n\treturn flag.Hidden || len(flag.Deprecated) > 0\n}\n\n// GenBashCompletionFile generates bash completion file.\nfunc (c *Command) GenBashCompletionFile(filename string) error {\n\toutFile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer outFile.Close()\n\n\treturn c.GenBashCompletion(outFile)\n}\n"
  },
  {
    "path": "bash_completionsV2.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\nfunc (c *Command) genBashCompletion(w io.Writer, includeDesc bool) error {\n\tbuf := new(bytes.Buffer)\n\tgenBashComp(buf, c.Name(), includeDesc)\n\t_, err := buf.WriteTo(w)\n\treturn err\n}\n\nfunc genBashComp(buf io.StringWriter, name string, includeDesc bool) {\n\tcompCmd := ShellCompRequestCmd\n\tif !includeDesc {\n\t\tcompCmd = ShellCompNoDescRequestCmd\n\t}\n\n\tWriteStringAndCheck(buf, fmt.Sprintf(`# bash completion V2 for %-36[1]s -*- shell-script -*-\n\n__%[1]s_debug()\n{\n    if [[ -n ${BASH_COMP_DEBUG_FILE-} ]]; then\n        echo \"$*\" >> \"${BASH_COMP_DEBUG_FILE}\"\n    fi\n}\n\n# Macs have bash3 for which the bash-completion package doesn't include\n# _init_completion. This is a minimal version of that function.\n__%[1]s_init_completion()\n{\n    COMPREPLY=()\n    _get_comp_words_by_ref \"$@\" cur prev words cword\n}\n\n# This function calls the %[1]s program to obtain the completion\n# results and the directive.  It fills the 'out' and 'directive' vars.\n__%[1]s_get_completion_results() {\n    local requestComp lastParam lastChar args\n\n    # Prepare the command to request completions for the program.\n    # Calling ${words[0]} instead of directly %[1]s allows handling aliases\n    args=(\"${words[@]:1}\")\n    requestComp=\"${words[0]} %[2]s ${args[*]}\"\n\n    lastParam=${words[$((${#words[@]}-1))]}\n    lastChar=${lastParam:$((${#lastParam}-1)):1}\n    __%[1]s_debug \"lastParam ${lastParam}, lastChar ${lastChar}\"\n\n    if [[ -z ${cur} && ${lastChar} != = ]]; then\n        # If the last parameter is complete (there is a space following it)\n        # We add an extra empty parameter so we can indicate this to the go method.\n        __%[1]s_debug \"Adding extra empty parameter\"\n        requestComp=\"${requestComp} ''\"\n    fi\n\n    # When completing a flag with an = (e.g., %[1]s -n=<TAB>)\n    # bash focuses on the part after the =, so we need to remove\n    # the flag part from $cur\n    if [[ ${cur} == -*=* ]]; then\n        cur=\"${cur#*=}\"\n    fi\n\n    __%[1]s_debug \"Calling ${requestComp}\"\n    # Use eval to handle any environment variables and such\n    out=$(eval \"${requestComp}\" 2>/dev/null)\n\n    # Extract the directive integer at the very end of the output following a colon (:)\n    directive=${out##*:}\n    # Remove the directive\n    out=${out%%:*}\n    if [[ ${directive} == \"${out}\" ]]; then\n        # There is not directive specified\n        directive=0\n    fi\n    __%[1]s_debug \"The completion directive is: ${directive}\"\n    __%[1]s_debug \"The completions are: ${out}\"\n}\n\n__%[1]s_process_completion_results() {\n    local shellCompDirectiveError=%[3]d\n    local shellCompDirectiveNoSpace=%[4]d\n    local shellCompDirectiveNoFileComp=%[5]d\n    local shellCompDirectiveFilterFileExt=%[6]d\n    local shellCompDirectiveFilterDirs=%[7]d\n    local shellCompDirectiveKeepOrder=%[8]d\n\n    if (((directive & shellCompDirectiveError) != 0)); then\n        # Error code.  No completion.\n        __%[1]s_debug \"Received error from custom completion go code\"\n        return\n    else\n        if (((directive & shellCompDirectiveNoSpace) != 0)); then\n            if [[ $(type -t compopt) == builtin ]]; then\n                __%[1]s_debug \"Activating no space\"\n                compopt -o nospace\n            else\n                __%[1]s_debug \"No space directive not supported in this version of bash\"\n            fi\n        fi\n        if (((directive & shellCompDirectiveKeepOrder) != 0)); then\n            if [[ $(type -t compopt) == builtin ]]; then\n                # no sort isn't supported for bash less than < 4.4\n                if [[ ${BASH_VERSINFO[0]} -lt 4 || ( ${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -lt 4 ) ]]; then\n                    __%[1]s_debug \"No sort directive not supported in this version of bash\"\n                else\n                    __%[1]s_debug \"Activating keep order\"\n                    compopt -o nosort\n                fi\n            else\n                __%[1]s_debug \"No sort directive not supported in this version of bash\"\n            fi\n        fi\n        if (((directive & shellCompDirectiveNoFileComp) != 0)); then\n            if [[ $(type -t compopt) == builtin ]]; then\n                __%[1]s_debug \"Activating no file completion\"\n                compopt +o default\n            else\n                __%[1]s_debug \"No file completion directive not supported in this version of bash\"\n            fi\n        fi\n    fi\n\n    # Separate activeHelp from normal completions\n    local completions=()\n    local activeHelp=()\n    __%[1]s_extract_activeHelp\n\n    if (((directive & shellCompDirectiveFilterFileExt) != 0)); then\n        # File extension filtering\n        local fullFilter=\"\" filter filteringCmd\n\n        # Do not use quotes around the $completions variable or else newline\n        # characters will be kept.\n        for filter in ${completions[*]}; do\n            fullFilter+=\"$filter|\"\n        done\n\n        filteringCmd=\"_filedir $fullFilter\"\n        __%[1]s_debug \"File filtering command: $filteringCmd\"\n        $filteringCmd\n    elif (((directive & shellCompDirectiveFilterDirs) != 0)); then\n        # File completion for directories only\n\n        local subdir\n        subdir=${completions[0]}\n        if [[ -n $subdir ]]; then\n            __%[1]s_debug \"Listing directories in $subdir\"\n            pushd \"$subdir\" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return\n        else\n            __%[1]s_debug \"Listing directories in .\"\n            _filedir -d\n        fi\n    else\n        __%[1]s_handle_completion_types\n    fi\n\n    __%[1]s_handle_special_char \"$cur\" :\n    __%[1]s_handle_special_char \"$cur\" =\n\n    # Print the activeHelp statements before we finish\n    __%[1]s_handle_activeHelp\n}\n\n__%[1]s_handle_activeHelp() {\n    # Print the activeHelp statements\n    if ((${#activeHelp[*]} != 0)); then\n        if [ -z $COMP_TYPE ]; then\n            # Bash v3 does not set the COMP_TYPE variable.\n            printf \"\\n\";\n            printf \"%%s\\n\" \"${activeHelp[@]}\"\n            printf \"\\n\"\n            __%[1]s_reprint_commandLine\n            return\n        fi\n\n        # Only print ActiveHelp on the second TAB press\n        if [ $COMP_TYPE -eq 63 ]; then\n            printf \"\\n\"\n            printf \"%%s\\n\" \"${activeHelp[@]}\"\n\n            if ((${#COMPREPLY[*]} == 0)); then\n                # When there are no completion choices from the program, file completion\n                # may kick in if the program has not disabled it; in such a case, we want\n                # to know if any files will match what the user typed, so that we know if\n                # there will be completions presented, so that we know how to handle ActiveHelp.\n                # To find out, we actually trigger the file completion ourselves;\n                # the call to _filedir will fill COMPREPLY if files match.\n                if (((directive & shellCompDirectiveNoFileComp) == 0)); then\n                    __%[1]s_debug \"Listing files\"\n                    _filedir\n                fi\n            fi\n\n            if ((${#COMPREPLY[*]} != 0)); then\n                # If there are completion choices to be shown, print a delimiter.\n                # Re-printing the command-line will automatically be done\n                # by the shell when it prints the completion choices.\n                printf -- \"--\"\n            else\n                # When there are no completion choices at all, we need\n                # to re-print the command-line since the shell will\n                # not be doing it itself.\n                __%[1]s_reprint_commandLine\n            fi\n        elif [ $COMP_TYPE -eq 37 ] || [ $COMP_TYPE -eq 42 ]; then\n            # For completion type: menu-complete/menu-complete-backward and insert-completions\n            # the completions are immediately inserted into the command-line, so we first\n            # print the activeHelp message and reprint the command-line since the shell won't.\n            printf \"\\n\"\n            printf \"%%s\\n\" \"${activeHelp[@]}\"\n\n            __%[1]s_reprint_commandLine\n        fi\n    fi\n}\n\n__%[1]s_reprint_commandLine() {\n    # The prompt format is only available from bash 4.4.\n    # We test if it is available before using it.\n    if (x=${PS1@P}) 2> /dev/null; then\n        printf \"%%s\" \"${PS1@P}${COMP_LINE[@]}\"\n    else\n        # Can't print the prompt.  Just print the\n        # text the user had typed, it is workable enough.\n        printf \"%%s\" \"${COMP_LINE[@]}\"\n    fi\n}\n\n# Separate activeHelp lines from real completions.\n# Fills the $activeHelp and $completions arrays.\n__%[1]s_extract_activeHelp() {\n    local activeHelpMarker=\"%[9]s\"\n    local endIndex=${#activeHelpMarker}\n\n    while IFS='' read -r comp; do\n        [[ -z $comp ]] && continue\n\n        if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then\n            comp=${comp:endIndex}\n            __%[1]s_debug \"ActiveHelp found: $comp\"\n            if [[ -n $comp ]]; then\n                activeHelp+=(\"$comp\")\n            fi\n        else\n            # Not an activeHelp line but a normal completion\n            completions+=(\"$comp\")\n        fi\n    done <<<\"${out}\"\n}\n\n__%[1]s_handle_completion_types() {\n    __%[1]s_debug \"__%[1]s_handle_completion_types: COMP_TYPE is $COMP_TYPE\"\n\n    case $COMP_TYPE in\n    37|42)\n        # Type: menu-complete/menu-complete-backward and insert-completions\n        # If the user requested inserting one completion at a time, or all\n        # completions at once on the command-line we must remove the descriptions.\n        # https://github.com/spf13/cobra/issues/1508\n\n        # If there are no completions, we don't need to do anything\n        (( ${#completions[@]} == 0 )) && return 0\n\n        local tab=$'\\t'\n\n        # Strip any description and escape the completion to handled special characters\n        IFS=$'\\n' read -ra completions -d '' < <(printf \"%%q\\n\" \"${completions[@]%%%%$tab*}\")\n\n        # Only consider the completions that match\n        IFS=$'\\n' read -ra COMPREPLY -d '' < <(IFS=$'\\n'; compgen -W \"${completions[*]}\" -- \"${cur}\")\n\n        # compgen looses the escaping so we need to escape all completions again since they will\n        # all be inserted on the command-line.\n        IFS=$'\\n' read -ra COMPREPLY -d '' < <(printf \"%%q\\n\" \"${COMPREPLY[@]}\")\n        ;;\n\n    *)\n        # Type: complete (normal completion)\n        __%[1]s_handle_standard_completion_case\n        ;;\n    esac\n}\n\n__%[1]s_handle_standard_completion_case() {\n    local tab=$'\\t'\n\n    # If there are no completions, we don't need to do anything\n    (( ${#completions[@]} == 0 )) && return 0\n\n    # Short circuit to optimize if we don't have descriptions\n    if [[ \"${completions[*]}\" != *$tab* ]]; then\n        # First, escape the completions to handle special characters\n        IFS=$'\\n' read -ra completions -d '' < <(printf \"%%q\\n\" \"${completions[@]}\")\n        # Only consider the completions that match what the user typed\n        IFS=$'\\n' read -ra COMPREPLY -d '' < <(IFS=$'\\n'; compgen -W \"${completions[*]}\" -- \"${cur}\")\n\n        # compgen looses the escaping so, if there is only a single completion, we need to\n        # escape it again because it will be inserted on the command-line.  If there are multiple\n        # completions, we don't want to escape them because they will be printed in a list\n        # and we don't want to show escape characters in that list.\n        if (( ${#COMPREPLY[@]} == 1 )); then\n            COMPREPLY[0]=$(printf \"%%q\" \"${COMPREPLY[0]}\")\n        fi\n        return 0\n    fi\n\n    local longest=0\n    local compline\n    # Look for the longest completion so that we can format things nicely\n    for compline in \"${completions[@]}\"; do\n        [[ -z $compline ]] && continue\n\n        # Before checking if the completion matches what the user typed,\n        # we need to strip any description and escape the completion to handle special\n        # characters because those escape characters are part of what the user typed.\n        # Don't call \"printf\" in a sub-shell because it will be much slower\n        # since we are in a loop.\n        printf -v comp \"%%q\" \"${compline%%%%$tab*}\" &>/dev/null || comp=$(printf \"%%q\" \"${compline%%%%$tab*}\")\n\n        # Only consider the completions that match\n        [[ $comp == \"$cur\"* ]] || continue\n\n        # The completions matches.  Add it to the list of full completions including\n        # its description.  We don't escape the completion because it may get printed\n        # in a list if there are more than one and we don't want show escape characters\n        # in that list.\n        COMPREPLY+=(\"$compline\")\n\n        # Strip any description before checking the length, and again, don't escape\n        # the completion because this length is only used when printing the completions\n        # in a list and we don't want show escape characters in that list.\n        comp=${compline%%%%$tab*}\n        if ((${#comp}>longest)); then\n            longest=${#comp}\n        fi\n    done\n\n    # If there is a single completion left, remove the description text and escape any special characters\n    if ((${#COMPREPLY[*]} == 1)); then\n        __%[1]s_debug \"COMPREPLY[0]: ${COMPREPLY[0]}\"\n        COMPREPLY[0]=$(printf \"%%q\" \"${COMPREPLY[0]%%%%$tab*}\")\n        __%[1]s_debug \"Removed description from single completion, which is now: ${COMPREPLY[0]}\"\n    else\n        # Format the descriptions\n        __%[1]s_format_comp_descriptions $longest\n    fi\n}\n\n__%[1]s_handle_special_char()\n{\n    local comp=\"$1\"\n    local char=$2\n    if [[ \"$comp\" == *${char}* && \"$COMP_WORDBREAKS\" == *${char}* ]]; then\n        local word=${comp%%\"${comp##*${char}}\"}\n        local idx=${#COMPREPLY[*]}\n        while ((--idx >= 0)); do\n            COMPREPLY[idx]=${COMPREPLY[idx]#\"$word\"}\n        done\n    fi\n}\n\n__%[1]s_format_comp_descriptions()\n{\n    local tab=$'\\t'\n    local comp desc maxdesclength\n    local longest=$1\n\n    local i ci\n    for ci in ${!COMPREPLY[*]}; do\n        comp=${COMPREPLY[ci]}\n        # Properly format the description string which follows a tab character if there is one\n        if [[ \"$comp\" == *$tab* ]]; then\n            __%[1]s_debug \"Original comp: $comp\"\n            desc=${comp#*$tab}\n            comp=${comp%%%%$tab*}\n\n            # $COLUMNS stores the current shell width.\n            # Remove an extra 4 because we add 2 spaces and 2 parentheses.\n            maxdesclength=$(( COLUMNS - longest - 4 ))\n\n            # Make sure we can fit a description of at least 8 characters\n            # if we are to align the descriptions.\n            if ((maxdesclength > 8)); then\n                # Add the proper number of spaces to align the descriptions\n                for ((i = ${#comp} ; i < longest ; i++)); do\n                    comp+=\" \"\n                done\n            else\n                # Don't pad the descriptions so we can fit more text after the completion\n                maxdesclength=$(( COLUMNS - ${#comp} - 4 ))\n            fi\n\n            # If there is enough space for any description text,\n            # truncate the descriptions that are too long for the shell width\n            if ((maxdesclength > 0)); then\n                if ((${#desc} > maxdesclength)); then\n                    desc=${desc:0:$(( maxdesclength - 1 ))}\n                    desc+=\"…\"\n                fi\n                comp+=\"  ($desc)\"\n            fi\n            COMPREPLY[ci]=$comp\n            __%[1]s_debug \"Final comp: $comp\"\n        fi\n    done\n}\n\n__start_%[1]s()\n{\n    local cur prev words cword split\n\n    COMPREPLY=()\n\n    # Call _init_completion from the bash-completion package\n    # to prepare the arguments properly\n    if declare -F _init_completion >/dev/null 2>&1; then\n        _init_completion -n =: || return\n    else\n        __%[1]s_init_completion -n =: || return\n    fi\n\n    __%[1]s_debug\n    __%[1]s_debug \"========= starting completion logic ==========\"\n    __%[1]s_debug \"cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword\"\n\n    # The user could have moved the cursor backwards on the command-line.\n    # We need to trigger completion from the $cword location, so we need\n    # to truncate the command-line ($words) up to the $cword location.\n    words=(\"${words[@]:0:$cword+1}\")\n    __%[1]s_debug \"Truncated words[*]: ${words[*]},\"\n\n    local out directive\n    __%[1]s_get_completion_results\n    __%[1]s_process_completion_results\n}\n\nif [[ $(type -t compopt) = \"builtin\" ]]; then\n    complete -o default -F __start_%[1]s %[1]s\nelse\n    complete -o default -o nospace -F __start_%[1]s %[1]s\nfi\n\n# ex: ts=4 sw=4 et filetype=sh\n`, name, compCmd,\n\t\tShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,\n\t\tShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder,\n\t\tactiveHelpMarker))\n}\n\n// GenBashCompletionFileV2 generates Bash completion version 2.\nfunc (c *Command) GenBashCompletionFileV2(filename string, includeDesc bool) error {\n\toutFile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer outFile.Close()\n\n\treturn c.GenBashCompletionV2(outFile, includeDesc)\n}\n\n// GenBashCompletionV2 generates Bash completion file version 2\n// and writes it to the passed writer.\nfunc (c *Command) GenBashCompletionV2(w io.Writer, includeDesc bool) error {\n\treturn c.genBashCompletion(w, includeDesc)\n}\n"
  },
  {
    "path": "bash_completionsV2_test.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestBashCompletionV2WithActiveHelp(t *testing.T) {\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, c.GenBashCompletionV2(buf, true))\n\toutput := buf.String()\n\n\t// check that active help is not being disabled\n\tactiveHelpVar := activeHelpEnvVar(c.Name())\n\tcheckOmit(t, output, fmt.Sprintf(\"%s=0\", activeHelpVar))\n}\n"
  },
  {
    "path": "bash_completions_test.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"regexp\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc checkOmit(t *testing.T, found, unexpected string) {\n\tif strings.Contains(found, unexpected) {\n\t\tt.Errorf(\"Got: %q\\nBut should not have!\\n\", unexpected)\n\t}\n}\n\nfunc check(t *testing.T, found, expected string) {\n\tif !strings.Contains(found, expected) {\n\t\tt.Errorf(\"Expecting to contain: \\n %q\\nGot:\\n %q\\n\", expected, found)\n\t}\n}\n\nfunc checkNumOccurrences(t *testing.T, found, expected string, expectedOccurrences int) {\n\tnumOccurrences := strings.Count(found, expected)\n\tif numOccurrences != expectedOccurrences {\n\t\tt.Errorf(\"Expecting to contain %d occurrences of: \\n %q\\nGot %d:\\n %q\\n\", expectedOccurrences, expected, numOccurrences, found)\n\t}\n}\n\nfunc checkRegex(t *testing.T, found, pattern string) {\n\tmatched, err := regexp.MatchString(pattern, found)\n\tif err != nil {\n\t\tt.Errorf(\"Error thrown performing MatchString: \\n %s\\n\", err)\n\t}\n\tif !matched {\n\t\tt.Errorf(\"Expecting to match: \\n %q\\nGot:\\n %q\\n\", pattern, found)\n\t}\n}\n\nfunc runShellCheck(s string) error {\n\tcmd := exec.Command(\"shellcheck\", \"-s\", \"bash\", \"-\", \"-e\",\n\t\t\"SC2034\", // PREFIX appears unused. Verify it or export it.\n\t)\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdout = os.Stdout\n\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo func() {\n\t\t_, err := stdin.Write([]byte(s))\n\t\tCheckErr(err)\n\n\t\tstdin.Close()\n\t}()\n\n\treturn cmd.Run()\n}\n\n// World worst custom function, just keep telling you to enter hello!\nconst bashCompletionFunc = `__root_custom_func() {\n\tCOMPREPLY=( \"hello\" )\n}\n`\n\nfunc TestBashCompletions(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse:                    \"root\",\n\t\tArgAliases:             []string{\"pods\", \"nodes\", \"services\", \"replicationcontrollers\", \"po\", \"no\", \"svc\", \"rc\"},\n\t\tValidArgs:              []string{\"pod\", \"node\", \"service\", \"replicationcontroller\"},\n\t\tBashCompletionFunction: bashCompletionFunc,\n\t\tRun:                    emptyRun,\n\t}\n\trootCmd.Flags().IntP(\"introot\", \"i\", -1, \"help message for flag introot\")\n\tassertNoErr(t, rootCmd.MarkFlagRequired(\"introot\"))\n\n\t// Filename.\n\trootCmd.Flags().String(\"filename\", \"\", \"Enter a filename\")\n\tassertNoErr(t, rootCmd.MarkFlagFilename(\"filename\", \"json\", \"yaml\", \"yml\"))\n\n\t// Persistent filename.\n\trootCmd.PersistentFlags().String(\"persistent-filename\", \"\", \"Enter a filename\")\n\tassertNoErr(t, rootCmd.MarkPersistentFlagFilename(\"persistent-filename\"))\n\tassertNoErr(t, rootCmd.MarkPersistentFlagRequired(\"persistent-filename\"))\n\n\t// Filename extensions.\n\trootCmd.Flags().String(\"filename-ext\", \"\", \"Enter a filename (extension limited)\")\n\tassertNoErr(t, rootCmd.MarkFlagFilename(\"filename-ext\"))\n\trootCmd.Flags().String(\"custom\", \"\", \"Enter a filename (extension limited)\")\n\tassertNoErr(t, rootCmd.MarkFlagCustom(\"custom\", \"__complete_custom\"))\n\n\t// Subdirectories in a given directory.\n\trootCmd.Flags().String(\"theme\", \"\", \"theme to use (located in /themes/THEMENAME/)\")\n\tassertNoErr(t, rootCmd.Flags().SetAnnotation(\"theme\", BashCompSubdirsInDir, []string{\"themes\"}))\n\n\t// For two word flags check\n\trootCmd.Flags().StringP(\"two\", \"t\", \"\", \"this is two word flags\")\n\trootCmd.Flags().BoolP(\"two-w-default\", \"T\", false, \"this is not two word flags\")\n\n\techoCmd := &Command{\n\t\tUse:     \"echo [string to echo]\",\n\t\tAliases: []string{\"say\"},\n\t\tShort:   \"Echo anything to the screen\",\n\t\tLong:    \"an utterly useless command for testing.\",\n\t\tExample: \"Just run cobra-test echo\",\n\t\tRun:     emptyRun,\n\t}\n\n\techoCmd.Flags().String(\"filename\", \"\", \"Enter a filename\")\n\tassertNoErr(t, echoCmd.MarkFlagFilename(\"filename\", \"json\", \"yaml\", \"yml\"))\n\techoCmd.Flags().String(\"config\", \"\", \"config to use (located in /config/PROFILE/)\")\n\tassertNoErr(t, echoCmd.Flags().SetAnnotation(\"config\", BashCompSubdirsInDir, []string{\"config\"}))\n\n\tprintCmd := &Command{\n\t\tUse:   \"print [string to print]\",\n\t\tArgs:  MinimumNArgs(1),\n\t\tShort: \"Print anything to the screen\",\n\t\tLong:  \"an absolutely utterly useless command for testing.\",\n\t\tRun:   emptyRun,\n\t}\n\n\tdeprecatedCmd := &Command{\n\t\tUse:        \"deprecated [can't do anything here]\",\n\t\tArgs:       NoArgs,\n\t\tShort:      \"A command which is deprecated\",\n\t\tLong:       \"an absolutely utterly useless command for testing deprecation!.\",\n\t\tDeprecated: \"Please use echo instead\",\n\t\tRun:        emptyRun,\n\t}\n\n\tcolonCmd := &Command{\n\t\tUse: \"cmd:colon\",\n\t\tRun: emptyRun,\n\t}\n\n\ttimesCmd := &Command{\n\t\tUse:        \"times [# times] [string to echo]\",\n\t\tSuggestFor: []string{\"counts\"},\n\t\tArgs:       OnlyValidArgs,\n\t\tValidArgs:  []string{\"one\", \"two\", \"three\", \"four\"},\n\t\tShort:      \"Echo anything to the screen more times\",\n\t\tLong:       \"a slightly useless command for testing.\",\n\t\tRun:        emptyRun,\n\t}\n\n\techoCmd.AddCommand(timesCmd)\n\trootCmd.AddCommand(echoCmd, printCmd, deprecatedCmd, colonCmd)\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenBashCompletion(buf))\n\toutput := buf.String()\n\n\tcheck(t, output, \"_root\")\n\tcheck(t, output, \"_root_echo\")\n\tcheck(t, output, \"_root_echo_times\")\n\tcheck(t, output, \"_root_print\")\n\tcheck(t, output, \"_root_cmd__colon\")\n\n\t// check for required flags\n\tcheck(t, output, `must_have_one_flag+=(\"--introot=\")`)\n\tcheck(t, output, `must_have_one_flag+=(\"--persistent-filename=\")`)\n\t// check for custom completion function with both qualified and unqualified name\n\tcheckNumOccurrences(t, output, `__custom_func`, 2)      // 1. check existence, 2. invoke\n\tcheckNumOccurrences(t, output, `__root_custom_func`, 3) // 1. check existence, 2. invoke, 3. actual definition\n\t// check for custom completion function body\n\tcheck(t, output, `COMPREPLY=( \"hello\" )`)\n\t// check for required nouns\n\tcheck(t, output, `must_have_one_noun+=(\"pod\")`)\n\t// check for noun aliases\n\tcheck(t, output, `noun_aliases+=(\"pods\")`)\n\tcheck(t, output, `noun_aliases+=(\"rc\")`)\n\tcheckOmit(t, output, `must_have_one_noun+=(\"pods\")`)\n\t// check for filename extension flags\n\tcheck(t, output, `flags_completion+=(\"_filedir\")`)\n\t// check for filename extension flags\n\tcheck(t, output, `must_have_one_noun+=(\"three\")`)\n\t// check for filename extension flags\n\tcheck(t, output, fmt.Sprintf(`flags_completion+=(\"__%s_handle_filename_extension_flag json|yaml|yml\")`, rootCmd.Name()))\n\t// check for filename extension flags in a subcommand\n\tcheckRegex(t, output, fmt.Sprintf(`_root_echo\\(\\)\\n{[^}]*flags_completion\\+=\\(\"__%s_handle_filename_extension_flag json\\|yaml\\|yml\"\\)`, rootCmd.Name()))\n\t// check for custom flags\n\tcheck(t, output, `flags_completion+=(\"__complete_custom\")`)\n\t// check for subdirs_in_dir flags\n\tcheck(t, output, fmt.Sprintf(`flags_completion+=(\"__%s_handle_subdirs_in_dir_flag themes\")`, rootCmd.Name()))\n\t// check for subdirs_in_dir flags in a subcommand\n\tcheckRegex(t, output, fmt.Sprintf(`_root_echo\\(\\)\\n{[^}]*flags_completion\\+=\\(\"__%s_handle_subdirs_in_dir_flag config\"\\)`, rootCmd.Name()))\n\n\t// check two word flags\n\tcheck(t, output, `two_word_flags+=(\"--two\")`)\n\tcheck(t, output, `two_word_flags+=(\"-t\")`)\n\tcheckOmit(t, output, `two_word_flags+=(\"--two-w-default\")`)\n\tcheckOmit(t, output, `two_word_flags+=(\"-T\")`)\n\n\t// check local nonpersistent flag\n\tcheck(t, output, `local_nonpersistent_flags+=(\"--two\")`)\n\tcheck(t, output, `local_nonpersistent_flags+=(\"--two=\")`)\n\tcheck(t, output, `local_nonpersistent_flags+=(\"-t\")`)\n\tcheck(t, output, `local_nonpersistent_flags+=(\"--two-w-default\")`)\n\tcheck(t, output, `local_nonpersistent_flags+=(\"-T\")`)\n\n\tcheckOmit(t, output, deprecatedCmd.Name())\n\n\t// If available, run shellcheck against the script.\n\tif err := exec.Command(\"which\", \"shellcheck\").Run(); err != nil {\n\t\treturn\n\t}\n\tif err := runShellCheck(output); err != nil {\n\t\tt.Fatalf(\"shellcheck failed: %v\", err)\n\t}\n}\n\nfunc TestBashCompletionHiddenFlag(t *testing.T) {\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\n\tconst flagName = \"hiddenFlag\"\n\tc.Flags().Bool(flagName, false, \"\")\n\tassertNoErr(t, c.Flags().MarkHidden(flagName))\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, c.GenBashCompletion(buf))\n\toutput := buf.String()\n\n\tif strings.Contains(output, flagName) {\n\t\tt.Errorf(\"Expected completion to not include %q flag: Got %v\", flagName, output)\n\t}\n}\n\nfunc TestBashCompletionDeprecatedFlag(t *testing.T) {\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\n\tconst flagName = \"deprecated-flag\"\n\tc.Flags().Bool(flagName, false, \"\")\n\tassertNoErr(t, c.Flags().MarkDeprecated(flagName, \"use --not-deprecated instead\"))\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, c.GenBashCompletion(buf))\n\toutput := buf.String()\n\n\tif strings.Contains(output, flagName) {\n\t\tt.Errorf(\"expected completion to not include %q flag: Got %v\", flagName, output)\n\t}\n}\n\nfunc TestBashCompletionTraverseChildren(t *testing.T) {\n\tc := &Command{Use: \"c\", Run: emptyRun, TraverseChildren: true}\n\n\tc.Flags().StringP(\"string-flag\", \"s\", \"\", \"string flag\")\n\tc.Flags().BoolP(\"bool-flag\", \"b\", false, \"bool flag\")\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, c.GenBashCompletion(buf))\n\toutput := buf.String()\n\n\t// check that local nonpersistent flag are not set since we have TraverseChildren set to true\n\tcheckOmit(t, output, `local_nonpersistent_flags+=(\"--string-flag\")`)\n\tcheckOmit(t, output, `local_nonpersistent_flags+=(\"--string-flag=\")`)\n\tcheckOmit(t, output, `local_nonpersistent_flags+=(\"-s\")`)\n\tcheckOmit(t, output, `local_nonpersistent_flags+=(\"--bool-flag\")`)\n\tcheckOmit(t, output, `local_nonpersistent_flags+=(\"-b\")`)\n}\n\nfunc TestBashCompletionNoActiveHelp(t *testing.T) {\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, c.GenBashCompletion(buf))\n\toutput := buf.String()\n\n\t// check that active help is being disabled\n\tactiveHelpVar := activeHelpEnvVar(c.Name())\n\tcheck(t, output, fmt.Sprintf(\"%s=0\", activeHelpVar))\n}\n"
  },
  {
    "path": "cobra.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// Commands similar to git, go tools and other modern CLI tools\n// inspired by go, go-Commander, gh and subcommand\n\npackage cobra\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text/template\"\n\t\"time\"\n\t\"unicode\"\n)\n\nvar templateFuncs = template.FuncMap{\n\t\"trim\":                    strings.TrimSpace,\n\t\"trimRightSpace\":          trimRightSpace,\n\t\"trimTrailingWhitespaces\": trimRightSpace,\n\t\"appendIfNotPresent\":      appendIfNotPresent,\n\t\"rpad\":                    rpad,\n\t\"gt\":                      Gt,\n\t\"eq\":                      Eq,\n}\n\nvar initializers []func()\nvar finalizers []func()\n\nconst (\n\tdefaultPrefixMatching   = false\n\tdefaultCommandSorting   = true\n\tdefaultCaseInsensitive  = false\n\tdefaultTraverseRunHooks = false\n)\n\n// EnablePrefixMatching allows setting automatic prefix matching. Automatic prefix matching can be a dangerous thing\n// to automatically enable in CLI tools.\n// Set this to true to enable it.\nvar EnablePrefixMatching = defaultPrefixMatching\n\n// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default.\n// To disable sorting, set it to false.\nvar EnableCommandSorting = defaultCommandSorting\n\n// EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default)\nvar EnableCaseInsensitive = defaultCaseInsensitive\n\n// EnableTraverseRunHooks executes persistent pre-run and post-run hooks from all parents.\n// By default this is disabled, which means only the first run hook to be found is executed.\nvar EnableTraverseRunHooks = defaultTraverseRunHooks\n\n// MousetrapHelpText enables an information splash screen on Windows\n// if the CLI is started from explorer.exe.\n// To disable the mousetrap, just set this variable to blank string (\"\").\n// Works only on Microsoft Windows.\nvar MousetrapHelpText = `This is a command line tool.\n\nYou need to open cmd.exe and run it from there.\n`\n\n// MousetrapDisplayDuration controls how long the MousetrapHelpText message is displayed on Windows\n// if the CLI is started from explorer.exe. Set to 0 to wait for the return key to be pressed.\n// To disable the mousetrap, just set MousetrapHelpText to blank string (\"\").\n// Works only on Microsoft Windows.\nvar MousetrapDisplayDuration = 5 * time.Second\n\n// AddTemplateFunc adds a template function that's available to Usage and Help\n// template generation.\nfunc AddTemplateFunc(name string, tmplFunc interface{}) {\n\ttemplateFuncs[name] = tmplFunc\n}\n\n// AddTemplateFuncs adds multiple template functions that are available to Usage and\n// Help template generation.\nfunc AddTemplateFuncs(tmplFuncs template.FuncMap) {\n\tfor k, v := range tmplFuncs {\n\t\ttemplateFuncs[k] = v\n\t}\n}\n\n// OnInitialize sets the passed functions to be run when each command's\n// Execute method is called.\nfunc OnInitialize(y ...func()) {\n\tinitializers = append(initializers, y...)\n}\n\n// OnFinalize sets the passed functions to be run when each command's\n// Execute method is terminated.\nfunc OnFinalize(y ...func()) {\n\tfinalizers = append(finalizers, y...)\n}\n\n// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.\n\n// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,\n// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as\n// ints and then compared.\nfunc Gt(a interface{}, b interface{}) bool {\n\tvar left, right int64\n\tav := reflect.ValueOf(a)\n\n\tswitch av.Kind() {\n\tcase reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:\n\t\tleft = int64(av.Len())\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\tleft = av.Int()\n\tcase reflect.String:\n\t\tleft, _ = strconv.ParseInt(av.String(), 10, 64)\n\t}\n\n\tbv := reflect.ValueOf(b)\n\n\tswitch bv.Kind() {\n\tcase reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:\n\t\tright = int64(bv.Len())\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\tright = bv.Int()\n\tcase reflect.String:\n\t\tright, _ = strconv.ParseInt(bv.String(), 10, 64)\n\t}\n\n\treturn left > right\n}\n\n// FIXME Eq is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.\n\n// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.\nfunc Eq(a interface{}, b interface{}) bool {\n\tav := reflect.ValueOf(a)\n\tbv := reflect.ValueOf(b)\n\n\tswitch av.Kind() {\n\tcase reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:\n\t\tpanic(\"Eq called on unsupported type\")\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\treturn av.Int() == bv.Int()\n\tcase reflect.String:\n\t\treturn av.String() == bv.String()\n\t}\n\treturn false\n}\n\nfunc trimRightSpace(s string) string {\n\treturn strings.TrimRightFunc(s, unicode.IsSpace)\n}\n\n// FIXME appendIfNotPresent is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.\n\n// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s.\nfunc appendIfNotPresent(s, stringToAppend string) string {\n\tif strings.Contains(s, stringToAppend) {\n\t\treturn s\n\t}\n\treturn s + \" \" + stringToAppend\n}\n\n// rpad adds padding to the right of a string.\nfunc rpad(s string, padding int) string {\n\tformattedString := fmt.Sprintf(\"%%-%ds\", padding)\n\treturn fmt.Sprintf(formattedString, s)\n}\n\nfunc tmpl(text string) *tmplFunc {\n\treturn &tmplFunc{\n\t\ttmpl: text,\n\t\tfn: func(w io.Writer, data interface{}) error {\n\t\t\tt := template.New(\"top\")\n\t\t\tt.Funcs(templateFuncs)\n\t\t\ttemplate.Must(t.Parse(text))\n\t\t\treturn t.Execute(w, data)\n\t\t},\n\t}\n}\n\n// ld compares two strings and returns the levenshtein distance between them.\nfunc ld(s, t string, ignoreCase bool) int {\n\tif ignoreCase {\n\t\ts = strings.ToLower(s)\n\t\tt = strings.ToLower(t)\n\t}\n\td := make([][]int, len(s)+1)\n\tfor i := range d {\n\t\td[i] = make([]int, len(t)+1)\n\t\td[i][0] = i\n\t}\n\tfor j := range d[0] {\n\t\td[0][j] = j\n\t}\n\tfor j := 1; j <= len(t); j++ {\n\t\tfor i := 1; i <= len(s); i++ {\n\t\t\tif s[i-1] == t[j-1] {\n\t\t\t\td[i][j] = d[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tmin := d[i-1][j]\n\t\t\t\tif d[i][j-1] < min {\n\t\t\t\t\tmin = d[i][j-1]\n\t\t\t\t}\n\t\t\t\tif d[i-1][j-1] < min {\n\t\t\t\t\tmin = d[i-1][j-1]\n\t\t\t\t}\n\t\t\t\td[i][j] = min + 1\n\t\t\t}\n\t\t}\n\n\t}\n\treturn d[len(s)][len(t)]\n}\n\nfunc stringInSlice(a string, list []string) bool {\n\tfor _, b := range list {\n\t\tif b == a {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// CheckErr prints the msg with the prefix 'Error:' and exits with error code 1. If the msg is nil, it does nothing.\nfunc CheckErr(msg interface{}) {\n\tif msg != nil {\n\t\tfmt.Fprintln(os.Stderr, \"Error:\", msg)\n\t\tos.Exit(1)\n\t}\n}\n\n// WriteStringAndCheck writes a string into a buffer, and checks if the error is not nil.\nfunc WriteStringAndCheck(b io.StringWriter, s string) {\n\t_, err := b.WriteString(s)\n\tCheckErr(err)\n}\n"
  },
  {
    "path": "cobra_test.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\t\"text/template\"\n)\n\nfunc assertNoErr(t *testing.T, e error) {\n\tif e != nil {\n\t\tt.Error(e)\n\t}\n}\n\nfunc TestAddTemplateFunctions(t *testing.T) {\n\tAddTemplateFunc(\"t\", func() bool { return true })\n\tAddTemplateFuncs(template.FuncMap{\n\t\t\"f\": func() bool { return false },\n\t\t\"h\": func() string { return \"Hello,\" },\n\t\t\"w\": func() string { return \"world.\" }})\n\n\tc := &Command{}\n\tc.SetUsageTemplate(`{{if t}}{{h}}{{end}}{{if f}}{{h}}{{end}} {{w}}`)\n\n\tconst expected = \"Hello, world.\"\n\tif got := c.UsageString(); got != expected {\n\t\tt.Errorf(\"Expected UsageString: %v\\nGot: %v\", expected, got)\n\t}\n}\n\nfunc TestLevenshteinDistance(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\ts          string\n\t\tt          string\n\t\tignoreCase bool\n\t\texpected   int\n\t}{\n\t\t{\n\t\t\tname:       \"Equal strings (case-sensitive)\",\n\t\t\ts:          \"hello\",\n\t\t\tt:          \"hello\",\n\t\t\tignoreCase: false,\n\t\t\texpected:   0,\n\t\t},\n\t\t{\n\t\t\tname:       \"Equal strings (case-insensitive)\",\n\t\t\ts:          \"Hello\",\n\t\t\tt:          \"hello\",\n\t\t\tignoreCase: true,\n\t\t\texpected:   0,\n\t\t},\n\t\t{\n\t\t\tname:       \"Different strings (case-sensitive)\",\n\t\t\ts:          \"kitten\",\n\t\t\tt:          \"sitting\",\n\t\t\tignoreCase: false,\n\t\t\texpected:   3,\n\t\t},\n\t\t{\n\t\t\tname:       \"Different strings (case-insensitive)\",\n\t\t\ts:          \"Kitten\",\n\t\t\tt:          \"Sitting\",\n\t\t\tignoreCase: true,\n\t\t\texpected:   3,\n\t\t},\n\t\t{\n\t\t\tname:       \"Empty strings\",\n\t\t\ts:          \"\",\n\t\t\tt:          \"\",\n\t\t\tignoreCase: false,\n\t\t\texpected:   0,\n\t\t},\n\t\t{\n\t\t\tname:       \"One empty string\",\n\t\t\ts:          \"abc\",\n\t\t\tt:          \"\",\n\t\t\tignoreCase: false,\n\t\t\texpected:   3,\n\t\t},\n\t\t{\n\t\t\tname:       \"Both empty strings\",\n\t\t\ts:          \"\",\n\t\t\tt:          \"\",\n\t\t\tignoreCase: true,\n\t\t\texpected:   0,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t// Act\n\t\t\tgot := ld(tt.s, tt.t, tt.ignoreCase)\n\n\t\t\t// Assert\n\t\t\tif got != tt.expected {\n\t\t\t\tt.Errorf(\"Expected ld: %v\\nGot: %v\", tt.expected, got)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestStringInSlice(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\ta        string\n\t\tlist     []string\n\t\texpected bool\n\t}{\n\t\t{\n\t\t\tname:     \"String in slice (case-sensitive)\",\n\t\t\ta:        \"apple\",\n\t\t\tlist:     []string{\"orange\", \"banana\", \"apple\", \"grape\"},\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname:     \"String not in slice (case-sensitive)\",\n\t\t\ta:        \"pear\",\n\t\t\tlist:     []string{\"orange\", \"banana\", \"apple\", \"grape\"},\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname:     \"String in slice (case-insensitive)\",\n\t\t\ta:        \"APPLE\",\n\t\t\tlist:     []string{\"orange\", \"banana\", \"apple\", \"grape\"},\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname:     \"Empty slice\",\n\t\t\ta:        \"apple\",\n\t\t\tlist:     []string{},\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname:     \"Empty string\",\n\t\t\ta:        \"\",\n\t\t\tlist:     []string{\"orange\", \"banana\", \"apple\", \"grape\"},\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname:     \"Empty strings match\",\n\t\t\ta:        \"\",\n\t\t\tlist:     []string{\"orange\", \"\"},\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname:     \"Empty string in empty slice\",\n\t\t\ta:        \"\",\n\t\t\tlist:     []string{},\n\t\t\texpected: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t// Act\n\t\t\tgot := stringInSlice(tt.a, tt.list)\n\n\t\t\t// Assert\n\t\t\tif got != tt.expected {\n\t\t\t\tt.Errorf(\"Expected stringInSlice: %v\\nGot: %v\", tt.expected, got)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestRpad(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tinputString string\n\t\tpadding     int\n\t\texpected    string\n\t}{\n\t\t{\n\t\t\tname:        \"Padding required\",\n\t\t\tinputString: \"Hello\",\n\t\t\tpadding:     10,\n\t\t\texpected:    \"Hello     \",\n\t\t},\n\t\t{\n\t\t\tname:        \"No padding required\",\n\t\t\tinputString: \"World\",\n\t\t\tpadding:     5,\n\t\t\texpected:    \"World\",\n\t\t},\n\t\t{\n\t\t\tname:        \"Empty string\",\n\t\t\tinputString: \"\",\n\t\t\tpadding:     8,\n\t\t\texpected:    \"        \",\n\t\t},\n\t\t{\n\t\t\tname:        \"Zero padding\",\n\t\t\tinputString: \"cobra\",\n\t\t\tpadding:     0,\n\t\t\texpected:    \"cobra\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t// Act\n\t\t\tgot := rpad(tt.inputString, tt.padding)\n\n\t\t\t// Assert\n\t\t\tif got != tt.expected {\n\t\t\t\tt.Errorf(\"Expected rpad: %v\\nGot: %v\", tt.expected, got)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// TestDeadcodeElimination checks that a simple program using cobra in its\n// default configuration is linked taking full advantage of the linker's\n// deadcode elimination step.\n//\n// If reflect.Value.MethodByName/reflect.Value.Method are reachable the\n// linker will not always be able to prove that exported methods are\n// unreachable, making deadcode elimination less effective. Using\n// text/template and html/template makes reflect.Value.MethodByName\n// reachable.\n// Since cobra can use text/template templates this test checks that in its\n// default configuration that code path can be proven to be unreachable by\n// the linker.\n//\n// See also: https://github.com/spf13/cobra/pull/1956\nfunc TestDeadcodeElimination(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"go tool nm fails on windows\")\n\t}\n\n\t// check that a simple program using cobra in its default configuration is\n\t// linked with deadcode elimination enabled.\n\tconst (\n\t\tdirname  = \"test_deadcode\"\n\t\tprogname = \"test_deadcode_elimination\"\n\t)\n\t_ = os.Mkdir(dirname, 0770)\n\tdefer os.RemoveAll(dirname)\n\tfilename := filepath.Join(dirname, progname+\".go\")\n\terr := os.WriteFile(filename, []byte(`package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nvar rootCmd = &cobra.Command{\n\tVersion: \"1.0\",\n\tUse:     \"example_program\",\n\tShort:   \"example_program - test fixture to check that deadcode elimination is allowed\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tfmt.Println(\"hello world\")\n\t},\n\tAliases: []string{\"alias1\", \"alias2\"},\n\tExample: \"stringer --help\",\n}\n\nfunc main() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Whoops. There was an error while executing your CLI '%s'\", err)\n\t\tos.Exit(1)\n\t}\n}\n`), 0600)\n\tif err != nil {\n\t\tt.Fatalf(\"could not write test program: %v\", err)\n\t}\n\tbuf, err := exec.Command(\"go\", \"build\", filename).CombinedOutput()\n\tif err != nil {\n\t\tt.Fatalf(\"could not compile test program: %s\", string(buf))\n\t}\n\tdefer os.Remove(progname)\n\tbuf, err = exec.Command(\"go\", \"tool\", \"nm\", progname).CombinedOutput()\n\tif err != nil {\n\t\tt.Fatalf(\"could not run go tool nm: %v\", err)\n\t}\n\tif strings.Contains(string(buf), \"MethodByName\") {\n\t\tt.Error(\"compiled programs contains MethodByName symbol\")\n\t}\n}\n"
  },
  {
    "path": "command.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces.\n// In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code.\npackage cobra\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n\n\tflag \"github.com/spf13/pflag\"\n)\n\nconst (\n\tFlagSetByCobraAnnotation     = \"cobra_annotation_flag_set_by_cobra\"\n\tCommandDisplayNameAnnotation = \"cobra_annotation_command_display_name\"\n\n\thelpFlagName    = \"help\"\n\thelpCommandName = \"help\"\n)\n\n// FParseErrWhitelist configures Flag parse errors to be ignored\ntype FParseErrWhitelist flag.ParseErrorsAllowlist\n\n// Group Structure to manage groups for commands\ntype Group struct {\n\tID    string\n\tTitle string\n}\n\n// Command is just that, a command for your application.\n// E.g.  'go run ...' - 'run' is the command. Cobra requires\n// you to define the usage and description as part of your command\n// definition to ensure usability.\ntype Command struct {\n\t// Use is the one-line usage message.\n\t// Recommended syntax is as follows:\n\t//   [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required.\n\t//   ... indicates that you can specify multiple values for the previous argument.\n\t//   |   indicates mutually exclusive information. You can use the argument to the left of the separator or the\n\t//       argument to the right of the separator. You cannot use both arguments in a single use of the command.\n\t//   { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are\n\t//       optional, they are enclosed in brackets ([ ]).\n\t// Example: add [-F file | -D dir]... [-f format] profile\n\tUse string\n\n\t// Aliases is an array of aliases that can be used instead of the first word in Use.\n\tAliases []string\n\n\t// SuggestFor is an array of command names for which this command will be suggested -\n\t// similar to aliases but only suggests.\n\tSuggestFor []string\n\n\t// Short is the short description shown in the 'help' output.\n\tShort string\n\n\t// The group id under which this subcommand is grouped in the 'help' output of its parent.\n\tGroupID string\n\n\t// Long is the long message shown in the 'help <this-command>' output.\n\tLong string\n\n\t// Example is examples of how to use the command.\n\tExample string\n\n\t// ValidArgs is list of all valid non-flag arguments that are accepted in shell completions\n\tValidArgs []Completion\n\t// ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion.\n\t// It is a dynamic version of using ValidArgs.\n\t// Only one of ValidArgs and ValidArgsFunction can be used for a command.\n\tValidArgsFunction CompletionFunc\n\n\t// Expected arguments\n\tArgs PositionalArgs\n\n\t// ArgAliases is List of aliases for ValidArgs.\n\t// These are not suggested to the user in the shell completion,\n\t// but accepted if entered manually.\n\tArgAliases []string\n\n\t// BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator.\n\t// For portability with other shells, it is recommended to instead use ValidArgsFunction\n\tBashCompletionFunction string\n\n\t// Deprecated defines, if this command is deprecated and should print this string when used.\n\tDeprecated string\n\n\t// Annotations are key/value pairs that can be used by applications to identify or\n\t// group commands or set special options.\n\tAnnotations map[string]string\n\n\t// Version defines the version for this command. If this value is non-empty and the command does not\n\t// define a \"version\" flag, a \"version\" boolean flag will be added to the command and, if specified,\n\t// will print content of the \"Version\" variable. A shorthand \"v\" flag will also be added if the\n\t// command does not define one.\n\tVersion string\n\n\t// The *Run functions are executed in the following order:\n\t//   * PersistentPreRun()\n\t//   * PreRun()\n\t//   * Run()\n\t//   * PostRun()\n\t//   * PersistentPostRun()\n\t// All functions get the same args, the arguments after the command name.\n\t// The *PreRun and *PostRun functions will only be executed if the Run function of the current\n\t// command has been declared.\n\t//\n\t// PersistentPreRun: children of this command will inherit and execute.\n\tPersistentPreRun func(cmd *Command, args []string)\n\t// PersistentPreRunE: PersistentPreRun but returns an error.\n\tPersistentPreRunE func(cmd *Command, args []string) error\n\t// PreRun: children of this command will not inherit.\n\tPreRun func(cmd *Command, args []string)\n\t// PreRunE: PreRun but returns an error.\n\tPreRunE func(cmd *Command, args []string) error\n\t// Run: Typically the actual work function. Most commands will only implement this.\n\tRun func(cmd *Command, args []string)\n\t// RunE: Run but returns an error.\n\tRunE func(cmd *Command, args []string) error\n\t// PostRun: run after the Run command.\n\tPostRun func(cmd *Command, args []string)\n\t// PostRunE: PostRun but returns an error.\n\tPostRunE func(cmd *Command, args []string) error\n\t// PersistentPostRun: children of this command will inherit and execute after PostRun.\n\tPersistentPostRun func(cmd *Command, args []string)\n\t// PersistentPostRunE: PersistentPostRun but returns an error.\n\tPersistentPostRunE func(cmd *Command, args []string) error\n\n\t// groups for subcommands\n\tcommandgroups []*Group\n\n\t// args is actual args parsed from flags.\n\targs []string\n\t// flagErrorBuf contains all error messages from pflag.\n\tflagErrorBuf *bytes.Buffer\n\t// flags is full set of flags.\n\tflags *flag.FlagSet\n\t// pflags contains persistent flags.\n\tpflags *flag.FlagSet\n\t// lflags contains local flags.\n\t// This field does not represent internal state, it's used as a cache to optimise LocalFlags function call\n\tlflags *flag.FlagSet\n\t// iflags contains inherited flags.\n\t// This field does not represent internal state, it's used as a cache to optimise InheritedFlags function call\n\tiflags *flag.FlagSet\n\t// parentsPflags is all persistent flags of cmd's parents.\n\tparentsPflags *flag.FlagSet\n\t// globNormFunc is the global normalization function\n\t// that we can use on every pflag set and children commands\n\tglobNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName\n\n\t// usageFunc is usage func defined by user.\n\tusageFunc func(*Command) error\n\t// usageTemplate is usage template defined by user.\n\tusageTemplate *tmplFunc\n\t// flagErrorFunc is func defined by user and it's called when the parsing of\n\t// flags returns an error.\n\tflagErrorFunc func(*Command, error) error\n\t// helpTemplate is help template defined by user.\n\thelpTemplate *tmplFunc\n\t// helpFunc is help func defined by user.\n\thelpFunc func(*Command, []string)\n\t// helpCommand is command with usage 'help'. If it's not defined by user,\n\t// cobra uses default help command.\n\thelpCommand *Command\n\t// helpCommandGroupID is the group id for the helpCommand\n\thelpCommandGroupID string\n\n\t// completionCommandGroupID is the group id for the completion command\n\tcompletionCommandGroupID string\n\n\t// versionTemplate is the version template defined by user.\n\tversionTemplate *tmplFunc\n\n\t// errPrefix is the error message prefix defined by user.\n\terrPrefix string\n\n\t// inReader is a reader defined by the user that replaces stdin\n\tinReader io.Reader\n\t// outWriter is a writer defined by the user that replaces stdout\n\toutWriter io.Writer\n\t// errWriter is a writer defined by the user that replaces stderr\n\terrWriter io.Writer\n\n\t// FParseErrWhitelist flag parse errors to be ignored\n\tFParseErrWhitelist FParseErrWhitelist\n\n\t// CompletionOptions is a set of options to control the handling of shell completion\n\tCompletionOptions CompletionOptions\n\n\t// commandsAreSorted defines, if command slice are sorted or not.\n\tcommandsAreSorted bool\n\t// commandCalledAs is the name or alias value used to call this command.\n\tcommandCalledAs struct {\n\t\tname   string\n\t\tcalled bool\n\t}\n\n\tctx context.Context\n\n\t// commands is the list of commands supported by this program.\n\tcommands []*Command\n\t// parent is a parent command for this command.\n\tparent *Command\n\t// Max lengths of commands' string lengths for use in padding.\n\tcommandsMaxUseLen         int\n\tcommandsMaxCommandPathLen int\n\tcommandsMaxNameLen        int\n\n\t// TraverseChildren parses flags on all parents before executing child command.\n\tTraverseChildren bool\n\n\t// Hidden defines, if this command is hidden and should NOT show up in the list of available commands.\n\tHidden bool\n\n\t// SilenceErrors is an option to quiet errors down stream.\n\tSilenceErrors bool\n\n\t// SilenceUsage is an option to silence usage when an error occurs.\n\tSilenceUsage bool\n\n\t// DisableFlagParsing disables the flag parsing.\n\t// If this is true all flags will be passed to the command as arguments.\n\tDisableFlagParsing bool\n\n\t// DisableAutoGenTag defines, if gen tag (\"Auto generated by spf13/cobra...\")\n\t// will be printed by generating docs for this command.\n\tDisableAutoGenTag bool\n\n\t// DisableFlagsInUseLine will disable the addition of [flags] to the usage\n\t// line of a command when printing help or generating docs\n\tDisableFlagsInUseLine bool\n\n\t// DisableSuggestions disables the suggestions based on Levenshtein distance\n\t// that go along with 'unknown command' messages.\n\tDisableSuggestions bool\n\n\t// SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.\n\t// Must be > 0.\n\tSuggestionsMinimumDistance int\n}\n\n// Context returns underlying command context. If command was executed\n// with ExecuteContext or the context was set with SetContext, the\n// previously set context will be returned. Otherwise, nil is returned.\n//\n// Notice that a call to Execute and ExecuteC will replace a nil context of\n// a command with a context.Background, so a background context will be\n// returned by Context after one of these functions has been called.\nfunc (c *Command) Context() context.Context {\n\treturn c.ctx\n}\n\n// SetContext sets context for the command. This context will be overwritten by\n// Command.ExecuteContext or Command.ExecuteContextC.\nfunc (c *Command) SetContext(ctx context.Context) {\n\tc.ctx = ctx\n}\n\n// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden\n// particularly useful when testing.\nfunc (c *Command) SetArgs(a []string) {\n\tc.args = a\n}\n\n// SetOutput sets the destination for usage and error messages.\n// If output is nil, os.Stderr is used.\n//\n// Deprecated: Use SetOut and/or SetErr instead\nfunc (c *Command) SetOutput(output io.Writer) {\n\tc.outWriter = output\n\tc.errWriter = output\n}\n\n// SetOut sets the destination for usage messages.\n// If newOut is nil, os.Stdout is used.\nfunc (c *Command) SetOut(newOut io.Writer) {\n\tc.outWriter = newOut\n}\n\n// SetErr sets the destination for error messages.\n// If newErr is nil, os.Stderr is used.\nfunc (c *Command) SetErr(newErr io.Writer) {\n\tc.errWriter = newErr\n}\n\n// SetIn sets the source for input data\n// If newIn is nil, os.Stdin is used.\nfunc (c *Command) SetIn(newIn io.Reader) {\n\tc.inReader = newIn\n}\n\n// SetUsageFunc sets usage function. Usage can be defined by application.\nfunc (c *Command) SetUsageFunc(f func(*Command) error) {\n\tc.usageFunc = f\n}\n\n// SetUsageTemplate sets usage template. Can be defined by Application.\nfunc (c *Command) SetUsageTemplate(s string) {\n\tif s == \"\" {\n\t\tc.usageTemplate = nil\n\t\treturn\n\t}\n\tc.usageTemplate = tmpl(s)\n}\n\n// SetFlagErrorFunc sets a function to generate an error when flag parsing\n// fails.\nfunc (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {\n\tc.flagErrorFunc = f\n}\n\n// SetHelpFunc sets help function. Can be defined by Application.\nfunc (c *Command) SetHelpFunc(f func(*Command, []string)) {\n\tc.helpFunc = f\n}\n\n// SetHelpCommand sets help command.\nfunc (c *Command) SetHelpCommand(cmd *Command) {\n\tc.helpCommand = cmd\n}\n\n// SetHelpCommandGroupID sets the group id of the help command.\nfunc (c *Command) SetHelpCommandGroupID(groupID string) {\n\tif c.helpCommand != nil {\n\t\tc.helpCommand.GroupID = groupID\n\t}\n\t// helpCommandGroupID is used if no helpCommand is defined by the user\n\tc.helpCommandGroupID = groupID\n}\n\n// SetCompletionCommandGroupID sets the group id of the completion command.\nfunc (c *Command) SetCompletionCommandGroupID(groupID string) {\n\t// completionCommandGroupID is used if no completion command is defined by the user\n\tc.Root().completionCommandGroupID = groupID\n}\n\n// SetHelpTemplate sets help template to be used. Application can use it to set custom template.\nfunc (c *Command) SetHelpTemplate(s string) {\n\tif s == \"\" {\n\t\tc.helpTemplate = nil\n\t\treturn\n\t}\n\tc.helpTemplate = tmpl(s)\n}\n\n// SetVersionTemplate sets version template to be used. Application can use it to set custom template.\nfunc (c *Command) SetVersionTemplate(s string) {\n\tif s == \"\" {\n\t\tc.versionTemplate = nil\n\t\treturn\n\t}\n\tc.versionTemplate = tmpl(s)\n}\n\n// SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix.\nfunc (c *Command) SetErrPrefix(s string) {\n\tc.errPrefix = s\n}\n\n// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.\n// The user should not have a cyclic dependency on commands.\nfunc (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {\n\tc.Flags().SetNormalizeFunc(n)\n\tc.PersistentFlags().SetNormalizeFunc(n)\n\tc.globNormFunc = n\n\n\tfor _, command := range c.commands {\n\t\tcommand.SetGlobalNormalizationFunc(n)\n\t}\n}\n\n// OutOrStdout returns output to stdout.\nfunc (c *Command) OutOrStdout() io.Writer {\n\treturn c.getOut(os.Stdout)\n}\n\n// OutOrStderr returns output to stderr\nfunc (c *Command) OutOrStderr() io.Writer {\n\treturn c.getOut(os.Stderr)\n}\n\n// ErrOrStderr returns output to stderr\nfunc (c *Command) ErrOrStderr() io.Writer {\n\treturn c.getErr(os.Stderr)\n}\n\n// InOrStdin returns input to stdin\nfunc (c *Command) InOrStdin() io.Reader {\n\treturn c.getIn(os.Stdin)\n}\n\nfunc (c *Command) getOut(def io.Writer) io.Writer {\n\tif c.outWriter != nil {\n\t\treturn c.outWriter\n\t}\n\tif c.HasParent() {\n\t\treturn c.parent.getOut(def)\n\t}\n\treturn def\n}\n\nfunc (c *Command) getErr(def io.Writer) io.Writer {\n\tif c.errWriter != nil {\n\t\treturn c.errWriter\n\t}\n\tif c.HasParent() {\n\t\treturn c.parent.getErr(def)\n\t}\n\treturn def\n}\n\nfunc (c *Command) getIn(def io.Reader) io.Reader {\n\tif c.inReader != nil {\n\t\treturn c.inReader\n\t}\n\tif c.HasParent() {\n\t\treturn c.parent.getIn(def)\n\t}\n\treturn def\n}\n\n// UsageFunc returns either the function set by SetUsageFunc for this command\n// or a parent, or it returns a default usage function.\nfunc (c *Command) UsageFunc() (f func(*Command) error) {\n\tif c.usageFunc != nil {\n\t\treturn c.usageFunc\n\t}\n\tif c.HasParent() {\n\t\treturn c.Parent().UsageFunc()\n\t}\n\treturn func(c *Command) error {\n\t\tc.mergePersistentFlags()\n\t\tfn := c.getUsageTemplateFunc()\n\t\terr := fn(c.OutOrStderr(), c)\n\t\tif err != nil {\n\t\t\tc.PrintErrln(err)\n\t\t}\n\t\treturn err\n\t}\n}\n\n// getUsageTemplateFunc returns the usage template function for the command\n// going up the command tree if necessary.\nfunc (c *Command) getUsageTemplateFunc() func(w io.Writer, data interface{}) error {\n\tif c.usageTemplate != nil {\n\t\treturn c.usageTemplate.fn\n\t}\n\n\tif c.HasParent() {\n\t\treturn c.parent.getUsageTemplateFunc()\n\t}\n\treturn defaultUsageFunc\n}\n\n// Usage puts out the usage for the command.\n// Used when a user provides invalid input.\n// Can be defined by user by overriding UsageFunc.\nfunc (c *Command) Usage() error {\n\treturn c.UsageFunc()(c)\n}\n\n// HelpFunc returns either the function set by SetHelpFunc for this command\n// or a parent, or it returns a function with default help behavior.\nfunc (c *Command) HelpFunc() func(*Command, []string) {\n\tif c.helpFunc != nil {\n\t\treturn c.helpFunc\n\t}\n\tif c.HasParent() {\n\t\treturn c.Parent().HelpFunc()\n\t}\n\treturn func(c *Command, a []string) {\n\t\tc.mergePersistentFlags()\n\t\tfn := c.getHelpTemplateFunc()\n\t\t// The help should be sent to stdout\n\t\t// See https://github.com/spf13/cobra/issues/1002\n\t\terr := fn(c.OutOrStdout(), c)\n\t\tif err != nil {\n\t\t\tc.PrintErrln(err)\n\t\t}\n\t}\n}\n\n// getHelpTemplateFunc returns the help template function for the command\n// going up the command tree if necessary.\nfunc (c *Command) getHelpTemplateFunc() func(w io.Writer, data interface{}) error {\n\tif c.helpTemplate != nil {\n\t\treturn c.helpTemplate.fn\n\t}\n\n\tif c.HasParent() {\n\t\treturn c.parent.getHelpTemplateFunc()\n\t}\n\n\treturn defaultHelpFunc\n}\n\n// Help puts out the help for the command.\n// Used when a user calls help [command].\n// Can be defined by user by overriding HelpFunc.\nfunc (c *Command) Help() error {\n\tc.HelpFunc()(c, []string{})\n\treturn nil\n}\n\n// UsageString returns usage string.\nfunc (c *Command) UsageString() string {\n\t// Storing normal writers\n\ttmpOutput := c.outWriter\n\ttmpErr := c.errWriter\n\n\tbb := new(bytes.Buffer)\n\tc.outWriter = bb\n\tc.errWriter = bb\n\n\tCheckErr(c.Usage())\n\n\t// Setting things back to normal\n\tc.outWriter = tmpOutput\n\tc.errWriter = tmpErr\n\n\treturn bb.String()\n}\n\n// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this\n// command or a parent, or it returns a function which returns the original\n// error.\nfunc (c *Command) FlagErrorFunc() (f func(*Command, error) error) {\n\tif c.flagErrorFunc != nil {\n\t\treturn c.flagErrorFunc\n\t}\n\n\tif c.HasParent() {\n\t\treturn c.parent.FlagErrorFunc()\n\t}\n\treturn func(c *Command, err error) error {\n\t\treturn err\n\t}\n}\n\nconst minUsagePadding = 25\n\n// UsagePadding return padding for the usage.\nfunc (c *Command) UsagePadding() int {\n\tif c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {\n\t\treturn minUsagePadding\n\t}\n\treturn c.parent.commandsMaxUseLen\n}\n\nconst minCommandPathPadding = 11\n\n// CommandPathPadding return padding for the command path.\nfunc (c *Command) CommandPathPadding() int {\n\tif c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {\n\t\treturn minCommandPathPadding\n\t}\n\treturn c.parent.commandsMaxCommandPathLen\n}\n\nconst minNamePadding = 11\n\n// NamePadding returns padding for the name.\nfunc (c *Command) NamePadding() int {\n\tif c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {\n\t\treturn minNamePadding\n\t}\n\treturn c.parent.commandsMaxNameLen\n}\n\n// UsageTemplate returns usage template for the command.\n// This function is kept for backwards-compatibility reasons.\nfunc (c *Command) UsageTemplate() string {\n\tif c.usageTemplate != nil {\n\t\treturn c.usageTemplate.tmpl\n\t}\n\n\tif c.HasParent() {\n\t\treturn c.parent.UsageTemplate()\n\t}\n\treturn defaultUsageTemplate\n}\n\n// HelpTemplate return help template for the command.\n// This function is kept for backwards-compatibility reasons.\nfunc (c *Command) HelpTemplate() string {\n\tif c.helpTemplate != nil {\n\t\treturn c.helpTemplate.tmpl\n\t}\n\n\tif c.HasParent() {\n\t\treturn c.parent.HelpTemplate()\n\t}\n\treturn defaultHelpTemplate\n}\n\n// VersionTemplate return version template for the command.\n// This function is kept for backwards-compatibility reasons.\nfunc (c *Command) VersionTemplate() string {\n\tif c.versionTemplate != nil {\n\t\treturn c.versionTemplate.tmpl\n\t}\n\n\tif c.HasParent() {\n\t\treturn c.parent.VersionTemplate()\n\t}\n\treturn defaultVersionTemplate\n}\n\n// getVersionTemplateFunc returns the version template function for the command\n// going up the command tree if necessary.\nfunc (c *Command) getVersionTemplateFunc() func(w io.Writer, data interface{}) error {\n\tif c.versionTemplate != nil {\n\t\treturn c.versionTemplate.fn\n\t}\n\n\tif c.HasParent() {\n\t\treturn c.parent.getVersionTemplateFunc()\n\t}\n\treturn defaultVersionFunc\n}\n\n// ErrPrefix return error message prefix for the command\nfunc (c *Command) ErrPrefix() string {\n\tif c.errPrefix != \"\" {\n\t\treturn c.errPrefix\n\t}\n\n\tif c.HasParent() {\n\t\treturn c.parent.ErrPrefix()\n\t}\n\treturn \"Error:\"\n}\n\nfunc hasNoOptDefVal(name string, fs *flag.FlagSet) bool {\n\tflag := fs.Lookup(name)\n\tif flag == nil {\n\t\treturn false\n\t}\n\treturn flag.NoOptDefVal != \"\"\n}\n\nfunc shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {\n\tif len(name) == 0 {\n\t\treturn false\n\t}\n\n\tflag := fs.ShorthandLookup(name[:1])\n\tif flag == nil {\n\t\treturn false\n\t}\n\treturn flag.NoOptDefVal != \"\"\n}\n\nfunc stripFlags(args []string, c *Command) []string {\n\tif len(args) == 0 {\n\t\treturn args\n\t}\n\tc.mergePersistentFlags()\n\n\tcommands := []string{}\n\tflags := c.Flags()\n\nLoop:\n\tfor len(args) > 0 {\n\t\ts := args[0]\n\t\targs = args[1:]\n\t\tswitch {\n\t\tcase s == \"--\":\n\t\t\t// \"--\" terminates the flags\n\t\t\tbreak Loop\n\t\tcase strings.HasPrefix(s, \"--\") && !strings.Contains(s, \"=\") && !hasNoOptDefVal(s[2:], flags):\n\t\t\t// If '--flag arg' then\n\t\t\t// delete arg from args.\n\t\t\tfallthrough // (do the same as below)\n\t\tcase strings.HasPrefix(s, \"-\") && !strings.Contains(s, \"=\") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):\n\t\t\t// If '-f arg' then\n\t\t\t// delete 'arg' from args or break the loop if len(args) <= 1.\n\t\t\tif len(args) <= 1 {\n\t\t\t\tbreak Loop\n\t\t\t} else {\n\t\t\t\targs = args[1:]\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase s != \"\" && !strings.HasPrefix(s, \"-\"):\n\t\t\tcommands = append(commands, s)\n\t\t}\n\t}\n\n\treturn commands\n}\n\n// argsMinusFirstX removes only the first x from args.  Otherwise, commands that look like\n// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).\n// Special care needs to be taken not to remove a flag value.\nfunc (c *Command) argsMinusFirstX(args []string, x string) []string {\n\tif len(args) == 0 {\n\t\treturn args\n\t}\n\tc.mergePersistentFlags()\n\tflags := c.Flags()\n\nLoop:\n\tfor pos := 0; pos < len(args); pos++ {\n\t\ts := args[pos]\n\t\tswitch {\n\t\tcase s == \"--\":\n\t\t\t// -- means we have reached the end of the parseable args. Break out of the loop now.\n\t\t\tbreak Loop\n\t\tcase strings.HasPrefix(s, \"--\") && !strings.Contains(s, \"=\") && !hasNoOptDefVal(s[2:], flags):\n\t\t\tfallthrough\n\t\tcase strings.HasPrefix(s, \"-\") && !strings.Contains(s, \"=\") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):\n\t\t\t// This is a flag without a default value, and an equal sign is not used. Increment pos in order to skip\n\t\t\t// over the next arg, because that is the value of this flag.\n\t\t\tpos++\n\t\t\tcontinue\n\t\tcase !strings.HasPrefix(s, \"-\"):\n\t\t\t// This is not a flag or a flag value. Check to see if it matches what we're looking for, and if so,\n\t\t\t// return the args, excluding the one at this position.\n\t\t\tif s == x {\n\t\t\t\tret := make([]string, 0, len(args)-1)\n\t\t\t\tret = append(ret, args[:pos]...)\n\t\t\t\tret = append(ret, args[pos+1:]...)\n\t\t\t\treturn ret\n\t\t\t}\n\t\t}\n\t}\n\treturn args\n}\n\nfunc isFlagArg(arg string) bool {\n\treturn ((len(arg) >= 3 && arg[0:2] == \"--\") ||\n\t\t(len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))\n}\n\n// Find the target command given the args and command tree\n// Meant to be run on the highest node. Only searches down.\nfunc (c *Command) Find(args []string) (*Command, []string, error) {\n\tvar innerfind func(*Command, []string) (*Command, []string)\n\n\tinnerfind = func(c *Command, innerArgs []string) (*Command, []string) {\n\t\targsWOflags := stripFlags(innerArgs, c)\n\t\tif len(argsWOflags) == 0 {\n\t\t\treturn c, innerArgs\n\t\t}\n\t\tnextSubCmd := argsWOflags[0]\n\n\t\tcmd := c.findNext(nextSubCmd)\n\t\tif cmd != nil {\n\t\t\treturn innerfind(cmd, c.argsMinusFirstX(innerArgs, nextSubCmd))\n\t\t}\n\t\treturn c, innerArgs\n\t}\n\n\tcommandFound, a := innerfind(c, args)\n\tif commandFound.Args == nil {\n\t\treturn commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))\n\t}\n\treturn commandFound, a, nil\n}\n\nfunc (c *Command) findSuggestions(arg string) string {\n\tif c.DisableSuggestions {\n\t\treturn \"\"\n\t}\n\tif c.SuggestionsMinimumDistance <= 0 {\n\t\tc.SuggestionsMinimumDistance = 2\n\t}\n\tvar sb strings.Builder\n\tif suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {\n\t\tsb.WriteString(\"\\n\\nDid you mean this?\\n\")\n\t\tfor _, s := range suggestions {\n\t\t\t_, _ = fmt.Fprintf(&sb, \"\\t%v\\n\", s)\n\t\t}\n\t}\n\treturn sb.String()\n}\n\nfunc (c *Command) findNext(next string) *Command {\n\tmatches := make([]*Command, 0)\n\tfor _, cmd := range c.commands {\n\t\tif commandNameMatches(cmd.Name(), next) || cmd.HasAlias(next) {\n\t\t\tcmd.commandCalledAs.name = next\n\t\t\treturn cmd\n\t\t}\n\t\tif EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {\n\t\t\tmatches = append(matches, cmd)\n\t\t}\n\t}\n\n\tif len(matches) == 1 {\n\t\t// Temporarily disable gosec G602, which produces a false positive.\n\t\t// See https://github.com/securego/gosec/issues/1005.\n\t\treturn matches[0] // #nosec G602\n\t}\n\n\treturn nil\n}\n\n// Traverse the command tree to find the command, and parse args for\n// each parent.\nfunc (c *Command) Traverse(args []string) (*Command, []string, error) {\n\tflags := []string{}\n\tinFlag := false\n\n\tfor i, arg := range args {\n\t\tswitch {\n\t\t// A long flag with a space separated value\n\t\tcase strings.HasPrefix(arg, \"--\") && !strings.Contains(arg, \"=\"):\n\t\t\t// TODO: this isn't quite right, we should really check ahead for 'true' or 'false'\n\t\t\tinFlag = !hasNoOptDefVal(arg[2:], c.Flags())\n\t\t\tflags = append(flags, arg)\n\t\t\tcontinue\n\t\t// A short flag with a space separated value\n\t\tcase strings.HasPrefix(arg, \"-\") && !strings.Contains(arg, \"=\") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):\n\t\t\tinFlag = true\n\t\t\tflags = append(flags, arg)\n\t\t\tcontinue\n\t\t// The value for a flag\n\t\tcase inFlag:\n\t\t\tinFlag = false\n\t\t\tflags = append(flags, arg)\n\t\t\tcontinue\n\t\t// A flag without a value, or with an `=` separated value\n\t\tcase isFlagArg(arg):\n\t\t\tflags = append(flags, arg)\n\t\t\tcontinue\n\t\t}\n\n\t\tcmd := c.findNext(arg)\n\t\tif cmd == nil {\n\t\t\treturn c, args, nil\n\t\t}\n\n\t\tif err := c.ParseFlags(flags); err != nil {\n\t\t\treturn nil, args, err\n\t\t}\n\t\treturn cmd.Traverse(args[i+1:])\n\t}\n\treturn c, args, nil\n}\n\n// SuggestionsFor provides suggestions for the typedName.\nfunc (c *Command) SuggestionsFor(typedName string) []string {\n\tsuggestions := []string{}\n\tfor _, cmd := range c.commands {\n\t\tif cmd.IsAvailableCommand() {\n\t\t\tlevenshteinDistance := ld(typedName, cmd.Name(), true)\n\t\t\tsuggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance\n\t\t\tsuggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))\n\t\t\tif suggestByLevenshtein || suggestByPrefix {\n\t\t\t\tsuggestions = append(suggestions, cmd.Name())\n\t\t\t}\n\t\t\tfor _, explicitSuggestion := range cmd.SuggestFor {\n\t\t\t\tif strings.EqualFold(typedName, explicitSuggestion) {\n\t\t\t\t\tsuggestions = append(suggestions, cmd.Name())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn suggestions\n}\n\n// VisitParents visits all parents of the command and invokes fn on each parent.\nfunc (c *Command) VisitParents(fn func(*Command)) {\n\tif c.HasParent() {\n\t\tfn(c.Parent())\n\t\tc.Parent().VisitParents(fn)\n\t}\n}\n\n// Root finds root command.\nfunc (c *Command) Root() *Command {\n\tif c.HasParent() {\n\t\treturn c.Parent().Root()\n\t}\n\treturn c\n}\n\n// ArgsLenAtDash will return the length of c.Flags().Args at the moment\n// when a -- was found during args parsing.\nfunc (c *Command) ArgsLenAtDash() int {\n\treturn c.Flags().ArgsLenAtDash()\n}\n\nfunc (c *Command) execute(a []string) (err error) {\n\tif c == nil {\n\t\treturn fmt.Errorf(\"called Execute() on a nil Command\")\n\t}\n\n\tif len(c.Deprecated) > 0 {\n\t\tc.Printf(\"Command %q is deprecated, %s\\n\", c.Name(), c.Deprecated)\n\t}\n\n\t// initialize help and version flag at the last point possible to allow for user\n\t// overriding\n\tc.InitDefaultHelpFlag()\n\tc.InitDefaultVersionFlag()\n\n\terr = c.ParseFlags(a)\n\tif err != nil {\n\t\treturn c.FlagErrorFunc()(c, err)\n\t}\n\n\t// If help is called, regardless of other flags, return we want help.\n\t// Also say we need help if the command isn't runnable.\n\thelpVal, err := c.Flags().GetBool(helpFlagName)\n\tif err != nil {\n\t\t// should be impossible to get here as we always declare a help\n\t\t// flag in InitDefaultHelpFlag()\n\t\tc.Println(\"\\\"help\\\" flag declared as non-bool. Please correct your code\")\n\t\treturn err\n\t}\n\n\tif helpVal {\n\t\treturn flag.ErrHelp\n\t}\n\n\t// for back-compat, only add version flag behavior if version is defined\n\tif c.Version != \"\" {\n\t\tversionVal, err := c.Flags().GetBool(\"version\")\n\t\tif err != nil {\n\t\t\tc.Println(\"\\\"version\\\" flag declared as non-bool. Please correct your code\")\n\t\t\treturn err\n\t\t}\n\t\tif versionVal {\n\t\t\tfn := c.getVersionTemplateFunc()\n\t\t\terr := fn(c.OutOrStdout(), c)\n\t\t\tif err != nil {\n\t\t\t\tc.Println(err)\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !c.Runnable() {\n\t\treturn flag.ErrHelp\n\t}\n\n\tc.preRun()\n\n\tdefer c.postRun()\n\n\targWoFlags := c.Flags().Args()\n\tif c.DisableFlagParsing {\n\t\targWoFlags = a\n\t}\n\n\tif err := c.ValidateArgs(argWoFlags); err != nil {\n\t\treturn err\n\t}\n\n\tparents := make([]*Command, 0, 5)\n\tfor p := c; p != nil; p = p.Parent() {\n\t\tif EnableTraverseRunHooks {\n\t\t\t// When EnableTraverseRunHooks is set:\n\t\t\t// - Execute all persistent pre-runs from the root parent till this command.\n\t\t\t// - Execute all persistent post-runs from this command till the root parent.\n\t\t\tparents = append([]*Command{p}, parents...)\n\t\t} else {\n\t\t\t// Otherwise, execute only the first found persistent hook.\n\t\t\tparents = append(parents, p)\n\t\t}\n\t}\n\tfor _, p := range parents {\n\t\tif p.PersistentPreRunE != nil {\n\t\t\tif err := p.PersistentPreRunE(c, argWoFlags); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !EnableTraverseRunHooks {\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else if p.PersistentPreRun != nil {\n\t\t\tp.PersistentPreRun(c, argWoFlags)\n\t\t\tif !EnableTraverseRunHooks {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif c.PreRunE != nil {\n\t\tif err := c.PreRunE(c, argWoFlags); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else if c.PreRun != nil {\n\t\tc.PreRun(c, argWoFlags)\n\t}\n\n\tif err := c.ValidateRequiredFlags(); err != nil {\n\t\treturn err\n\t}\n\tif err := c.ValidateFlagGroups(); err != nil {\n\t\treturn err\n\t}\n\n\tif c.RunE != nil {\n\t\tif err := c.RunE(c, argWoFlags); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tc.Run(c, argWoFlags)\n\t}\n\tif c.PostRunE != nil {\n\t\tif err := c.PostRunE(c, argWoFlags); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else if c.PostRun != nil {\n\t\tc.PostRun(c, argWoFlags)\n\t}\n\tfor p := c; p != nil; p = p.Parent() {\n\t\tif p.PersistentPostRunE != nil {\n\t\t\tif err := p.PersistentPostRunE(c, argWoFlags); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !EnableTraverseRunHooks {\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else if p.PersistentPostRun != nil {\n\t\t\tp.PersistentPostRun(c, argWoFlags)\n\t\t\tif !EnableTraverseRunHooks {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c *Command) preRun() {\n\tfor _, x := range initializers {\n\t\tx()\n\t}\n}\n\nfunc (c *Command) postRun() {\n\tfor _, x := range finalizers {\n\t\tx()\n\t}\n}\n\n// ExecuteContext is the same as Execute(), but sets the ctx on the command.\n// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs\n// functions.\nfunc (c *Command) ExecuteContext(ctx context.Context) error {\n\tc.ctx = ctx\n\treturn c.Execute()\n}\n\n// Execute uses the args (os.Args[1:] by default)\n// and run through the command tree finding appropriate matches\n// for commands and then corresponding flags.\nfunc (c *Command) Execute() error {\n\t_, err := c.ExecuteC()\n\treturn err\n}\n\n// ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command.\n// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs\n// functions.\nfunc (c *Command) ExecuteContextC(ctx context.Context) (*Command, error) {\n\tc.ctx = ctx\n\treturn c.ExecuteC()\n}\n\n// ExecuteC executes the command.\nfunc (c *Command) ExecuteC() (cmd *Command, err error) {\n\tif c.ctx == nil {\n\t\tc.ctx = context.Background()\n\t}\n\n\t// Regardless of what command execute is called on, run on Root only\n\tif c.HasParent() {\n\t\treturn c.Root().ExecuteC()\n\t}\n\n\t// windows hook\n\tif preExecHookFn != nil {\n\t\tpreExecHookFn(c)\n\t}\n\n\t// initialize help at the last point to allow for user overriding\n\tc.InitDefaultHelpCmd()\n\n\targs := c.args\n\n\t// Workaround FAIL with \"go test -v\" or \"cobra.test -test.v\", see #155\n\tif c.args == nil && filepath.Base(os.Args[0]) != \"cobra.test\" {\n\t\targs = os.Args[1:]\n\t}\n\n\t// initialize the __complete command to be used for shell completion\n\tc.initCompleteCmd(args)\n\n\t// initialize the default completion command\n\tc.InitDefaultCompletionCmd(args...)\n\n\t// Now that all commands have been created, let's make sure all groups\n\t// are properly created also\n\tc.checkCommandGroups()\n\n\tvar flags []string\n\tif c.TraverseChildren {\n\t\tcmd, flags, err = c.Traverse(args)\n\t} else {\n\t\tcmd, flags, err = c.Find(args)\n\t}\n\tif err != nil {\n\t\t// If found parse to a subcommand and then failed, talk about the subcommand\n\t\tif cmd != nil {\n\t\t\tc = cmd\n\t\t}\n\t\tif !c.SilenceErrors {\n\t\t\tc.PrintErrln(c.ErrPrefix(), err.Error())\n\t\t\tc.PrintErrf(\"Run '%v --help' for usage.\\n\", c.CommandPath())\n\t\t}\n\t\treturn c, err\n\t}\n\n\tcmd.commandCalledAs.called = true\n\tif cmd.commandCalledAs.name == \"\" {\n\t\tcmd.commandCalledAs.name = cmd.Name()\n\t}\n\n\t// We have to pass global context to children command\n\t// if context is present on the parent command.\n\tif cmd.ctx == nil {\n\t\tcmd.ctx = c.ctx\n\t}\n\n\terr = cmd.execute(flags)\n\tif err != nil {\n\t\t// Always show help if requested, even if SilenceErrors is in\n\t\t// effect\n\t\tif errors.Is(err, flag.ErrHelp) {\n\t\t\tcmd.HelpFunc()(cmd, args)\n\t\t\treturn cmd, nil\n\t\t}\n\n\t\t// If root command has SilenceErrors flagged,\n\t\t// all subcommands should respect it\n\t\tif !cmd.SilenceErrors && !c.SilenceErrors {\n\t\t\tc.PrintErrln(cmd.ErrPrefix(), err.Error())\n\t\t}\n\n\t\t// If root command has SilenceUsage flagged,\n\t\t// all subcommands should respect it\n\t\tif !cmd.SilenceUsage && !c.SilenceUsage {\n\t\t\tc.Println(cmd.UsageString())\n\t\t}\n\t}\n\treturn cmd, err\n}\n\nfunc (c *Command) ValidateArgs(args []string) error {\n\tif c.Args == nil {\n\t\treturn ArbitraryArgs(c, args)\n\t}\n\treturn c.Args(c, args)\n}\n\n// ValidateRequiredFlags validates all required flags are present and returns an error otherwise\nfunc (c *Command) ValidateRequiredFlags() error {\n\tif c.DisableFlagParsing {\n\t\treturn nil\n\t}\n\n\tflags := c.Flags()\n\tmissingFlagNames := []string{}\n\tflags.VisitAll(func(pflag *flag.Flag) {\n\t\trequiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]\n\t\tif !found {\n\t\t\treturn\n\t\t}\n\t\tif (requiredAnnotation[0] == \"true\") && !pflag.Changed {\n\t\t\tmissingFlagNames = append(missingFlagNames, pflag.Name)\n\t\t}\n\t})\n\n\tif len(missingFlagNames) > 0 {\n\t\treturn fmt.Errorf(`required flag(s) \"%s\" not set`, strings.Join(missingFlagNames, `\", \"`))\n\t}\n\treturn nil\n}\n\n// checkCommandGroups checks if a command has been added to a group that does not exists.\n// If so, we panic because it indicates a coding error that should be corrected.\nfunc (c *Command) checkCommandGroups() {\n\tfor _, sub := range c.commands {\n\t\t// if Group is not defined let the developer know right away\n\t\tif sub.GroupID != \"\" && !c.ContainsGroup(sub.GroupID) {\n\t\t\tpanic(fmt.Sprintf(\"group id '%s' is not defined for subcommand '%s'\", sub.GroupID, sub.CommandPath()))\n\t\t}\n\n\t\tsub.checkCommandGroups()\n\t}\n}\n\n// InitDefaultHelpFlag adds default help flag to c.\n// It is called automatically by executing the c or by calling help and usage.\n// If c already has help flag, it will do nothing.\nfunc (c *Command) InitDefaultHelpFlag() {\n\tc.mergePersistentFlags()\n\tif c.Flags().Lookup(helpFlagName) == nil {\n\t\tusage := \"help for \"\n\t\tname := c.DisplayName()\n\t\tif name == \"\" {\n\t\t\tusage += \"this command\"\n\t\t} else {\n\t\t\tusage += name\n\t\t}\n\t\tc.Flags().BoolP(helpFlagName, \"h\", false, usage)\n\t\t_ = c.Flags().SetAnnotation(helpFlagName, FlagSetByCobraAnnotation, []string{\"true\"})\n\t}\n}\n\n// InitDefaultVersionFlag adds default version flag to c.\n// It is called automatically by executing the c.\n// If c already has a version flag, it will do nothing.\n// If c.Version is empty, it will do nothing.\nfunc (c *Command) InitDefaultVersionFlag() {\n\tif c.Version == \"\" {\n\t\treturn\n\t}\n\n\tc.mergePersistentFlags()\n\tif c.Flags().Lookup(\"version\") == nil {\n\t\tusage := \"version for \"\n\t\tif c.Name() == \"\" {\n\t\t\tusage += \"this command\"\n\t\t} else {\n\t\t\tusage += c.DisplayName()\n\t\t}\n\t\tif c.Flags().ShorthandLookup(\"v\") == nil {\n\t\t\tc.Flags().BoolP(\"version\", \"v\", false, usage)\n\t\t} else {\n\t\t\tc.Flags().Bool(\"version\", false, usage)\n\t\t}\n\t\t_ = c.Flags().SetAnnotation(\"version\", FlagSetByCobraAnnotation, []string{\"true\"})\n\t}\n}\n\n// InitDefaultHelpCmd adds default help command to c.\n// It is called automatically by executing the c or by calling help and usage.\n// If c already has help command or c has no subcommands, it will do nothing.\nfunc (c *Command) InitDefaultHelpCmd() {\n\tif !c.HasSubCommands() {\n\t\treturn\n\t}\n\n\tif c.helpCommand == nil {\n\t\tc.helpCommand = &Command{\n\t\t\tUse:   \"help [command]\",\n\t\t\tShort: \"Help about any command\",\n\t\t\tLong: `Help provides help for any command in the application.\nSimply type ` + c.DisplayName() + ` help [path to command] for full details.`,\n\t\t\tValidArgsFunction: func(c *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) {\n\t\t\t\tvar completions []Completion\n\t\t\t\tcmd, _, e := c.Root().Find(args)\n\t\t\t\tif e != nil {\n\t\t\t\t\treturn nil, ShellCompDirectiveNoFileComp\n\t\t\t\t}\n\t\t\t\tif cmd == nil {\n\t\t\t\t\t// Root help command.\n\t\t\t\t\tcmd = c.Root()\n\t\t\t\t}\n\t\t\t\tfor _, subCmd := range cmd.Commands() {\n\t\t\t\t\tif subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand {\n\t\t\t\t\t\tif strings.HasPrefix(subCmd.Name(), toComplete) {\n\t\t\t\t\t\t\tcompletions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn completions, ShellCompDirectiveNoFileComp\n\t\t\t},\n\t\t\tRun: func(c *Command, args []string) {\n\t\t\t\tcmd, _, e := c.Root().Find(args)\n\t\t\t\tif cmd == nil || e != nil {\n\t\t\t\t\tc.Printf(\"Unknown help topic %#q\\n\", args)\n\t\t\t\t\tCheckErr(c.Root().Usage())\n\t\t\t\t} else {\n\t\t\t\t\t// FLow the context down to be used in help text\n\t\t\t\t\tif cmd.ctx == nil {\n\t\t\t\t\t\tcmd.ctx = c.ctx\n\t\t\t\t\t}\n\n\t\t\t\t\tcmd.InitDefaultHelpFlag()    // make possible 'help' flag to be shown\n\t\t\t\t\tcmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown\n\t\t\t\t\tCheckErr(cmd.Help())\n\t\t\t\t}\n\t\t\t},\n\t\t\tGroupID: c.helpCommandGroupID,\n\t\t}\n\t}\n\tc.RemoveCommand(c.helpCommand)\n\tc.AddCommand(c.helpCommand)\n}\n\n// ResetCommands delete parent, subcommand and help command from c.\nfunc (c *Command) ResetCommands() {\n\tc.parent = nil\n\tc.commands = nil\n\tc.helpCommand = nil\n\tc.parentsPflags = nil\n}\n\n// Sorts commands by their names.\ntype commandSorterByName []*Command\n\nfunc (c commandSorterByName) Len() int           { return len(c) }\nfunc (c commandSorterByName) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }\nfunc (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }\n\n// Commands returns a sorted slice of child commands.\nfunc (c *Command) Commands() []*Command {\n\t// do not sort commands if it already sorted or sorting was disabled\n\tif EnableCommandSorting && !c.commandsAreSorted {\n\t\tsort.Sort(commandSorterByName(c.commands))\n\t\tc.commandsAreSorted = true\n\t}\n\treturn c.commands\n}\n\n// AddCommand adds one or more commands to this parent command.\nfunc (c *Command) AddCommand(cmds ...*Command) {\n\tfor i, x := range cmds {\n\t\tif cmds[i] == c {\n\t\t\tpanic(\"Command can't be a child of itself\")\n\t\t}\n\t\tcmds[i].parent = c\n\t\t// update max lengths\n\t\tusageLen := len(x.Use)\n\t\tif usageLen > c.commandsMaxUseLen {\n\t\t\tc.commandsMaxUseLen = usageLen\n\t\t}\n\t\tcommandPathLen := len(x.CommandPath())\n\t\tif commandPathLen > c.commandsMaxCommandPathLen {\n\t\t\tc.commandsMaxCommandPathLen = commandPathLen\n\t\t}\n\t\tnameLen := len(x.Name())\n\t\tif nameLen > c.commandsMaxNameLen {\n\t\t\tc.commandsMaxNameLen = nameLen\n\t\t}\n\t\t// If global normalization function exists, update all children\n\t\tif c.globNormFunc != nil {\n\t\t\tx.SetGlobalNormalizationFunc(c.globNormFunc)\n\t\t}\n\t\tc.commands = append(c.commands, x)\n\t\tc.commandsAreSorted = false\n\t}\n}\n\n// Groups returns a slice of child command groups.\nfunc (c *Command) Groups() []*Group {\n\treturn c.commandgroups\n}\n\n// AllChildCommandsHaveGroup returns if all subcommands are assigned to a group\nfunc (c *Command) AllChildCommandsHaveGroup() bool {\n\tfor _, sub := range c.commands {\n\t\tif (sub.IsAvailableCommand() || sub == c.helpCommand) && sub.GroupID == \"\" {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// ContainsGroup return if groupID exists in the list of command groups.\nfunc (c *Command) ContainsGroup(groupID string) bool {\n\tfor _, x := range c.commandgroups {\n\t\tif x.ID == groupID {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// AddGroup adds one or more command groups to this parent command.\nfunc (c *Command) AddGroup(groups ...*Group) {\n\tc.commandgroups = append(c.commandgroups, groups...)\n}\n\n// RemoveCommand removes one or more commands from a parent command.\nfunc (c *Command) RemoveCommand(cmds ...*Command) {\n\tcommands := []*Command{}\nmain:\n\tfor _, command := range c.commands {\n\t\tfor _, cmd := range cmds {\n\t\t\tif command == cmd {\n\t\t\t\tcommand.parent = nil\n\t\t\t\tcontinue main\n\t\t\t}\n\t\t}\n\t\tcommands = append(commands, command)\n\t}\n\tc.commands = commands\n\t// recompute all lengths\n\tc.commandsMaxUseLen = 0\n\tc.commandsMaxCommandPathLen = 0\n\tc.commandsMaxNameLen = 0\n\tfor _, command := range c.commands {\n\t\tusageLen := len(command.Use)\n\t\tif usageLen > c.commandsMaxUseLen {\n\t\t\tc.commandsMaxUseLen = usageLen\n\t\t}\n\t\tcommandPathLen := len(command.CommandPath())\n\t\tif commandPathLen > c.commandsMaxCommandPathLen {\n\t\t\tc.commandsMaxCommandPathLen = commandPathLen\n\t\t}\n\t\tnameLen := len(command.Name())\n\t\tif nameLen > c.commandsMaxNameLen {\n\t\t\tc.commandsMaxNameLen = nameLen\n\t\t}\n\t}\n}\n\n// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.\nfunc (c *Command) Print(i ...interface{}) {\n\tfmt.Fprint(c.OutOrStderr(), i...)\n}\n\n// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.\nfunc (c *Command) Println(i ...interface{}) {\n\tc.Print(fmt.Sprintln(i...))\n}\n\n// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.\nfunc (c *Command) Printf(format string, i ...interface{}) {\n\tc.Print(fmt.Sprintf(format, i...))\n}\n\n// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.\nfunc (c *Command) PrintErr(i ...interface{}) {\n\tfmt.Fprint(c.ErrOrStderr(), i...)\n}\n\n// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.\nfunc (c *Command) PrintErrln(i ...interface{}) {\n\tc.PrintErr(fmt.Sprintln(i...))\n}\n\n// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.\nfunc (c *Command) PrintErrf(format string, i ...interface{}) {\n\tc.PrintErr(fmt.Sprintf(format, i...))\n}\n\n// CommandPath returns the full path to this command.\nfunc (c *Command) CommandPath() string {\n\tif c.HasParent() {\n\t\treturn c.Parent().CommandPath() + \" \" + c.Name()\n\t}\n\treturn c.DisplayName()\n}\n\n// DisplayName returns the name to display in help text. Returns command Name()\n// If CommandDisplayNameAnnoation is not set\nfunc (c *Command) DisplayName() string {\n\tif displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok {\n\t\treturn displayName\n\t}\n\treturn c.Name()\n}\n\n// UseLine puts out the full usage for a given command (including parents).\nfunc (c *Command) UseLine() string {\n\tvar useline string\n\tuse := strings.Replace(c.Use, c.Name(), c.DisplayName(), 1)\n\tif c.HasParent() {\n\t\tuseline = c.parent.CommandPath() + \" \" + use\n\t} else {\n\t\tuseline = use\n\t}\n\tif c.DisableFlagsInUseLine {\n\t\treturn useline\n\t}\n\tif c.HasAvailableFlags() && !strings.Contains(useline, \"[flags]\") {\n\t\tuseline += \" [flags]\"\n\t}\n\treturn useline\n}\n\n// DebugFlags used to determine which flags have been assigned to which commands\n// and which persist.\nfunc (c *Command) DebugFlags() {\n\tc.Println(\"DebugFlags called on\", c.Name())\n\tvar debugflags func(*Command)\n\n\tdebugflags = func(x *Command) {\n\t\tif x.HasFlags() || x.HasPersistentFlags() {\n\t\t\tc.Println(x.Name())\n\t\t}\n\t\tif x.HasFlags() {\n\t\t\tx.flags.VisitAll(func(f *flag.Flag) {\n\t\t\t\tif x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {\n\t\t\t\t\tc.Println(\"  -\"+f.Shorthand+\",\", \"--\"+f.Name, \"[\"+f.DefValue+\"]\", \"\", f.Value, \"  [LP]\")\n\t\t\t\t} else {\n\t\t\t\t\tc.Println(\"  -\"+f.Shorthand+\",\", \"--\"+f.Name, \"[\"+f.DefValue+\"]\", \"\", f.Value, \"  [L]\")\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\tif x.HasPersistentFlags() {\n\t\t\tx.pflags.VisitAll(func(f *flag.Flag) {\n\t\t\t\tif x.HasFlags() {\n\t\t\t\t\tif x.flags.Lookup(f.Name) == nil {\n\t\t\t\t\t\tc.Println(\"  -\"+f.Shorthand+\",\", \"--\"+f.Name, \"[\"+f.DefValue+\"]\", \"\", f.Value, \"  [P]\")\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tc.Println(\"  -\"+f.Shorthand+\",\", \"--\"+f.Name, \"[\"+f.DefValue+\"]\", \"\", f.Value, \"  [P]\")\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\tc.Println(x.flagErrorBuf)\n\t\tif x.HasSubCommands() {\n\t\t\tfor _, y := range x.commands {\n\t\t\t\tdebugflags(y)\n\t\t\t}\n\t\t}\n\t}\n\n\tdebugflags(c)\n}\n\n// Name returns the command's name: the first word in the use line.\nfunc (c *Command) Name() string {\n\tname := c.Use\n\ti := strings.Index(name, \" \")\n\tif i >= 0 {\n\t\tname = name[:i]\n\t}\n\treturn name\n}\n\n// HasAlias determines if a given string is an alias of the command.\nfunc (c *Command) HasAlias(s string) bool {\n\tfor _, a := range c.Aliases {\n\t\tif commandNameMatches(a, s) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// CalledAs returns the command name or alias that was used to invoke\n// this command or an empty string if the command has not been called.\nfunc (c *Command) CalledAs() string {\n\tif c.commandCalledAs.called {\n\t\treturn c.commandCalledAs.name\n\t}\n\treturn \"\"\n}\n\n// hasNameOrAliasPrefix returns true if the Name or any of aliases start\n// with prefix\nfunc (c *Command) hasNameOrAliasPrefix(prefix string) bool {\n\tif strings.HasPrefix(c.Name(), prefix) {\n\t\tc.commandCalledAs.name = c.Name()\n\t\treturn true\n\t}\n\tfor _, alias := range c.Aliases {\n\t\tif strings.HasPrefix(alias, prefix) {\n\t\t\tc.commandCalledAs.name = alias\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// NameAndAliases returns a list of the command name and all aliases\nfunc (c *Command) NameAndAliases() string {\n\treturn strings.Join(append([]string{c.Name()}, c.Aliases...), \", \")\n}\n\n// HasExample determines if the command has example.\nfunc (c *Command) HasExample() bool {\n\treturn len(c.Example) > 0\n}\n\n// Runnable determines if the command is itself runnable.\nfunc (c *Command) Runnable() bool {\n\treturn c.Run != nil || c.RunE != nil\n}\n\n// HasSubCommands determines if the command has children commands.\nfunc (c *Command) HasSubCommands() bool {\n\treturn len(c.commands) > 0\n}\n\n// IsAvailableCommand determines if a command is available as a non-help command\n// (this includes all non deprecated/hidden commands).\nfunc (c *Command) IsAvailableCommand() bool {\n\tif len(c.Deprecated) != 0 || c.Hidden {\n\t\treturn false\n\t}\n\n\tif c.HasParent() && c.Parent().helpCommand == c {\n\t\treturn false\n\t}\n\n\tif c.Runnable() || c.HasAvailableSubCommands() {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n// IsAdditionalHelpTopicCommand determines if a command is an additional\n// help topic command; additional help topic command is determined by the\n// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that\n// are runnable/hidden/deprecated.\n// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.\nfunc (c *Command) IsAdditionalHelpTopicCommand() bool {\n\t// if a command is runnable, deprecated, or hidden it is not a 'help' command\n\tif c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {\n\t\treturn false\n\t}\n\n\t// if any non-help sub commands are found, the command is not a 'help' command\n\tfor _, sub := range c.commands {\n\t\tif !sub.IsAdditionalHelpTopicCommand() {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// the command either has no sub commands, or no non-help sub commands\n\treturn true\n}\n\n// HasHelpSubCommands determines if a command has any available 'help' sub commands\n// that need to be shown in the usage/help default template under 'additional help\n// topics'.\nfunc (c *Command) HasHelpSubCommands() bool {\n\t// return true on the first found available 'help' sub command\n\tfor _, sub := range c.commands {\n\t\tif sub.IsAdditionalHelpTopicCommand() {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t// the command either has no sub commands, or no available 'help' sub commands\n\treturn false\n}\n\n// HasAvailableSubCommands determines if a command has available sub commands that\n// need to be shown in the usage/help default template under 'available commands'.\nfunc (c *Command) HasAvailableSubCommands() bool {\n\t// return true on the first found available (non deprecated/help/hidden)\n\t// sub command\n\tfor _, sub := range c.commands {\n\t\tif sub.IsAvailableCommand() {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t// the command either has no sub commands, or no available (non deprecated/help/hidden)\n\t// sub commands\n\treturn false\n}\n\n// HasParent determines if the command is a child command.\nfunc (c *Command) HasParent() bool {\n\treturn c.parent != nil\n}\n\n// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.\nfunc (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {\n\treturn c.globNormFunc\n}\n\n// Flags returns the complete FlagSet that applies\n// to this command (local and persistent declared here and by all parents).\nfunc (c *Command) Flags() *flag.FlagSet {\n\tif c.flags == nil {\n\t\tc.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)\n\t\tif c.flagErrorBuf == nil {\n\t\t\tc.flagErrorBuf = new(bytes.Buffer)\n\t\t}\n\t\tc.flags.SetOutput(c.flagErrorBuf)\n\t}\n\n\treturn c.flags\n}\n\n// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.\n// This function does not modify the flags of the current command, it's purpose is to return the current state.\nfunc (c *Command) LocalNonPersistentFlags() *flag.FlagSet {\n\tpersistentFlags := c.PersistentFlags()\n\n\tout := flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)\n\tc.LocalFlags().VisitAll(func(f *flag.Flag) {\n\t\tif persistentFlags.Lookup(f.Name) == nil {\n\t\t\tout.AddFlag(f)\n\t\t}\n\t})\n\treturn out\n}\n\n// LocalFlags returns the local FlagSet specifically set in the current command.\n// This function does not modify the flags of the current command, it's purpose is to return the current state.\nfunc (c *Command) LocalFlags() *flag.FlagSet {\n\tc.mergePersistentFlags()\n\n\tif c.lflags == nil {\n\t\tc.lflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)\n\t\tif c.flagErrorBuf == nil {\n\t\t\tc.flagErrorBuf = new(bytes.Buffer)\n\t\t}\n\t\tc.lflags.SetOutput(c.flagErrorBuf)\n\t}\n\tc.lflags.SortFlags = c.Flags().SortFlags\n\tif c.globNormFunc != nil {\n\t\tc.lflags.SetNormalizeFunc(c.globNormFunc)\n\t}\n\n\taddToLocal := func(f *flag.Flag) {\n\t\t// Add the flag if it is not a parent PFlag, or it shadows a parent PFlag\n\t\tif c.lflags.Lookup(f.Name) == nil && f != c.parentsPflags.Lookup(f.Name) {\n\t\t\tc.lflags.AddFlag(f)\n\t\t}\n\t}\n\tc.Flags().VisitAll(addToLocal)\n\tc.PersistentFlags().VisitAll(addToLocal)\n\treturn c.lflags\n}\n\n// InheritedFlags returns all flags which were inherited from parent commands.\n// This function does not modify the flags of the current command, it's purpose is to return the current state.\nfunc (c *Command) InheritedFlags() *flag.FlagSet {\n\tc.mergePersistentFlags()\n\n\tif c.iflags == nil {\n\t\tc.iflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)\n\t\tif c.flagErrorBuf == nil {\n\t\t\tc.flagErrorBuf = new(bytes.Buffer)\n\t\t}\n\t\tc.iflags.SetOutput(c.flagErrorBuf)\n\t}\n\n\tlocal := c.LocalFlags()\n\tif c.globNormFunc != nil {\n\t\tc.iflags.SetNormalizeFunc(c.globNormFunc)\n\t}\n\n\tc.parentsPflags.VisitAll(func(f *flag.Flag) {\n\t\tif c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {\n\t\t\tc.iflags.AddFlag(f)\n\t\t}\n\t})\n\treturn c.iflags\n}\n\n// NonInheritedFlags returns all flags which were not inherited from parent commands.\n// This function does not modify the flags of the current command, it's purpose is to return the current state.\nfunc (c *Command) NonInheritedFlags() *flag.FlagSet {\n\treturn c.LocalFlags()\n}\n\n// PersistentFlags returns the persistent FlagSet specifically set in the current command.\nfunc (c *Command) PersistentFlags() *flag.FlagSet {\n\tif c.pflags == nil {\n\t\tc.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)\n\t\tif c.flagErrorBuf == nil {\n\t\t\tc.flagErrorBuf = new(bytes.Buffer)\n\t\t}\n\t\tc.pflags.SetOutput(c.flagErrorBuf)\n\t}\n\treturn c.pflags\n}\n\n// ResetFlags deletes all flags from command.\nfunc (c *Command) ResetFlags() {\n\tc.flagErrorBuf = new(bytes.Buffer)\n\tc.flagErrorBuf.Reset()\n\tc.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)\n\tc.flags.SetOutput(c.flagErrorBuf)\n\tc.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)\n\tc.pflags.SetOutput(c.flagErrorBuf)\n\n\tc.lflags = nil\n\tc.iflags = nil\n\tc.parentsPflags = nil\n}\n\n// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).\nfunc (c *Command) HasFlags() bool {\n\treturn c.Flags().HasFlags()\n}\n\n// HasPersistentFlags checks if the command contains persistent flags.\nfunc (c *Command) HasPersistentFlags() bool {\n\treturn c.PersistentFlags().HasFlags()\n}\n\n// HasLocalFlags checks if the command has flags specifically declared locally.\nfunc (c *Command) HasLocalFlags() bool {\n\treturn c.LocalFlags().HasFlags()\n}\n\n// HasInheritedFlags checks if the command has flags inherited from its parent command.\nfunc (c *Command) HasInheritedFlags() bool {\n\treturn c.InheritedFlags().HasFlags()\n}\n\n// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire\n// structure) which are not hidden or deprecated.\nfunc (c *Command) HasAvailableFlags() bool {\n\treturn c.Flags().HasAvailableFlags()\n}\n\n// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.\nfunc (c *Command) HasAvailablePersistentFlags() bool {\n\treturn c.PersistentFlags().HasAvailableFlags()\n}\n\n// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden\n// or deprecated.\nfunc (c *Command) HasAvailableLocalFlags() bool {\n\treturn c.LocalFlags().HasAvailableFlags()\n}\n\n// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are\n// not hidden or deprecated.\nfunc (c *Command) HasAvailableInheritedFlags() bool {\n\treturn c.InheritedFlags().HasAvailableFlags()\n}\n\n// Flag climbs up the command tree looking for matching flag.\nfunc (c *Command) Flag(name string) (flag *flag.Flag) {\n\tflag = c.Flags().Lookup(name)\n\n\tif flag == nil {\n\t\tflag = c.persistentFlag(name)\n\t}\n\n\treturn\n}\n\n// Recursively find matching persistent flag.\nfunc (c *Command) persistentFlag(name string) (flag *flag.Flag) {\n\tif c.HasPersistentFlags() {\n\t\tflag = c.PersistentFlags().Lookup(name)\n\t}\n\n\tif flag == nil {\n\t\tc.updateParentsPflags()\n\t\tflag = c.parentsPflags.Lookup(name)\n\t}\n\treturn\n}\n\n// ParseFlags parses persistent flag tree and local flags.\nfunc (c *Command) ParseFlags(args []string) error {\n\tif c.DisableFlagParsing {\n\t\treturn nil\n\t}\n\n\tif c.flagErrorBuf == nil {\n\t\tc.flagErrorBuf = new(bytes.Buffer)\n\t}\n\tbeforeErrorBufLen := c.flagErrorBuf.Len()\n\tc.mergePersistentFlags()\n\n\t// do it here after merging all flags and just before parse\n\tc.Flags().ParseErrorsAllowlist = flag.ParseErrorsAllowlist(c.FParseErrWhitelist)\n\n\terr := c.Flags().Parse(args)\n\t// Print warnings if they occurred (e.g. deprecated flag messages).\n\tif c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {\n\t\tc.Print(c.flagErrorBuf.String())\n\t}\n\n\treturn err\n}\n\n// Parent returns a commands parent command.\nfunc (c *Command) Parent() *Command {\n\treturn c.parent\n}\n\n// mergePersistentFlags merges c.PersistentFlags() to c.Flags()\n// and adds missing persistent flags of all parents.\nfunc (c *Command) mergePersistentFlags() {\n\tc.updateParentsPflags()\n\tc.Flags().AddFlagSet(c.PersistentFlags())\n\tc.Flags().AddFlagSet(c.parentsPflags)\n}\n\n// updateParentsPflags updates c.parentsPflags by adding\n// new persistent flags of all parents.\n// If c.parentsPflags == nil, it makes new.\nfunc (c *Command) updateParentsPflags() {\n\tif c.parentsPflags == nil {\n\t\tc.parentsPflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)\n\t\tc.parentsPflags.SetOutput(c.flagErrorBuf)\n\t\tc.parentsPflags.SortFlags = false\n\t}\n\n\tif c.globNormFunc != nil {\n\t\tc.parentsPflags.SetNormalizeFunc(c.globNormFunc)\n\t}\n\n\tc.Root().PersistentFlags().AddFlagSet(flag.CommandLine)\n\n\tc.VisitParents(func(parent *Command) {\n\t\tc.parentsPflags.AddFlagSet(parent.PersistentFlags())\n\t})\n}\n\n// commandNameMatches checks if two command names are equal\n// taking into account case sensitivity according to\n// EnableCaseInsensitive global configuration.\nfunc commandNameMatches(s string, t string) bool {\n\tif EnableCaseInsensitive {\n\t\treturn strings.EqualFold(s, t)\n\t}\n\n\treturn s == t\n}\n\n// tmplFunc holds a template and a function that will execute said template.\ntype tmplFunc struct {\n\ttmpl string\n\tfn   func(io.Writer, interface{}) error\n}\n\nconst defaultUsageTemplate = `Usage:{{if .Runnable}}\n  {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}\n  {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}\n\nAliases:\n  {{.NameAndAliases}}{{end}}{{if .HasExample}}\n\nExamples:\n{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}\n\nAvailable Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name \"help\"))}}\n  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}\n\n{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name \"help\")))}}\n  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}}\n\nAdditional Commands:{{range $cmds}}{{if (and (eq .GroupID \"\") (or .IsAvailableCommand (eq .Name \"help\")))}}\n  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}\n\nFlags:\n{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}\n\nGlobal Flags:\n{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}\n\nAdditional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}\n  {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}\n\nUse \"{{.CommandPath}} [command] --help\" for more information about a command.{{end}}\n`\n\n// defaultUsageFunc is equivalent to executing defaultUsageTemplate. The two should be changed in sync.\nfunc defaultUsageFunc(w io.Writer, in interface{}) error {\n\tc := in.(*Command)\n\tfmt.Fprint(w, \"Usage:\")\n\tif c.Runnable() {\n\t\tfmt.Fprintf(w, \"\\n  %s\", c.UseLine())\n\t}\n\tif c.HasAvailableSubCommands() {\n\t\tfmt.Fprintf(w, \"\\n  %s [command]\", c.CommandPath())\n\t}\n\tif len(c.Aliases) > 0 {\n\t\tfmt.Fprintf(w, \"\\n\\nAliases:\\n\")\n\t\tfmt.Fprintf(w, \"  %s\", c.NameAndAliases())\n\t}\n\tif c.HasExample() {\n\t\tfmt.Fprintf(w, \"\\n\\nExamples:\\n\")\n\t\tfmt.Fprintf(w, \"%s\", c.Example)\n\t}\n\tif c.HasAvailableSubCommands() {\n\t\tcmds := c.Commands()\n\t\tif len(c.Groups()) == 0 {\n\t\t\tfmt.Fprintf(w, \"\\n\\nAvailable Commands:\")\n\t\t\tfor _, subcmd := range cmds {\n\t\t\t\tif subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName {\n\t\t\t\t\tfmt.Fprintf(w, \"\\n  %s %s\", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor _, group := range c.Groups() {\n\t\t\t\tfmt.Fprintf(w, \"\\n\\n%s\", group.Title)\n\t\t\t\tfor _, subcmd := range cmds {\n\t\t\t\t\tif subcmd.GroupID == group.ID && (subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName) {\n\t\t\t\t\t\tfmt.Fprintf(w, \"\\n  %s %s\", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !c.AllChildCommandsHaveGroup() {\n\t\t\t\tfmt.Fprintf(w, \"\\n\\nAdditional Commands:\")\n\t\t\t\tfor _, subcmd := range cmds {\n\t\t\t\t\tif subcmd.GroupID == \"\" && (subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName) {\n\t\t\t\t\t\tfmt.Fprintf(w, \"\\n  %s %s\", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif c.HasAvailableLocalFlags() {\n\t\tfmt.Fprintf(w, \"\\n\\nFlags:\\n\")\n\t\tfmt.Fprint(w, trimRightSpace(c.LocalFlags().FlagUsages()))\n\t}\n\tif c.HasAvailableInheritedFlags() {\n\t\tfmt.Fprintf(w, \"\\n\\nGlobal Flags:\\n\")\n\t\tfmt.Fprint(w, trimRightSpace(c.InheritedFlags().FlagUsages()))\n\t}\n\tif c.HasHelpSubCommands() {\n\t\tfmt.Fprintf(w, \"\\n\\nAdditional help topics:\")\n\t\tfor _, subcmd := range c.Commands() {\n\t\t\tif subcmd.IsAdditionalHelpTopicCommand() {\n\t\t\t\tfmt.Fprintf(w, \"\\n  %s %s\", rpad(subcmd.CommandPath(), subcmd.CommandPathPadding()), subcmd.Short)\n\t\t\t}\n\t\t}\n\t}\n\tif c.HasAvailableSubCommands() {\n\t\tfmt.Fprintf(w, \"\\n\\nUse \\\"%s [command] --help\\\" for more information about a command.\", c.CommandPath())\n\t}\n\tfmt.Fprintln(w)\n\treturn nil\n}\n\nconst defaultHelpTemplate = `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}\n\n{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`\n\n// defaultHelpFunc is equivalent to executing defaultHelpTemplate. The two should be changed in sync.\nfunc defaultHelpFunc(w io.Writer, in interface{}) error {\n\tc := in.(*Command)\n\tusage := c.Long\n\tif usage == \"\" {\n\t\tusage = c.Short\n\t}\n\tusage = trimRightSpace(usage)\n\tif usage != \"\" {\n\t\tfmt.Fprintln(w, usage)\n\t\tfmt.Fprintln(w)\n\t}\n\tif c.Runnable() || c.HasSubCommands() {\n\t\tfmt.Fprint(w, c.UsageString())\n\t}\n\treturn nil\n}\n\nconst defaultVersionTemplate = `{{with .DisplayName}}{{printf \"%s \" .}}{{end}}{{printf \"version %s\" .Version}}\n`\n\n// defaultVersionFunc is equivalent to executing defaultVersionTemplate. The two should be changed in sync.\nfunc defaultVersionFunc(w io.Writer, in interface{}) error {\n\tc := in.(*Command)\n\t_, err := fmt.Fprintf(w, \"%s version %s\\n\", c.DisplayName(), c.Version)\n\treturn err\n}\n"
  },
  {
    "path": "command_notwin.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n//go:build !windows\n// +build !windows\n\npackage cobra\n\nvar preExecHookFn func(*Command)\n"
  },
  {
    "path": "command_test.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/spf13/pflag\"\n)\n\nfunc emptyRun(*Command, []string) {}\n\nfunc executeCommand(root *Command, args ...string) (output string, err error) {\n\t_, output, err = executeCommandC(root, args...)\n\treturn output, err\n}\n\nfunc executeCommandWithContext(ctx context.Context, root *Command, args ...string) (output string, err error) {\n\tbuf := new(bytes.Buffer)\n\troot.SetOut(buf)\n\troot.SetErr(buf)\n\troot.SetArgs(args)\n\n\terr = root.ExecuteContext(ctx)\n\n\treturn buf.String(), err\n}\n\nfunc executeCommandC(root *Command, args ...string) (c *Command, output string, err error) {\n\tbuf := new(bytes.Buffer)\n\troot.SetOut(buf)\n\troot.SetErr(buf)\n\troot.SetArgs(args)\n\n\tc, err = root.ExecuteC()\n\n\treturn c, buf.String(), err\n}\n\nfunc executeCommandWithContextC(ctx context.Context, root *Command, args ...string) (c *Command, output string, err error) {\n\tbuf := new(bytes.Buffer)\n\troot.SetOut(buf)\n\troot.SetErr(buf)\n\troot.SetArgs(args)\n\n\tc, err = root.ExecuteContextC(ctx)\n\n\treturn c, buf.String(), err\n}\n\nfunc resetCommandLineFlagSet() {\n\tpflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)\n}\n\nfunc checkStringContains(t *testing.T, got, expected string) {\n\tif !strings.Contains(got, expected) {\n\t\tt.Errorf(\"Expected to contain: \\n %v\\nGot:\\n %v\\n\", expected, got)\n\t}\n}\n\nfunc checkStringOmits(t *testing.T, got, expected string) {\n\tif strings.Contains(got, expected) {\n\t\tt.Errorf(\"Expected to not contain: \\n %v\\nGot: %v\", expected, got)\n\t}\n}\n\nconst onetwo = \"one two\"\n\nfunc TestSingleCommand(t *testing.T) {\n\tvar rootCmdArgs []string\n\trootCmd := &Command{\n\t\tUse:  \"root\",\n\t\tArgs: ExactArgs(2),\n\t\tRun:  func(_ *Command, args []string) { rootCmdArgs = args },\n\t}\n\taCmd := &Command{Use: \"a\", Args: NoArgs, Run: emptyRun}\n\tbCmd := &Command{Use: \"b\", Args: NoArgs, Run: emptyRun}\n\trootCmd.AddCommand(aCmd, bCmd)\n\n\toutput, err := executeCommand(rootCmd, \"one\", \"two\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tgot := strings.Join(rootCmdArgs, \" \")\n\tif got != onetwo {\n\t\tt.Errorf(\"rootCmdArgs expected: %q, got: %q\", onetwo, got)\n\t}\n}\n\nfunc TestChildCommand(t *testing.T) {\n\tvar child1CmdArgs []string\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild1Cmd := &Command{\n\t\tUse:  \"child1\",\n\t\tArgs: ExactArgs(2),\n\t\tRun:  func(_ *Command, args []string) { child1CmdArgs = args },\n\t}\n\tchild2Cmd := &Command{Use: \"child2\", Args: NoArgs, Run: emptyRun}\n\trootCmd.AddCommand(child1Cmd, child2Cmd)\n\n\toutput, err := executeCommand(rootCmd, \"child1\", \"one\", \"two\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tgot := strings.Join(child1CmdArgs, \" \")\n\tif got != onetwo {\n\t\tt.Errorf(\"child1CmdArgs expected: %q, got: %q\", onetwo, got)\n\t}\n}\n\nfunc TestCallCommandWithoutSubcommands(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\t_, err := executeCommand(rootCmd)\n\tif err != nil {\n\t\tt.Errorf(\"Calling command without subcommands should not have error: %v\", err)\n\t}\n}\n\nfunc TestRootExecuteUnknownCommand(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\trootCmd.AddCommand(&Command{Use: \"child\", Run: emptyRun})\n\n\toutput, _ := executeCommand(rootCmd, \"unknown\")\n\n\texpected := \"Error: unknown command \\\"unknown\\\" for \\\"root\\\"\\nRun 'root --help' for usage.\\n\"\n\n\tif output != expected {\n\t\tt.Errorf(\"Expected:\\n %q\\nGot:\\n %q\\n\", expected, output)\n\t}\n}\n\nfunc TestSubcommandExecuteC(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchildCmd := &Command{Use: \"child\", Run: emptyRun}\n\trootCmd.AddCommand(childCmd)\n\n\tc, output, err := executeCommandC(rootCmd, \"child\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tif c.Name() != \"child\" {\n\t\tt.Errorf(`invalid command returned from ExecuteC: expected \"child\"', got: %q`, c.Name())\n\t}\n}\n\nfunc TestExecuteContext(t *testing.T) {\n\tctx := context.TODO()\n\n\tctxRun := func(cmd *Command, args []string) {\n\t\tif cmd.Context() != ctx {\n\t\t\tt.Errorf(\"Command %q must have context when called with ExecuteContext\", cmd.Use)\n\t\t}\n\t}\n\n\trootCmd := &Command{Use: \"root\", Run: ctxRun, PreRun: ctxRun}\n\tchildCmd := &Command{Use: \"child\", Run: ctxRun, PreRun: ctxRun}\n\tgranchildCmd := &Command{Use: \"grandchild\", Run: ctxRun, PreRun: ctxRun}\n\n\tchildCmd.AddCommand(granchildCmd)\n\trootCmd.AddCommand(childCmd)\n\n\tif _, err := executeCommandWithContext(ctx, rootCmd, \"\"); err != nil {\n\t\tt.Errorf(\"Root command must not fail: %+v\", err)\n\t}\n\n\tif _, err := executeCommandWithContext(ctx, rootCmd, \"child\"); err != nil {\n\t\tt.Errorf(\"Subcommand must not fail: %+v\", err)\n\t}\n\n\tif _, err := executeCommandWithContext(ctx, rootCmd, \"child\", \"grandchild\"); err != nil {\n\t\tt.Errorf(\"Command child must not fail: %+v\", err)\n\t}\n}\n\nfunc TestExecuteContextC(t *testing.T) {\n\tctx := context.TODO()\n\n\tctxRun := func(cmd *Command, args []string) {\n\t\tif cmd.Context() != ctx {\n\t\t\tt.Errorf(\"Command %q must have context when called with ExecuteContext\", cmd.Use)\n\t\t}\n\t}\n\n\trootCmd := &Command{Use: \"root\", Run: ctxRun, PreRun: ctxRun}\n\tchildCmd := &Command{Use: \"child\", Run: ctxRun, PreRun: ctxRun}\n\tgranchildCmd := &Command{Use: \"grandchild\", Run: ctxRun, PreRun: ctxRun}\n\n\tchildCmd.AddCommand(granchildCmd)\n\trootCmd.AddCommand(childCmd)\n\n\tif _, _, err := executeCommandWithContextC(ctx, rootCmd, \"\"); err != nil {\n\t\tt.Errorf(\"Root command must not fail: %+v\", err)\n\t}\n\n\tif _, _, err := executeCommandWithContextC(ctx, rootCmd, \"child\"); err != nil {\n\t\tt.Errorf(\"Subcommand must not fail: %+v\", err)\n\t}\n\n\tif _, _, err := executeCommandWithContextC(ctx, rootCmd, \"child\", \"grandchild\"); err != nil {\n\t\tt.Errorf(\"Command child must not fail: %+v\", err)\n\t}\n}\n\nfunc TestExecute_NoContext(t *testing.T) {\n\trun := func(cmd *Command, args []string) {\n\t\tif cmd.Context() != context.Background() {\n\t\t\tt.Errorf(\"Command %s must have background context\", cmd.Use)\n\t\t}\n\t}\n\n\trootCmd := &Command{Use: \"root\", Run: run, PreRun: run}\n\tchildCmd := &Command{Use: \"child\", Run: run, PreRun: run}\n\tgranchildCmd := &Command{Use: \"grandchild\", Run: run, PreRun: run}\n\n\tchildCmd.AddCommand(granchildCmd)\n\trootCmd.AddCommand(childCmd)\n\n\tif _, err := executeCommand(rootCmd, \"\"); err != nil {\n\t\tt.Errorf(\"Root command must not fail: %+v\", err)\n\t}\n\n\tif _, err := executeCommand(rootCmd, \"child\"); err != nil {\n\t\tt.Errorf(\"Subcommand must not fail: %+v\", err)\n\t}\n\n\tif _, err := executeCommand(rootCmd, \"child\", \"grandchild\"); err != nil {\n\t\tt.Errorf(\"Command child must not fail: %+v\", err)\n\t}\n}\n\nfunc TestRootUnknownCommandSilenced(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\trootCmd.SilenceErrors = true\n\trootCmd.SilenceUsage = true\n\trootCmd.AddCommand(&Command{Use: \"child\", Run: emptyRun})\n\n\toutput, _ := executeCommand(rootCmd, \"unknown\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Expected blank output, because of silenced usage.\\nGot:\\n %q\\n\", output)\n\t}\n}\n\nfunc TestCommandAlias(t *testing.T) {\n\tvar timesCmdArgs []string\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\techoCmd := &Command{\n\t\tUse:     \"echo\",\n\t\tAliases: []string{\"say\", \"tell\"},\n\t\tArgs:    NoArgs,\n\t\tRun:     emptyRun,\n\t}\n\ttimesCmd := &Command{\n\t\tUse:  \"times\",\n\t\tArgs: ExactArgs(2),\n\t\tRun:  func(_ *Command, args []string) { timesCmdArgs = args },\n\t}\n\techoCmd.AddCommand(timesCmd)\n\trootCmd.AddCommand(echoCmd)\n\n\toutput, err := executeCommand(rootCmd, \"tell\", \"times\", \"one\", \"two\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tgot := strings.Join(timesCmdArgs, \" \")\n\tif got != onetwo {\n\t\tt.Errorf(\"timesCmdArgs expected: %v, got: %v\", onetwo, got)\n\t}\n}\n\nfunc TestEnablePrefixMatching(t *testing.T) {\n\tEnablePrefixMatching = true\n\n\tvar aCmdArgs []string\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\taCmd := &Command{\n\t\tUse:  \"aCmd\",\n\t\tArgs: ExactArgs(2),\n\t\tRun:  func(_ *Command, args []string) { aCmdArgs = args },\n\t}\n\tbCmd := &Command{Use: \"bCmd\", Args: NoArgs, Run: emptyRun}\n\trootCmd.AddCommand(aCmd, bCmd)\n\n\toutput, err := executeCommand(rootCmd, \"a\", \"one\", \"two\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tgot := strings.Join(aCmdArgs, \" \")\n\tif got != onetwo {\n\t\tt.Errorf(\"aCmdArgs expected: %q, got: %q\", onetwo, got)\n\t}\n\n\tEnablePrefixMatching = defaultPrefixMatching\n}\n\nfunc TestAliasPrefixMatching(t *testing.T) {\n\tEnablePrefixMatching = true\n\n\tvar timesCmdArgs []string\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\techoCmd := &Command{\n\t\tUse:     \"echo\",\n\t\tAliases: []string{\"say\", \"tell\"},\n\t\tArgs:    NoArgs,\n\t\tRun:     emptyRun,\n\t}\n\ttimesCmd := &Command{\n\t\tUse:  \"times\",\n\t\tArgs: ExactArgs(2),\n\t\tRun:  func(_ *Command, args []string) { timesCmdArgs = args },\n\t}\n\techoCmd.AddCommand(timesCmd)\n\trootCmd.AddCommand(echoCmd)\n\n\toutput, err := executeCommand(rootCmd, \"sa\", \"times\", \"one\", \"two\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tgot := strings.Join(timesCmdArgs, \" \")\n\tif got != onetwo {\n\t\tt.Errorf(\"timesCmdArgs expected: %v, got: %v\", onetwo, got)\n\t}\n\n\tEnablePrefixMatching = defaultPrefixMatching\n}\n\n// TestPlugin checks usage as plugin for another command such as kubectl.  The\n// executable is `kubectl-plugin`, but we run it as `kubectl plugin`. The help\n// text should reflect the way we run the command.\nfunc TestPlugin(t *testing.T) {\n\tcmd := &Command{\n\t\tUse:     \"kubectl-plugin\",\n\t\tVersion: \"1.0.0\",\n\t\tArgs:    NoArgs,\n\t\tAnnotations: map[string]string{\n\t\t\tCommandDisplayNameAnnotation: \"kubectl plugin\",\n\t\t},\n\t\tRun: emptyRun,\n\t}\n\n\tcmdHelp, err := executeCommand(cmd, \"-h\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, cmdHelp, \"kubectl plugin [flags]\")\n\tcheckStringContains(t, cmdHelp, \"help for kubectl plugin\")\n\tcheckStringContains(t, cmdHelp, \"version for kubectl plugin\")\n}\n\n// TestPluginWithSubCommands checks usage as plugin with sub commands.\nfunc TestPluginWithSubCommands(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse:     \"kubectl-plugin\",\n\t\tVersion: \"1.0.0\",\n\t\tArgs:    NoArgs,\n\t\tAnnotations: map[string]string{\n\t\t\tCommandDisplayNameAnnotation: \"kubectl plugin\",\n\t\t},\n\t}\n\n\tsubCmd := &Command{Use: \"sub [flags]\", Args: NoArgs, Run: emptyRun}\n\trootCmd.AddCommand(subCmd)\n\n\trootHelp, err := executeCommand(rootCmd, \"-h\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, rootHelp, \"kubectl plugin [command]\")\n\tcheckStringContains(t, rootHelp, \"help for kubectl plugin\")\n\tcheckStringContains(t, rootHelp, \"version for kubectl plugin\")\n\tcheckStringContains(t, rootHelp, \"kubectl plugin [command] --help\")\n\n\tchildHelp, err := executeCommand(rootCmd, \"sub\", \"-h\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, childHelp, \"kubectl plugin sub [flags]\")\n\tcheckStringContains(t, childHelp, \"help for sub\")\n\n\thelpHelp, err := executeCommand(rootCmd, \"help\", \"-h\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, helpHelp, \"kubectl plugin help [path to command]\")\n\tcheckStringContains(t, helpHelp, \"kubectl plugin help [command]\")\n}\n\n// TestChildSameName checks the correct behaviour of cobra in cases,\n// when an application with name \"foo\" and with subcommand \"foo\"\n// is executed with args \"foo foo\".\nfunc TestChildSameName(t *testing.T) {\n\tvar fooCmdArgs []string\n\trootCmd := &Command{Use: \"foo\", Args: NoArgs, Run: emptyRun}\n\tfooCmd := &Command{\n\t\tUse:  \"foo\",\n\t\tArgs: ExactArgs(2),\n\t\tRun:  func(_ *Command, args []string) { fooCmdArgs = args },\n\t}\n\tbarCmd := &Command{Use: \"bar\", Args: NoArgs, Run: emptyRun}\n\trootCmd.AddCommand(fooCmd, barCmd)\n\n\toutput, err := executeCommand(rootCmd, \"foo\", \"one\", \"two\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tgot := strings.Join(fooCmdArgs, \" \")\n\tif got != onetwo {\n\t\tt.Errorf(\"fooCmdArgs expected: %v, got: %v\", onetwo, got)\n\t}\n}\n\n// TestGrandChildSameName checks the correct behaviour of cobra in cases,\n// when user has a root command and a grand child\n// with the same name.\nfunc TestGrandChildSameName(t *testing.T) {\n\tvar fooCmdArgs []string\n\trootCmd := &Command{Use: \"foo\", Args: NoArgs, Run: emptyRun}\n\tbarCmd := &Command{Use: \"bar\", Args: NoArgs, Run: emptyRun}\n\tfooCmd := &Command{\n\t\tUse:  \"foo\",\n\t\tArgs: ExactArgs(2),\n\t\tRun:  func(_ *Command, args []string) { fooCmdArgs = args },\n\t}\n\tbarCmd.AddCommand(fooCmd)\n\trootCmd.AddCommand(barCmd)\n\n\toutput, err := executeCommand(rootCmd, \"bar\", \"foo\", \"one\", \"two\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tgot := strings.Join(fooCmdArgs, \" \")\n\tif got != onetwo {\n\t\tt.Errorf(\"fooCmdArgs expected: %v, got: %v\", onetwo, got)\n\t}\n}\n\nfunc TestFlagLong(t *testing.T) {\n\tvar cArgs []string\n\tc := &Command{\n\t\tUse:  \"c\",\n\t\tArgs: ArbitraryArgs,\n\t\tRun:  func(_ *Command, args []string) { cArgs = args },\n\t}\n\n\tvar intFlagValue int\n\tvar stringFlagValue string\n\tc.Flags().IntVar(&intFlagValue, \"intf\", -1, \"\")\n\tc.Flags().StringVar(&stringFlagValue, \"sf\", \"\", \"\")\n\n\toutput, err := executeCommand(c, \"--intf=7\", \"--sf=abc\", \"one\", \"--\", \"two\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tif c.ArgsLenAtDash() != 1 {\n\t\tt.Errorf(\"Expected ArgsLenAtDash: %v but got %v\", 1, c.ArgsLenAtDash())\n\t}\n\tif intFlagValue != 7 {\n\t\tt.Errorf(\"Expected intFlagValue: %v, got %v\", 7, intFlagValue)\n\t}\n\tif stringFlagValue != \"abc\" {\n\t\tt.Errorf(\"Expected stringFlagValue: %q, got %q\", \"abc\", stringFlagValue)\n\t}\n\n\tgot := strings.Join(cArgs, \" \")\n\tif got != onetwo {\n\t\tt.Errorf(\"rootCmdArgs expected: %q, got: %q\", onetwo, got)\n\t}\n}\n\nfunc TestFlagShort(t *testing.T) {\n\tvar cArgs []string\n\tc := &Command{\n\t\tUse:  \"c\",\n\t\tArgs: ArbitraryArgs,\n\t\tRun:  func(_ *Command, args []string) { cArgs = args },\n\t}\n\n\tvar intFlagValue int\n\tvar stringFlagValue string\n\tc.Flags().IntVarP(&intFlagValue, \"intf\", \"i\", -1, \"\")\n\tc.Flags().StringVarP(&stringFlagValue, \"sf\", \"s\", \"\", \"\")\n\n\toutput, err := executeCommand(c, \"-i\", \"7\", \"-sabc\", \"one\", \"two\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tif intFlagValue != 7 {\n\t\tt.Errorf(\"Expected flag value: %v, got %v\", 7, intFlagValue)\n\t}\n\tif stringFlagValue != \"abc\" {\n\t\tt.Errorf(\"Expected stringFlagValue: %q, got %q\", \"abc\", stringFlagValue)\n\t}\n\n\tgot := strings.Join(cArgs, \" \")\n\tif got != onetwo {\n\t\tt.Errorf(\"rootCmdArgs expected: %q, got: %q\", onetwo, got)\n\t}\n}\n\nfunc TestChildFlag(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchildCmd := &Command{Use: \"child\", Run: emptyRun}\n\trootCmd.AddCommand(childCmd)\n\n\tvar intFlagValue int\n\tchildCmd.Flags().IntVarP(&intFlagValue, \"intf\", \"i\", -1, \"\")\n\n\toutput, err := executeCommand(rootCmd, \"child\", \"-i7\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tif intFlagValue != 7 {\n\t\tt.Errorf(\"Expected flag value: %v, got %v\", 7, intFlagValue)\n\t}\n}\n\nfunc TestChildFlagWithParentLocalFlag(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchildCmd := &Command{Use: \"child\", Run: emptyRun}\n\trootCmd.AddCommand(childCmd)\n\n\tvar intFlagValue int\n\trootCmd.Flags().StringP(\"sf\", \"s\", \"\", \"\")\n\tchildCmd.Flags().IntVarP(&intFlagValue, \"intf\", \"i\", -1, \"\")\n\n\t_, err := executeCommand(rootCmd, \"child\", \"-i7\", \"-sabc\")\n\tif err == nil {\n\t\tt.Errorf(\"Invalid flag should generate error\")\n\t}\n\n\tcheckStringContains(t, err.Error(), \"unknown shorthand\")\n\n\tif intFlagValue != 7 {\n\t\tt.Errorf(\"Expected flag value: %v, got %v\", 7, intFlagValue)\n\t}\n}\n\nfunc TestFlagInvalidInput(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\trootCmd.Flags().IntP(\"intf\", \"i\", -1, \"\")\n\n\t_, err := executeCommand(rootCmd, \"-iabc\")\n\tif err == nil {\n\t\tt.Errorf(\"Invalid flag value should generate error\")\n\t}\n\n\tcheckStringContains(t, err.Error(), \"invalid syntax\")\n}\n\nfunc TestFlagBeforeCommand(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchildCmd := &Command{Use: \"child\", Run: emptyRun}\n\trootCmd.AddCommand(childCmd)\n\n\tvar flagValue int\n\tchildCmd.Flags().IntVarP(&flagValue, \"intf\", \"i\", -1, \"\")\n\n\t// With short flag.\n\t_, err := executeCommand(rootCmd, \"-i7\", \"child\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\tif flagValue != 7 {\n\t\tt.Errorf(\"Expected flag value: %v, got %v\", 7, flagValue)\n\t}\n\n\t// With long flag.\n\t_, err = executeCommand(rootCmd, \"--intf=8\", \"child\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\tif flagValue != 8 {\n\t\tt.Errorf(\"Expected flag value: %v, got %v\", 9, flagValue)\n\t}\n}\n\nfunc TestStripFlags(t *testing.T) {\n\ttests := []struct {\n\t\tinput  []string\n\t\toutput []string\n\t}{\n\t\t{\n\t\t\t[]string{\"foo\", \"bar\"},\n\t\t\t[]string{\"foo\", \"bar\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"foo\", \"--str\", \"-s\"},\n\t\t\t[]string{\"foo\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"-s\", \"foo\", \"--str\", \"bar\"},\n\t\t\t[]string{},\n\t\t},\n\t\t{\n\t\t\t[]string{\"-i10\", \"echo\"},\n\t\t\t[]string{\"echo\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"-i=10\", \"echo\"},\n\t\t\t[]string{\"echo\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"--int=100\", \"echo\"},\n\t\t\t[]string{\"echo\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"-ib\", \"echo\", \"-sfoo\", \"baz\"},\n\t\t\t[]string{\"echo\", \"baz\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"-i=baz\", \"bar\", \"-i\", \"foo\", \"blah\"},\n\t\t\t[]string{\"bar\", \"blah\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"--int=baz\", \"-sbar\", \"-i\", \"foo\", \"blah\"},\n\t\t\t[]string{\"blah\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"--bool\", \"bar\", \"-i\", \"foo\", \"blah\"},\n\t\t\t[]string{\"bar\", \"blah\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"-b\", \"bar\", \"-i\", \"foo\", \"blah\"},\n\t\t\t[]string{\"bar\", \"blah\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"--persist\", \"bar\"},\n\t\t\t[]string{\"bar\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"-p\", \"bar\"},\n\t\t\t[]string{\"bar\"},\n\t\t},\n\t}\n\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\tc.PersistentFlags().BoolP(\"persist\", \"p\", false, \"\")\n\tc.Flags().IntP(\"int\", \"i\", -1, \"\")\n\tc.Flags().StringP(\"str\", \"s\", \"\", \"\")\n\tc.Flags().BoolP(\"bool\", \"b\", false, \"\")\n\n\tfor i, test := range tests {\n\t\tgot := stripFlags(test.input, c)\n\t\tif !reflect.DeepEqual(test.output, got) {\n\t\t\tt.Errorf(\"(%v) Expected: %v, got: %v\", i, test.output, got)\n\t\t}\n\t}\n}\n\nfunc TestDisableFlagParsing(t *testing.T) {\n\tvar cArgs []string\n\tc := &Command{\n\t\tUse:                \"c\",\n\t\tDisableFlagParsing: true,\n\t\tRun: func(_ *Command, args []string) {\n\t\t\tcArgs = args\n\t\t},\n\t}\n\n\targs := []string{\"cmd\", \"-v\", \"-race\", \"-file\", \"foo.go\"}\n\toutput, err := executeCommand(c, args...)\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tif !reflect.DeepEqual(args, cArgs) {\n\t\tt.Errorf(\"Expected: %v, got: %v\", args, cArgs)\n\t}\n}\n\nfunc TestPersistentFlagsOnSameCommand(t *testing.T) {\n\tvar rootCmdArgs []string\n\trootCmd := &Command{\n\t\tUse:  \"root\",\n\t\tArgs: ArbitraryArgs,\n\t\tRun:  func(_ *Command, args []string) { rootCmdArgs = args },\n\t}\n\n\tvar flagValue int\n\trootCmd.PersistentFlags().IntVarP(&flagValue, \"intf\", \"i\", -1, \"\")\n\n\toutput, err := executeCommand(rootCmd, \"-i7\", \"one\", \"two\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tgot := strings.Join(rootCmdArgs, \" \")\n\tif got != onetwo {\n\t\tt.Errorf(\"rootCmdArgs expected: %q, got %q\", onetwo, got)\n\t}\n\tif flagValue != 7 {\n\t\tt.Errorf(\"flagValue expected: %v, got %v\", 7, flagValue)\n\t}\n}\n\n// TestEmptyInputs checks,\n// if flags correctly parsed with blank strings in args.\nfunc TestEmptyInputs(t *testing.T) {\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\n\tvar flagValue int\n\tc.Flags().IntVarP(&flagValue, \"intf\", \"i\", -1, \"\")\n\n\toutput, err := executeCommand(c, \"\", \"-i7\", \"\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tif flagValue != 7 {\n\t\tt.Errorf(\"flagValue expected: %v, got %v\", 7, flagValue)\n\t}\n}\n\nfunc TestChildFlagShadowsParentPersistentFlag(t *testing.T) {\n\tparent := &Command{Use: \"parent\", Run: emptyRun}\n\tchild := &Command{Use: \"child\", Run: emptyRun}\n\n\tparent.PersistentFlags().Bool(\"boolf\", false, \"\")\n\tparent.PersistentFlags().Int(\"intf\", -1, \"\")\n\tchild.Flags().String(\"strf\", \"\", \"\")\n\tchild.Flags().Int(\"intf\", -1, \"\")\n\n\tparent.AddCommand(child)\n\n\tchildInherited := child.InheritedFlags()\n\tchildLocal := child.LocalFlags()\n\n\tif childLocal.Lookup(\"strf\") == nil {\n\t\tt.Error(`LocalFlags expected to contain \"strf\", got \"nil\"`)\n\t}\n\tif childInherited.Lookup(\"boolf\") == nil {\n\t\tt.Error(`InheritedFlags expected to contain \"boolf\", got \"nil\"`)\n\t}\n\n\tif childInherited.Lookup(\"intf\") != nil {\n\t\tt.Errorf(`InheritedFlags should not contain shadowed flag \"intf\"`)\n\t}\n\tif childLocal.Lookup(\"intf\") == nil {\n\t\tt.Error(`LocalFlags expected to contain \"intf\", got \"nil\"`)\n\t}\n}\n\nfunc TestPersistentFlagsOnChild(t *testing.T) {\n\tvar childCmdArgs []string\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchildCmd := &Command{\n\t\tUse:  \"child\",\n\t\tArgs: ArbitraryArgs,\n\t\tRun:  func(_ *Command, args []string) { childCmdArgs = args },\n\t}\n\trootCmd.AddCommand(childCmd)\n\n\tvar parentFlagValue int\n\tvar childFlagValue int\n\trootCmd.PersistentFlags().IntVarP(&parentFlagValue, \"parentf\", \"p\", -1, \"\")\n\tchildCmd.Flags().IntVarP(&childFlagValue, \"childf\", \"c\", -1, \"\")\n\n\toutput, err := executeCommand(rootCmd, \"child\", \"-c7\", \"-p8\", \"one\", \"two\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tgot := strings.Join(childCmdArgs, \" \")\n\tif got != onetwo {\n\t\tt.Errorf(\"rootCmdArgs expected: %q, got: %q\", onetwo, got)\n\t}\n\tif parentFlagValue != 8 {\n\t\tt.Errorf(\"parentFlagValue expected: %v, got %v\", 8, parentFlagValue)\n\t}\n\tif childFlagValue != 7 {\n\t\tt.Errorf(\"childFlagValue expected: %v, got %v\", 7, childFlagValue)\n\t}\n}\n\nfunc TestRequiredFlags(t *testing.T) {\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\tc.Flags().String(\"foo1\", \"\", \"\")\n\tassertNoErr(t, c.MarkFlagRequired(\"foo1\"))\n\tc.Flags().String(\"foo2\", \"\", \"\")\n\tassertNoErr(t, c.MarkFlagRequired(\"foo2\"))\n\tc.Flags().String(\"bar\", \"\", \"\")\n\n\texpected := fmt.Sprintf(\"required flag(s) %q, %q not set\", \"foo1\", \"foo2\")\n\n\t_, err := executeCommand(c)\n\tgot := err.Error()\n\n\tif got != expected {\n\t\tt.Errorf(\"Expected error: %q, got: %q\", expected, got)\n\t}\n}\n\nfunc TestPersistentRequiredFlags(t *testing.T) {\n\tparent := &Command{Use: \"parent\", Run: emptyRun}\n\tparent.PersistentFlags().String(\"foo1\", \"\", \"\")\n\tassertNoErr(t, parent.MarkPersistentFlagRequired(\"foo1\"))\n\tparent.PersistentFlags().String(\"foo2\", \"\", \"\")\n\tassertNoErr(t, parent.MarkPersistentFlagRequired(\"foo2\"))\n\tparent.Flags().String(\"foo3\", \"\", \"\")\n\n\tchild := &Command{Use: \"child\", Run: emptyRun}\n\tchild.Flags().String(\"bar1\", \"\", \"\")\n\tassertNoErr(t, child.MarkFlagRequired(\"bar1\"))\n\tchild.Flags().String(\"bar2\", \"\", \"\")\n\tassertNoErr(t, child.MarkFlagRequired(\"bar2\"))\n\tchild.Flags().String(\"bar3\", \"\", \"\")\n\n\tparent.AddCommand(child)\n\n\texpected := fmt.Sprintf(\"required flag(s) %q, %q, %q, %q not set\", \"bar1\", \"bar2\", \"foo1\", \"foo2\")\n\n\t_, err := executeCommand(parent, \"child\")\n\tif err.Error() != expected {\n\t\tt.Errorf(\"Expected %q, got %q\", expected, err.Error())\n\t}\n}\n\nfunc TestPersistentRequiredFlagsWithDisableFlagParsing(t *testing.T) {\n\t// Make sure a required persistent flag does not break\n\t// commands that disable flag parsing\n\n\tparent := &Command{Use: \"parent\", Run: emptyRun}\n\tparent.PersistentFlags().Bool(\"foo\", false, \"\")\n\tflag := parent.PersistentFlags().Lookup(\"foo\")\n\tassertNoErr(t, parent.MarkPersistentFlagRequired(\"foo\"))\n\n\tchild := &Command{Use: \"child\", Run: emptyRun}\n\tchild.DisableFlagParsing = true\n\n\tparent.AddCommand(child)\n\n\tif _, err := executeCommand(parent, \"--foo\", \"child\"); err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\t// Reset the flag or else it will remember the state from the previous command\n\tflag.Changed = false\n\tif _, err := executeCommand(parent, \"child\", \"--foo\"); err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\t// Reset the flag or else it will remember the state from the previous command\n\tflag.Changed = false\n\tif _, err := executeCommand(parent, \"child\"); err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n}\n\nfunc TestInitHelpFlagMergesFlags(t *testing.T) {\n\tusage := \"custom flag\"\n\trootCmd := &Command{Use: \"root\"}\n\trootCmd.PersistentFlags().Bool(\"help\", false, \"custom flag\")\n\tchildCmd := &Command{Use: \"child\"}\n\trootCmd.AddCommand(childCmd)\n\n\tchildCmd.InitDefaultHelpFlag()\n\tgot := childCmd.Flags().Lookup(\"help\").Usage\n\tif got != usage {\n\t\tt.Errorf(\"Expected the help flag from the root command with usage: %v\\nGot the default with usage: %v\", usage, got)\n\t}\n}\n\nfunc TestHelpCommandExecuted(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Long: \"Long description\", Run: emptyRun}\n\trootCmd.AddCommand(&Command{Use: \"child\", Run: emptyRun})\n\n\toutput, err := executeCommand(rootCmd, \"help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, rootCmd.Long)\n}\n\nfunc TestHelpCommandExecutedOnChild(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchildCmd := &Command{Use: \"child\", Long: \"Long description\", Run: emptyRun}\n\trootCmd.AddCommand(childCmd)\n\n\toutput, err := executeCommand(rootCmd, \"help\", \"child\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, childCmd.Long)\n}\n\nfunc TestHelpCommandExecutedOnChildWithFlagThatShadowsParentFlag(t *testing.T) {\n\tparent := &Command{Use: \"parent\", Run: emptyRun}\n\tchild := &Command{Use: \"child\", Run: emptyRun}\n\tparent.AddCommand(child)\n\n\tparent.PersistentFlags().Bool(\"foo\", false, \"parent foo usage\")\n\tparent.PersistentFlags().Bool(\"bar\", false, \"parent bar usage\")\n\tchild.Flags().Bool(\"foo\", false, \"child foo usage\") // This shadows parent's foo flag\n\tchild.Flags().Bool(\"baz\", false, \"child baz usage\")\n\n\tgot, err := executeCommand(parent, \"help\", \"child\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := `Usage:\n  parent child [flags]\n\nFlags:\n      --baz    child baz usage\n      --foo    child foo usage\n  -h, --help   help for child\n\nGlobal Flags:\n      --bar   parent bar usage\n`\n\n\tif got != expected {\n\t\tt.Errorf(\"Help text mismatch.\\nExpected:\\n%s\\n\\nGot:\\n%s\\n\", expected, got)\n\t}\n}\n\nfunc TestSetHelpCommand(t *testing.T) {\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\tc.AddCommand(&Command{Use: \"empty\", Run: emptyRun})\n\n\texpected := \"WORKS\"\n\tc.SetHelpCommand(&Command{\n\t\tUse:   \"help [command]\",\n\t\tShort: \"Help about any command\",\n\t\tLong: `Help provides help for any command in the application.\n\tSimply type ` + c.Name() + ` help [path to command] for full details.`,\n\t\tRun: func(c *Command, _ []string) { c.Print(expected) },\n\t})\n\n\tgot, err := executeCommand(c, \"help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tif got != expected {\n\t\tt.Errorf(\"Expected to contain %q, got %q\", expected, got)\n\t}\n}\n\nfunc TestSetHelpTemplate(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchildCmd := &Command{Use: \"child\", Run: emptyRun}\n\trootCmd.AddCommand(childCmd)\n\n\trootCmd.SetHelpTemplate(\"WORKS {{.UseLine}}\")\n\n\t// Call the help on the root command and check the new template is used\n\tgot, err := executeCommand(rootCmd, \"--help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := \"WORKS \" + rootCmd.UseLine()\n\tif got != expected {\n\t\tt.Errorf(\"Expected %q, got %q\", expected, got)\n\t}\n\n\t// Call the help on the child command and check\n\t// the new template is inherited from the parent\n\tgot, err = executeCommand(rootCmd, \"child\", \"--help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = \"WORKS \" + childCmd.UseLine()\n\tif got != expected {\n\t\tt.Errorf(\"Expected %q, got %q\", expected, got)\n\t}\n\n\t// Reset the root command help template and make sure\n\t// it falls back to the default\n\trootCmd.SetHelpTemplate(\"\")\n\tgot, err = executeCommand(rootCmd, \"--help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tif !strings.Contains(got, \"Usage:\") {\n\t\tt.Errorf(\"Expected to contain %q, got %q\", \"Usage:\", got)\n\t}\n}\n\nfunc TestHelpFlagExecuted(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Long: \"Long description\", Run: emptyRun}\n\n\toutput, err := executeCommand(rootCmd, \"--help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, rootCmd.Long)\n}\n\nfunc TestHelpFlagExecutedOnChild(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchildCmd := &Command{Use: \"child\", Long: \"Long description\", Run: emptyRun}\n\trootCmd.AddCommand(childCmd)\n\n\toutput, err := executeCommand(rootCmd, \"child\", \"--help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, childCmd.Long)\n}\n\n// TestHelpFlagInHelp checks,\n// if '--help' flag is shown in help for child (executing `parent help child`),\n// that has no other flags.\n// Related to https://github.com/spf13/cobra/issues/302.\nfunc TestHelpFlagInHelp(t *testing.T) {\n\tparentCmd := &Command{Use: \"parent\", Run: func(*Command, []string) {}}\n\n\tchildCmd := &Command{Use: \"child\", Run: func(*Command, []string) {}}\n\tparentCmd.AddCommand(childCmd)\n\n\toutput, err := executeCommand(parentCmd, \"help\", \"child\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, \"[flags]\")\n}\n\nfunc TestFlagsInUsage(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: func(*Command, []string) {}}\n\toutput, err := executeCommand(rootCmd, \"--help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, \"[flags]\")\n}\n\nfunc TestHelpExecutedOnNonRunnableChild(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchildCmd := &Command{Use: \"child\", Long: \"Long description\"}\n\trootCmd.AddCommand(childCmd)\n\n\toutput, err := executeCommand(rootCmd, \"child\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, childCmd.Long)\n}\n\nfunc TestSetUsageTemplate(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchildCmd := &Command{Use: \"child\", Run: emptyRun}\n\trootCmd.AddCommand(childCmd)\n\n\trootCmd.SetUsageTemplate(\"WORKS {{.UseLine}}\")\n\n\t// Trigger the usage on the root command and check the new template is used\n\tgot, err := executeCommand(rootCmd, \"--invalid\")\n\tif err == nil {\n\t\tt.Errorf(\"Expected error but did not get one\")\n\t}\n\n\texpected := \"WORKS \" + rootCmd.UseLine()\n\tcheckStringContains(t, got, expected)\n\n\t// Trigger the usage on the child command and check\n\t// the new template is inherited from the parent\n\tgot, err = executeCommand(rootCmd, \"child\", \"--invalid\")\n\tif err == nil {\n\t\tt.Errorf(\"Expected error but did not get one\")\n\t}\n\n\texpected = \"WORKS \" + childCmd.UseLine()\n\tcheckStringContains(t, got, expected)\n\n\t// Reset the root command usage template and make sure\n\t// it falls back to the default\n\trootCmd.SetUsageTemplate(\"\")\n\tgot, err = executeCommand(rootCmd, \"--invalid\")\n\tif err == nil {\n\t\tt.Errorf(\"Expected error but did not get one\")\n\t}\n\n\tif !strings.Contains(got, \"Usage:\") {\n\t\tt.Errorf(\"Expected to contain %q, got %q\", \"Usage:\", got)\n\t}\n}\n\nfunc TestVersionFlagExecuted(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Version: \"1.0.0\", Run: emptyRun}\n\n\toutput, err := executeCommand(rootCmd, \"--version\", \"arg1\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, \"root version 1.0.0\")\n}\n\nfunc TestVersionFlagExecutedDiplayName(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse:     \"kubectl-plugin\",\n\t\tVersion: \"1.0.0\",\n\t\tAnnotations: map[string]string{\n\t\t\tCommandDisplayNameAnnotation: \"kubectl plugin\",\n\t\t},\n\t\tRun: emptyRun,\n\t}\n\n\toutput, err := executeCommand(rootCmd, \"--version\", \"arg1\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, \"kubectl plugin version 1.0.0\")\n}\n\nfunc TestVersionFlagExecutedWithNoName(t *testing.T) {\n\trootCmd := &Command{Version: \"1.0.0\", Run: emptyRun}\n\n\toutput, err := executeCommand(rootCmd, \"--version\", \"arg1\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, \"version 1.0.0\")\n}\n\nfunc TestShortAndLongVersionFlagInHelp(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Version: \"1.0.0\", Run: emptyRun}\n\n\toutput, err := executeCommand(rootCmd, \"--help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, \"-v, --version\")\n}\n\nfunc TestLongVersionFlagOnlyInHelpWhenShortPredefined(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Version: \"1.0.0\", Run: emptyRun}\n\trootCmd.Flags().StringP(\"foo\", \"v\", \"\", \"not a version flag\")\n\n\toutput, err := executeCommand(rootCmd, \"--help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringOmits(t, output, \"-v, --version\")\n\tcheckStringContains(t, output, \"--version\")\n}\n\nfunc TestShorthandVersionFlagExecuted(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Version: \"1.0.0\", Run: emptyRun}\n\n\toutput, err := executeCommand(rootCmd, \"-v\", \"arg1\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, \"root version 1.0.0\")\n}\n\nfunc TestVersionTemplate(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Version: \"1.0.0\", Run: emptyRun}\n\trootCmd.SetVersionTemplate(`customized version: {{.Version}}`)\n\n\toutput, err := executeCommand(rootCmd, \"--version\", \"arg1\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, \"customized version: 1.0.0\")\n}\n\nfunc TestShorthandVersionTemplate(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Version: \"1.0.0\", Run: emptyRun}\n\trootCmd.SetVersionTemplate(`customized version: {{.Version}}`)\n\n\toutput, err := executeCommand(rootCmd, \"-v\", \"arg1\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, \"customized version: 1.0.0\")\n}\n\nfunc TestRootErrPrefixExecutedOnSubcommand(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\trootCmd.SetErrPrefix(\"root error prefix:\")\n\trootCmd.AddCommand(&Command{Use: \"sub\", Run: emptyRun})\n\n\toutput, err := executeCommand(rootCmd, \"sub\", \"--unknown-flag\")\n\tif err == nil {\n\t\tt.Errorf(\"Expected error\")\n\t}\n\n\tcheckStringContains(t, output, \"root error prefix: unknown flag: --unknown-flag\")\n}\n\nfunc TestRootAndSubErrPrefix(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tsubCmd := &Command{Use: \"sub\", Run: emptyRun}\n\trootCmd.AddCommand(subCmd)\n\trootCmd.SetErrPrefix(\"root error prefix:\")\n\tsubCmd.SetErrPrefix(\"sub error prefix:\")\n\n\tif output, err := executeCommand(rootCmd, \"--unknown-root-flag\"); err == nil {\n\t\tt.Errorf(\"Expected error\")\n\t} else {\n\t\tcheckStringContains(t, output, \"root error prefix: unknown flag: --unknown-root-flag\")\n\t}\n\n\tif output, err := executeCommand(rootCmd, \"sub\", \"--unknown-sub-flag\"); err == nil {\n\t\tt.Errorf(\"Expected error\")\n\t} else {\n\t\tcheckStringContains(t, output, \"sub error prefix: unknown flag: --unknown-sub-flag\")\n\t}\n}\n\nfunc TestVersionFlagExecutedOnSubcommand(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Version: \"1.0.0\"}\n\trootCmd.AddCommand(&Command{Use: \"sub\", Run: emptyRun})\n\n\toutput, err := executeCommand(rootCmd, \"--version\", \"sub\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, \"root version 1.0.0\")\n}\n\nfunc TestShorthandVersionFlagExecutedOnSubcommand(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Version: \"1.0.0\"}\n\trootCmd.AddCommand(&Command{Use: \"sub\", Run: emptyRun})\n\n\toutput, err := executeCommand(rootCmd, \"-v\", \"sub\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, \"root version 1.0.0\")\n}\n\nfunc TestVersionFlagOnlyAddedToRoot(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Version: \"1.0.0\", Run: emptyRun}\n\trootCmd.AddCommand(&Command{Use: \"sub\", Run: emptyRun})\n\n\t_, err := executeCommand(rootCmd, \"sub\", \"--version\")\n\tif err == nil {\n\t\tt.Errorf(\"Expected error\")\n\t}\n\n\tcheckStringContains(t, err.Error(), \"unknown flag: --version\")\n}\n\nfunc TestShortVersionFlagOnlyAddedToRoot(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Version: \"1.0.0\", Run: emptyRun}\n\trootCmd.AddCommand(&Command{Use: \"sub\", Run: emptyRun})\n\n\t_, err := executeCommand(rootCmd, \"sub\", \"-v\")\n\tif err == nil {\n\t\tt.Errorf(\"Expected error\")\n\t}\n\n\tcheckStringContains(t, err.Error(), \"unknown shorthand flag: 'v' in -v\")\n}\n\nfunc TestVersionFlagOnlyExistsIfVersionNonEmpty(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\n\t_, err := executeCommand(rootCmd, \"--version\")\n\tif err == nil {\n\t\tt.Errorf(\"Expected error\")\n\t}\n\tcheckStringContains(t, err.Error(), \"unknown flag: --version\")\n}\n\nfunc TestShorthandVersionFlagOnlyExistsIfVersionNonEmpty(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\n\t_, err := executeCommand(rootCmd, \"-v\")\n\tif err == nil {\n\t\tt.Errorf(\"Expected error\")\n\t}\n\tcheckStringContains(t, err.Error(), \"unknown shorthand flag: 'v' in -v\")\n}\n\nfunc TestShorthandVersionFlagOnlyAddedIfShorthandNotDefined(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun, Version: \"1.2.3\"}\n\trootCmd.Flags().StringP(\"notversion\", \"v\", \"\", \"not a version flag\")\n\n\t_, err := executeCommand(rootCmd, \"-v\")\n\tif err == nil {\n\t\tt.Errorf(\"Expected error\")\n\t}\n\tcheck(t, rootCmd.Flags().ShorthandLookup(\"v\").Name, \"notversion\")\n\tcheckStringContains(t, err.Error(), \"flag needs an argument: 'v' in -v\")\n}\n\nfunc TestShorthandVersionFlagOnlyAddedIfVersionNotDefined(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun, Version: \"1.2.3\"}\n\trootCmd.Flags().Bool(\"version\", false, \"a different kind of version flag\")\n\n\t_, err := executeCommand(rootCmd, \"-v\")\n\tif err == nil {\n\t\tt.Errorf(\"Expected error\")\n\t}\n\tcheckStringContains(t, err.Error(), \"unknown shorthand flag: 'v' in -v\")\n}\n\nfunc TestUsageIsNotPrintedTwice(t *testing.T) {\n\tvar cmd = &Command{Use: \"root\"}\n\tvar sub = &Command{Use: \"sub\"}\n\tcmd.AddCommand(sub)\n\n\toutput, _ := executeCommand(cmd, \"\")\n\tif strings.Count(output, \"Usage:\") != 1 {\n\t\tt.Error(\"Usage output is not printed exactly once\")\n\t}\n}\n\nfunc TestVisitParents(t *testing.T) {\n\tc := &Command{Use: \"app\"}\n\tsub := &Command{Use: \"sub\"}\n\tdsub := &Command{Use: \"dsub\"}\n\tsub.AddCommand(dsub)\n\tc.AddCommand(sub)\n\n\ttotal := 0\n\tadd := func(x *Command) {\n\t\ttotal++\n\t}\n\tsub.VisitParents(add)\n\tif total != 1 {\n\t\tt.Errorf(\"Should have visited 1 parent but visited %d\", total)\n\t}\n\n\ttotal = 0\n\tdsub.VisitParents(add)\n\tif total != 2 {\n\t\tt.Errorf(\"Should have visited 2 parents but visited %d\", total)\n\t}\n\n\ttotal = 0\n\tc.VisitParents(add)\n\tif total != 0 {\n\t\tt.Errorf(\"Should have visited no parents but visited %d\", total)\n\t}\n}\n\nfunc TestSuggestions(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\ttimesCmd := &Command{\n\t\tUse:        \"times\",\n\t\tSuggestFor: []string{\"counts\"},\n\t\tRun:        emptyRun,\n\t}\n\trootCmd.AddCommand(timesCmd)\n\n\ttemplateWithSuggestions := \"Error: unknown command \\\"%s\\\" for \\\"root\\\"\\n\\nDid you mean this?\\n\\t%s\\n\\nRun 'root --help' for usage.\\n\"\n\ttemplateWithoutSuggestions := \"Error: unknown command \\\"%s\\\" for \\\"root\\\"\\nRun 'root --help' for usage.\\n\"\n\n\ttests := map[string]string{\n\t\t\"time\":     \"times\",\n\t\t\"tiems\":    \"times\",\n\t\t\"tims\":     \"times\",\n\t\t\"timeS\":    \"times\",\n\t\t\"rimes\":    \"times\",\n\t\t\"ti\":       \"times\",\n\t\t\"t\":        \"times\",\n\t\t\"timely\":   \"times\",\n\t\t\"ri\":       \"\",\n\t\t\"timezone\": \"\",\n\t\t\"foo\":      \"\",\n\t\t\"counts\":   \"times\",\n\t}\n\n\tfor typo, suggestion := range tests {\n\t\tfor _, suggestionsDisabled := range []bool{true, false} {\n\t\t\trootCmd.DisableSuggestions = suggestionsDisabled\n\n\t\t\tvar expected string\n\t\t\toutput, _ := executeCommand(rootCmd, typo)\n\n\t\t\tif suggestion == \"\" || suggestionsDisabled {\n\t\t\t\texpected = fmt.Sprintf(templateWithoutSuggestions, typo)\n\t\t\t} else {\n\t\t\t\texpected = fmt.Sprintf(templateWithSuggestions, typo, suggestion)\n\t\t\t}\n\n\t\t\tif output != expected {\n\t\t\t\tt.Errorf(\"Unexpected response.\\nExpected:\\n %q\\nGot:\\n %q\\n\", expected, output)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestCaseInsensitive(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchildCmd := &Command{Use: \"child\", Run: emptyRun, Aliases: []string{\"alternative\"}}\n\tgranchildCmd := &Command{Use: \"GRANDCHILD\", Run: emptyRun, Aliases: []string{\"ALIAS\"}}\n\n\tchildCmd.AddCommand(granchildCmd)\n\trootCmd.AddCommand(childCmd)\n\n\ttests := []struct {\n\t\targs                []string\n\t\tfailWithoutEnabling bool\n\t}{\n\t\t{\n\t\t\targs:                []string{\"child\"},\n\t\t\tfailWithoutEnabling: false,\n\t\t},\n\t\t{\n\t\t\targs:                []string{\"CHILD\"},\n\t\t\tfailWithoutEnabling: true,\n\t\t},\n\t\t{\n\t\t\targs:                []string{\"chILD\"},\n\t\t\tfailWithoutEnabling: true,\n\t\t},\n\t\t{\n\t\t\targs:                []string{\"CHIld\"},\n\t\t\tfailWithoutEnabling: true,\n\t\t},\n\t\t{\n\t\t\targs:                []string{\"alternative\"},\n\t\t\tfailWithoutEnabling: false,\n\t\t},\n\t\t{\n\t\t\targs:                []string{\"ALTERNATIVE\"},\n\t\t\tfailWithoutEnabling: true,\n\t\t},\n\t\t{\n\t\t\targs:                []string{\"ALTernatIVE\"},\n\t\t\tfailWithoutEnabling: true,\n\t\t},\n\t\t{\n\t\t\targs:                []string{\"alternatiVE\"},\n\t\t\tfailWithoutEnabling: true,\n\t\t},\n\t\t{\n\t\t\targs:                []string{\"child\", \"GRANDCHILD\"},\n\t\t\tfailWithoutEnabling: false,\n\t\t},\n\t\t{\n\t\t\targs:                []string{\"child\", \"grandchild\"},\n\t\t\tfailWithoutEnabling: true,\n\t\t},\n\t\t{\n\t\t\targs:                []string{\"CHIld\", \"GRANdchild\"},\n\t\t\tfailWithoutEnabling: true,\n\t\t},\n\t\t{\n\t\t\targs:                []string{\"alternative\", \"ALIAS\"},\n\t\t\tfailWithoutEnabling: false,\n\t\t},\n\t\t{\n\t\t\targs:                []string{\"alternative\", \"alias\"},\n\t\t\tfailWithoutEnabling: true,\n\t\t},\n\t\t{\n\t\t\targs:                []string{\"CHILD\", \"alias\"},\n\t\t\tfailWithoutEnabling: true,\n\t\t},\n\t\t{\n\t\t\targs:                []string{\"CHIld\", \"aliAS\"},\n\t\t\tfailWithoutEnabling: true,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tfor _, enableCaseInsensitivity := range []bool{true, false} {\n\t\t\tEnableCaseInsensitive = enableCaseInsensitivity\n\n\t\t\toutput, err := executeCommand(rootCmd, test.args...)\n\t\t\texpectedFailure := test.failWithoutEnabling && !enableCaseInsensitivity\n\n\t\t\tif !expectedFailure && output != \"\" {\n\t\t\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t\t\t}\n\t\t\tif !expectedFailure && err != nil {\n\t\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tEnableCaseInsensitive = defaultCaseInsensitive\n}\n\n// This test make sure we keep backwards-compatibility with respect\n// to command names case sensitivity behavior.\nfunc TestCaseSensitivityBackwardCompatibility(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchildCmd := &Command{Use: \"child\", Run: emptyRun}\n\n\trootCmd.AddCommand(childCmd)\n\t_, err := executeCommand(rootCmd, strings.ToUpper(childCmd.Use))\n\tif err == nil {\n\t\tt.Error(\"Expected error on calling a command in upper case while command names are case sensitive. Got nil.\")\n\t}\n\n}\n\nfunc TestRemoveCommand(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchildCmd := &Command{Use: \"child\", Run: emptyRun}\n\trootCmd.AddCommand(childCmd)\n\trootCmd.RemoveCommand(childCmd)\n\n\t_, err := executeCommand(rootCmd, \"child\")\n\tif err == nil {\n\t\tt.Error(\"Expected error on calling removed command. Got nil.\")\n\t}\n}\n\nfunc TestReplaceCommandWithRemove(t *testing.T) {\n\tchildUsed := 0\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchild1Cmd := &Command{\n\t\tUse: \"child\",\n\t\tRun: func(*Command, []string) { childUsed = 1 },\n\t}\n\tchild2Cmd := &Command{\n\t\tUse: \"child\",\n\t\tRun: func(*Command, []string) { childUsed = 2 },\n\t}\n\trootCmd.AddCommand(child1Cmd)\n\trootCmd.RemoveCommand(child1Cmd)\n\trootCmd.AddCommand(child2Cmd)\n\n\toutput, err := executeCommand(rootCmd, \"child\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tif childUsed == 1 {\n\t\tt.Error(\"Removed command shouldn't be called\")\n\t}\n\tif childUsed != 2 {\n\t\tt.Error(\"Replacing command should have been called but didn't\")\n\t}\n}\n\nfunc TestDeprecatedCommand(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tdeprecatedCmd := &Command{\n\t\tUse:        \"deprecated\",\n\t\tDeprecated: \"This command is deprecated\",\n\t\tRun:        emptyRun,\n\t}\n\trootCmd.AddCommand(deprecatedCmd)\n\n\toutput, err := executeCommand(rootCmd, \"deprecated\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, deprecatedCmd.Deprecated)\n}\n\nfunc TestHooks(t *testing.T) {\n\tvar (\n\t\tpersPreArgs  string\n\t\tpreArgs      string\n\t\trunArgs      string\n\t\tpostArgs     string\n\t\tpersPostArgs string\n\t)\n\n\tc := &Command{\n\t\tUse: \"c\",\n\t\tPersistentPreRun: func(_ *Command, args []string) {\n\t\t\tpersPreArgs = strings.Join(args, \" \")\n\t\t},\n\t\tPreRun: func(_ *Command, args []string) {\n\t\t\tpreArgs = strings.Join(args, \" \")\n\t\t},\n\t\tRun: func(_ *Command, args []string) {\n\t\t\trunArgs = strings.Join(args, \" \")\n\t\t},\n\t\tPostRun: func(_ *Command, args []string) {\n\t\t\tpostArgs = strings.Join(args, \" \")\n\t\t},\n\t\tPersistentPostRun: func(_ *Command, args []string) {\n\t\t\tpersPostArgs = strings.Join(args, \" \")\n\t\t},\n\t}\n\n\toutput, err := executeCommand(c, \"one\", \"two\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tfor _, v := range []struct {\n\t\tname string\n\t\tgot  string\n\t}{\n\t\t{\"persPreArgs\", persPreArgs},\n\t\t{\"preArgs\", preArgs},\n\t\t{\"runArgs\", runArgs},\n\t\t{\"postArgs\", postArgs},\n\t\t{\"persPostArgs\", persPostArgs},\n\t} {\n\t\tif v.got != onetwo {\n\t\t\tt.Errorf(\"Expected %s %q, got %q\", v.name, onetwo, v.got)\n\t\t}\n\t}\n}\n\nfunc TestPersistentHooks(t *testing.T) {\n\tEnableTraverseRunHooks = true\n\ttestPersistentHooks(t, []string{\n\t\t\"parent PersistentPreRun\",\n\t\t\"child PersistentPreRun\",\n\t\t\"child PreRun\",\n\t\t\"child Run\",\n\t\t\"child PostRun\",\n\t\t\"child PersistentPostRun\",\n\t\t\"parent PersistentPostRun\",\n\t})\n\n\tEnableTraverseRunHooks = false\n\ttestPersistentHooks(t, []string{\n\t\t\"child PersistentPreRun\",\n\t\t\"child PreRun\",\n\t\t\"child Run\",\n\t\t\"child PostRun\",\n\t\t\"child PersistentPostRun\",\n\t})\n}\n\nfunc testPersistentHooks(t *testing.T, expectedHookRunOrder []string) {\n\tvar hookRunOrder []string\n\n\tvalidateHook := func(args []string, hookName string) {\n\t\thookRunOrder = append(hookRunOrder, hookName)\n\t\tgot := strings.Join(args, \" \")\n\t\tif onetwo != got {\n\t\t\tt.Errorf(\"Expected %s %q, got %q\", hookName, onetwo, got)\n\t\t}\n\t}\n\n\tparentCmd := &Command{\n\t\tUse: \"parent\",\n\t\tPersistentPreRun: func(_ *Command, args []string) {\n\t\t\tvalidateHook(args, \"parent PersistentPreRun\")\n\t\t},\n\t\tPreRun: func(_ *Command, args []string) {\n\t\t\tvalidateHook(args, \"parent PreRun\")\n\t\t},\n\t\tRun: func(_ *Command, args []string) {\n\t\t\tvalidateHook(args, \"parent Run\")\n\t\t},\n\t\tPostRun: func(_ *Command, args []string) {\n\t\t\tvalidateHook(args, \"parent PostRun\")\n\t\t},\n\t\tPersistentPostRun: func(_ *Command, args []string) {\n\t\t\tvalidateHook(args, \"parent PersistentPostRun\")\n\t\t},\n\t}\n\n\tchildCmd := &Command{\n\t\tUse: \"child\",\n\t\tPersistentPreRun: func(_ *Command, args []string) {\n\t\t\tvalidateHook(args, \"child PersistentPreRun\")\n\t\t},\n\t\tPreRun: func(_ *Command, args []string) {\n\t\t\tvalidateHook(args, \"child PreRun\")\n\t\t},\n\t\tRun: func(_ *Command, args []string) {\n\t\t\tvalidateHook(args, \"child Run\")\n\t\t},\n\t\tPostRun: func(_ *Command, args []string) {\n\t\t\tvalidateHook(args, \"child PostRun\")\n\t\t},\n\t\tPersistentPostRun: func(_ *Command, args []string) {\n\t\t\tvalidateHook(args, \"child PersistentPostRun\")\n\t\t},\n\t}\n\tparentCmd.AddCommand(childCmd)\n\n\toutput, err := executeCommand(parentCmd, \"child\", \"one\", \"two\")\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tfor idx, exp := range expectedHookRunOrder {\n\t\tif len(hookRunOrder) > idx {\n\t\t\tif act := hookRunOrder[idx]; act != exp {\n\t\t\t\tt.Errorf(\"Expected %q at %d, got %q\", exp, idx, act)\n\t\t\t}\n\t\t} else {\n\t\t\tt.Errorf(\"Expected %q at %d, got nothing\", exp, idx)\n\t\t}\n\t}\n}\n\n// Related to https://github.com/spf13/cobra/issues/521.\nfunc TestGlobalNormFuncPropagation(t *testing.T) {\n\tnormFunc := func(f *pflag.FlagSet, name string) pflag.NormalizedName {\n\t\treturn pflag.NormalizedName(name)\n\t}\n\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchildCmd := &Command{Use: \"child\", Run: emptyRun}\n\trootCmd.AddCommand(childCmd)\n\n\trootCmd.SetGlobalNormalizationFunc(normFunc)\n\tif reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() {\n\t\tt.Error(\"rootCmd seems to have a wrong normalization function\")\n\t}\n\n\tif reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(childCmd.GlobalNormalizationFunc()).Pointer() {\n\t\tt.Error(\"childCmd should have had the normalization function of rootCmd\")\n\t}\n}\n\n// Related to https://github.com/spf13/cobra/issues/521.\nfunc TestNormPassedOnLocal(t *testing.T) {\n\ttoUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName {\n\t\treturn pflag.NormalizedName(strings.ToUpper(name))\n\t}\n\n\tc := &Command{}\n\tc.Flags().Bool(\"flagname\", true, \"this is a dummy flag\")\n\tc.SetGlobalNormalizationFunc(toUpper)\n\tif c.LocalFlags().Lookup(\"flagname\") != c.LocalFlags().Lookup(\"FLAGNAME\") {\n\t\tt.Error(\"Normalization function should be passed on to Local flag set\")\n\t}\n}\n\n// Related to https://github.com/spf13/cobra/issues/521.\nfunc TestNormPassedOnInherited(t *testing.T) {\n\ttoUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName {\n\t\treturn pflag.NormalizedName(strings.ToUpper(name))\n\t}\n\n\tc := &Command{}\n\tc.SetGlobalNormalizationFunc(toUpper)\n\n\tchild1 := &Command{}\n\tc.AddCommand(child1)\n\n\tc.PersistentFlags().Bool(\"flagname\", true, \"\")\n\n\tchild2 := &Command{}\n\tc.AddCommand(child2)\n\n\tinherited := child1.InheritedFlags()\n\tif inherited.Lookup(\"flagname\") == nil || inherited.Lookup(\"flagname\") != inherited.Lookup(\"FLAGNAME\") {\n\t\tt.Error(\"Normalization function should be passed on to inherited flag set in command added before flag\")\n\t}\n\n\tinherited = child2.InheritedFlags()\n\tif inherited.Lookup(\"flagname\") == nil || inherited.Lookup(\"flagname\") != inherited.Lookup(\"FLAGNAME\") {\n\t\tt.Error(\"Normalization function should be passed on to inherited flag set in command added after flag\")\n\t}\n}\n\n// Related to https://github.com/spf13/cobra/issues/521.\nfunc TestConsistentNormalizedName(t *testing.T) {\n\ttoUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName {\n\t\treturn pflag.NormalizedName(strings.ToUpper(name))\n\t}\n\tn := func(f *pflag.FlagSet, name string) pflag.NormalizedName {\n\t\treturn pflag.NormalizedName(name)\n\t}\n\n\tc := &Command{}\n\tc.Flags().Bool(\"flagname\", true, \"\")\n\tc.SetGlobalNormalizationFunc(toUpper)\n\tc.SetGlobalNormalizationFunc(n)\n\n\tif c.LocalFlags().Lookup(\"flagname\") == c.LocalFlags().Lookup(\"FLAGNAME\") {\n\t\tt.Error(\"Normalizing flag names should not result in duplicate flags\")\n\t}\n}\n\nfunc TestFlagOnPflagCommandLine(t *testing.T) {\n\tflagName := \"flagOnCommandLine\"\n\tpflag.String(flagName, \"\", \"about my flag\")\n\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\tc.AddCommand(&Command{Use: \"child\", Run: emptyRun})\n\n\toutput, _ := executeCommand(c, \"--help\")\n\tcheckStringContains(t, output, flagName)\n\n\tresetCommandLineFlagSet()\n}\n\n// TestHiddenCommandExecutes checks,\n// if hidden commands run as intended.\nfunc TestHiddenCommandExecutes(t *testing.T) {\n\texecuted := false\n\tc := &Command{\n\t\tUse:    \"c\",\n\t\tHidden: true,\n\t\tRun:    func(*Command, []string) { executed = true },\n\t}\n\n\toutput, err := executeCommand(c)\n\tif output != \"\" {\n\t\tt.Errorf(\"Unexpected output: %v\", output)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tif !executed {\n\t\tt.Error(\"Hidden command should have been executed\")\n\t}\n}\n\n// test to ensure hidden commands do not show up in usage/help text\nfunc TestHiddenCommandIsHidden(t *testing.T) {\n\tc := &Command{Use: \"c\", Hidden: true, Run: emptyRun}\n\tif c.IsAvailableCommand() {\n\t\tt.Errorf(\"Hidden command should be unavailable\")\n\t}\n}\n\nfunc TestCommandsAreSorted(t *testing.T) {\n\tEnableCommandSorting = true\n\n\toriginalNames := []string{\"middle\", \"zlast\", \"afirst\"}\n\texpectedNames := []string{\"afirst\", \"middle\", \"zlast\"}\n\n\tvar rootCmd = &Command{Use: \"root\"}\n\n\tfor _, name := range originalNames {\n\t\trootCmd.AddCommand(&Command{Use: name})\n\t}\n\n\tfor i, c := range rootCmd.Commands() {\n\t\tgot := c.Name()\n\t\tif expectedNames[i] != got {\n\t\t\tt.Errorf(\"Expected: %s, got: %s\", expectedNames[i], got)\n\t\t}\n\t}\n\n\tEnableCommandSorting = defaultCommandSorting\n}\n\nfunc TestEnableCommandSortingIsDisabled(t *testing.T) {\n\tEnableCommandSorting = false\n\n\toriginalNames := []string{\"middle\", \"zlast\", \"afirst\"}\n\n\tvar rootCmd = &Command{Use: \"root\"}\n\n\tfor _, name := range originalNames {\n\t\trootCmd.AddCommand(&Command{Use: name})\n\t}\n\n\tfor i, c := range rootCmd.Commands() {\n\t\tgot := c.Name()\n\t\tif originalNames[i] != got {\n\t\t\tt.Errorf(\"expected: %s, got: %s\", originalNames[i], got)\n\t\t}\n\t}\n\n\tEnableCommandSorting = defaultCommandSorting\n}\n\nfunc TestUsageWithGroup(t *testing.T) {\n\tvar rootCmd = &Command{Use: \"root\", Short: \"test\", Run: emptyRun}\n\trootCmd.CompletionOptions.DisableDefaultCmd = true\n\n\trootCmd.AddGroup(&Group{ID: \"group1\", Title: \"group1\"})\n\trootCmd.AddGroup(&Group{ID: \"group2\", Title: \"group2\"})\n\n\trootCmd.AddCommand(&Command{Use: \"cmd1\", GroupID: \"group1\", Run: emptyRun})\n\trootCmd.AddCommand(&Command{Use: \"cmd2\", GroupID: \"group2\", Run: emptyRun})\n\n\toutput, err := executeCommand(rootCmd, \"--help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\t// help should be ungrouped here\n\tcheckStringContains(t, output, \"\\nAdditional Commands:\\n  help\")\n\tcheckStringContains(t, output, \"\\ngroup1\\n  cmd1\")\n\tcheckStringContains(t, output, \"\\ngroup2\\n  cmd2\")\n}\n\nfunc TestUsageHelpGroup(t *testing.T) {\n\tvar rootCmd = &Command{Use: \"root\", Short: \"test\", Run: emptyRun}\n\trootCmd.CompletionOptions.DisableDefaultCmd = true\n\n\trootCmd.AddGroup(&Group{ID: \"group\", Title: \"group\"})\n\trootCmd.AddCommand(&Command{Use: \"xxx\", GroupID: \"group\", Run: emptyRun})\n\trootCmd.SetHelpCommandGroupID(\"group\")\n\n\toutput, err := executeCommand(rootCmd, \"--help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\t// now help should be grouped under \"group\"\n\tcheckStringOmits(t, output, \"\\nAdditional Commands:\\n  help\")\n\tcheckStringContains(t, output, \"\\ngroup\\n  help\")\n}\n\nfunc TestUsageCompletionGroup(t *testing.T) {\n\tvar rootCmd = &Command{Use: \"root\", Short: \"test\", Run: emptyRun}\n\n\trootCmd.AddGroup(&Group{ID: \"group\", Title: \"group\"})\n\trootCmd.AddGroup(&Group{ID: \"help\", Title: \"help\"})\n\n\trootCmd.AddCommand(&Command{Use: \"xxx\", GroupID: \"group\", Run: emptyRun})\n\trootCmd.SetHelpCommandGroupID(\"help\")\n\trootCmd.SetCompletionCommandGroupID(\"group\")\n\n\toutput, err := executeCommand(rootCmd, \"--help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\t// now completion should be grouped under \"group\"\n\tcheckStringOmits(t, output, \"\\nAdditional Commands:\\n  completion\")\n\tcheckStringContains(t, output, \"\\ngroup\\n  completion\")\n}\n\nfunc TestUngroupedCommand(t *testing.T) {\n\tvar rootCmd = &Command{Use: \"root\", Short: \"test\", Run: emptyRun}\n\n\trootCmd.AddGroup(&Group{ID: \"group\", Title: \"group\"})\n\trootCmd.AddGroup(&Group{ID: \"help\", Title: \"help\"})\n\n\trootCmd.AddCommand(&Command{Use: \"xxx\", GroupID: \"group\", Run: emptyRun})\n\trootCmd.SetHelpCommandGroupID(\"help\")\n\trootCmd.SetCompletionCommandGroupID(\"group\")\n\n\t// Add a command without a group\n\trootCmd.AddCommand(&Command{Use: \"yyy\", Run: emptyRun})\n\n\toutput, err := executeCommand(rootCmd, \"--help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\t// The yyy command should be in the additional command \"group\"\n\tcheckStringContains(t, output, \"\\nAdditional Commands:\\n  yyy\")\n}\n\nfunc TestAddGroup(t *testing.T) {\n\tvar rootCmd = &Command{Use: \"root\", Short: \"test\", Run: emptyRun}\n\n\trootCmd.AddGroup(&Group{ID: \"group\", Title: \"Test group\"})\n\trootCmd.AddCommand(&Command{Use: \"cmd\", GroupID: \"group\", Run: emptyRun})\n\n\toutput, err := executeCommand(rootCmd, \"--help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, \"\\nTest group\\n  cmd\")\n}\n\nfunc TestWrongGroupFirstLevel(t *testing.T) {\n\tvar rootCmd = &Command{Use: \"root\", Short: \"test\", Run: emptyRun}\n\n\trootCmd.AddGroup(&Group{ID: \"group\", Title: \"Test group\"})\n\t// Use the wrong group ID\n\trootCmd.AddCommand(&Command{Use: \"cmd\", GroupID: \"wrong\", Run: emptyRun})\n\n\tdefer func() {\n\t\tif recover() == nil {\n\t\t\tt.Errorf(\"The code should have panicked due to a missing group\")\n\t\t}\n\t}()\n\t_, err := executeCommand(rootCmd, \"--help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n}\n\nfunc TestWrongGroupNestedLevel(t *testing.T) {\n\tvar rootCmd = &Command{Use: \"root\", Short: \"test\", Run: emptyRun}\n\tvar childCmd = &Command{Use: \"child\", Run: emptyRun}\n\trootCmd.AddCommand(childCmd)\n\n\tchildCmd.AddGroup(&Group{ID: \"group\", Title: \"Test group\"})\n\t// Use the wrong group ID\n\tchildCmd.AddCommand(&Command{Use: \"cmd\", GroupID: \"wrong\", Run: emptyRun})\n\n\tdefer func() {\n\t\tif recover() == nil {\n\t\t\tt.Errorf(\"The code should have panicked due to a missing group\")\n\t\t}\n\t}()\n\t_, err := executeCommand(rootCmd, \"child\", \"--help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n}\n\nfunc TestWrongGroupForHelp(t *testing.T) {\n\tvar rootCmd = &Command{Use: \"root\", Short: \"test\", Run: emptyRun}\n\tvar childCmd = &Command{Use: \"child\", Run: emptyRun}\n\trootCmd.AddCommand(childCmd)\n\n\trootCmd.AddGroup(&Group{ID: \"group\", Title: \"Test group\"})\n\t// Use the wrong group ID\n\trootCmd.SetHelpCommandGroupID(\"wrong\")\n\n\tdefer func() {\n\t\tif recover() == nil {\n\t\t\tt.Errorf(\"The code should have panicked due to a missing group\")\n\t\t}\n\t}()\n\t_, err := executeCommand(rootCmd, \"--help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n}\n\nfunc TestWrongGroupForCompletion(t *testing.T) {\n\tvar rootCmd = &Command{Use: \"root\", Short: \"test\", Run: emptyRun}\n\tvar childCmd = &Command{Use: \"child\", Run: emptyRun}\n\trootCmd.AddCommand(childCmd)\n\n\trootCmd.AddGroup(&Group{ID: \"group\", Title: \"Test group\"})\n\t// Use the wrong group ID\n\trootCmd.SetCompletionCommandGroupID(\"wrong\")\n\n\tdefer func() {\n\t\tif recover() == nil {\n\t\t\tt.Errorf(\"The code should have panicked due to a missing group\")\n\t\t}\n\t}()\n\t_, err := executeCommand(rootCmd, \"--help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n}\n\nfunc TestSetOutput(t *testing.T) {\n\tc := &Command{}\n\tc.SetOutput(nil)\n\tif out := c.OutOrStdout(); out != os.Stdout {\n\t\tt.Errorf(\"Expected setting output to nil to revert back to stdout\")\n\t}\n}\n\nfunc TestSetOut(t *testing.T) {\n\tc := &Command{}\n\tc.SetOut(nil)\n\tif out := c.OutOrStdout(); out != os.Stdout {\n\t\tt.Errorf(\"Expected setting output to nil to revert back to stdout\")\n\t}\n}\n\nfunc TestSetErr(t *testing.T) {\n\tc := &Command{}\n\tc.SetErr(nil)\n\tif out := c.ErrOrStderr(); out != os.Stderr {\n\t\tt.Errorf(\"Expected setting error to nil to revert back to stderr\")\n\t}\n}\n\nfunc TestSetIn(t *testing.T) {\n\tc := &Command{}\n\tc.SetIn(nil)\n\tif out := c.InOrStdin(); out != os.Stdin {\n\t\tt.Errorf(\"Expected setting input to nil to revert back to stdin\")\n\t}\n}\n\nfunc TestUsageStringRedirected(t *testing.T) {\n\tc := &Command{}\n\n\tc.usageFunc = func(cmd *Command) error {\n\t\tcmd.Print(\"[stdout1]\")\n\t\tcmd.PrintErr(\"[stderr2]\")\n\t\tcmd.Print(\"[stdout3]\")\n\t\treturn nil\n\t}\n\n\texpected := \"[stdout1][stderr2][stdout3]\"\n\tif got := c.UsageString(); got != expected {\n\t\tt.Errorf(\"Expected usage string to consider both stdout and stderr\")\n\t}\n}\n\nfunc TestCommandPrintRedirection(t *testing.T) {\n\terrBuff, outBuff := bytes.NewBuffer(nil), bytes.NewBuffer(nil)\n\troot := &Command{\n\t\tRun: func(cmd *Command, args []string) {\n\n\t\t\tcmd.PrintErr(\"PrintErr\")\n\t\t\tcmd.PrintErrln(\"PrintErr\", \"line\")\n\t\t\tcmd.PrintErrf(\"PrintEr%s\", \"r\")\n\n\t\t\tcmd.Print(\"Print\")\n\t\t\tcmd.Println(\"Print\", \"line\")\n\t\t\tcmd.Printf(\"Prin%s\", \"t\")\n\t\t},\n\t}\n\n\troot.SetErr(errBuff)\n\troot.SetOut(outBuff)\n\n\tif err := root.Execute(); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tgotErrBytes, err := io.ReadAll(errBuff)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tgotOutBytes, err := io.ReadAll(outBuff)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif wantErr := []byte(\"PrintErrPrintErr line\\nPrintErr\"); !bytes.Equal(gotErrBytes, wantErr) {\n\t\tt.Errorf(\"got: '%s' want: '%s'\", gotErrBytes, wantErr)\n\t}\n\n\tif wantOut := []byte(\"PrintPrint line\\nPrint\"); !bytes.Equal(gotOutBytes, wantOut) {\n\t\tt.Errorf(\"got: '%s' want: '%s'\", gotOutBytes, wantOut)\n\t}\n}\n\nfunc TestFlagErrorFunc(t *testing.T) {\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\n\texpectedFmt := \"This is expected: %v\"\n\tc.SetFlagErrorFunc(func(_ *Command, err error) error {\n\t\treturn fmt.Errorf(expectedFmt, err)\n\t})\n\n\t_, err := executeCommand(c, \"--unknown-flag\")\n\n\tgot := err.Error()\n\texpected := fmt.Sprintf(expectedFmt, \"unknown flag: --unknown-flag\")\n\tif got != expected {\n\t\tt.Errorf(\"Expected %v, got %v\", expected, got)\n\t}\n}\n\nfunc TestFlagErrorFuncHelp(t *testing.T) {\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\tc.PersistentFlags().Bool(\"help\", false, \"help for c\")\n\tc.SetFlagErrorFunc(func(_ *Command, err error) error {\n\t\treturn fmt.Errorf(\"wrap error: %w\", err)\n\t})\n\n\tout, err := executeCommand(c, \"--help\")\n\tif err != nil {\n\t\tt.Errorf(\"--help should not fail: %v\", err)\n\t}\n\n\texpected := `Usage:\n  c [flags]\n\nFlags:\n      --help   help for c\n`\n\tif out != expected {\n\t\tt.Errorf(\"Expected: %v, got: %v\", expected, out)\n\t}\n\n\tout, err = executeCommand(c, \"-h\")\n\tif err != nil {\n\t\tt.Errorf(\"-h should not fail: %v\", err)\n\t}\n\n\tif out != expected {\n\t\tt.Errorf(\"Expected: %v, got: %v\", expected, out)\n\t}\n}\n\n// TestSortedFlags checks,\n// if cmd.LocalFlags() is unsorted when cmd.Flags().SortFlags set to false.\n// Related to https://github.com/spf13/cobra/issues/404.\nfunc TestSortedFlags(t *testing.T) {\n\tc := &Command{}\n\tc.Flags().SortFlags = false\n\tnames := []string{\"C\", \"B\", \"A\", \"D\"}\n\tfor _, name := range names {\n\t\tc.Flags().Bool(name, false, \"\")\n\t}\n\n\ti := 0\n\tc.LocalFlags().VisitAll(func(f *pflag.Flag) {\n\t\tif i == len(names) {\n\t\t\treturn\n\t\t}\n\t\tif stringInSlice(f.Name, names) {\n\t\t\tif names[i] != f.Name {\n\t\t\t\tt.Errorf(\"Incorrect order. Expected %v, got %v\", names[i], f.Name)\n\t\t\t}\n\t\t\ti++\n\t\t}\n\t})\n}\n\n// TestMergeCommandLineToFlags checks,\n// if pflag.CommandLine is correctly merged to c.Flags() after first call\n// of c.mergePersistentFlags.\n// Related to https://github.com/spf13/cobra/issues/443.\nfunc TestMergeCommandLineToFlags(t *testing.T) {\n\tpflag.Bool(\"boolflag\", false, \"\")\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\tc.mergePersistentFlags()\n\tif c.Flags().Lookup(\"boolflag\") == nil {\n\t\tt.Fatal(\"Expecting to have flag from CommandLine in c.Flags()\")\n\t}\n\n\tresetCommandLineFlagSet()\n}\n\n// TestUseDeprecatedFlags checks,\n// if cobra.Execute() prints a message, if a deprecated flag is used.\n// Related to https://github.com/spf13/cobra/issues/463.\nfunc TestUseDeprecatedFlags(t *testing.T) {\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\tc.Flags().BoolP(\"deprecated\", \"d\", false, \"deprecated flag\")\n\tassertNoErr(t, c.Flags().MarkDeprecated(\"deprecated\", \"This flag is deprecated\"))\n\n\toutput, err := executeCommand(c, \"c\", \"-d\")\n\tif err != nil {\n\t\tt.Error(\"Unexpected error:\", err)\n\t}\n\tcheckStringContains(t, output, \"This flag is deprecated\")\n}\n\nfunc TestTraverseWithParentFlags(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", TraverseChildren: true}\n\trootCmd.Flags().String(\"str\", \"\", \"\")\n\trootCmd.Flags().BoolP(\"bool\", \"b\", false, \"\")\n\n\tchildCmd := &Command{Use: \"child\"}\n\tchildCmd.Flags().Int(\"int\", -1, \"\")\n\n\trootCmd.AddCommand(childCmd)\n\n\tc, args, err := rootCmd.Traverse([]string{\"-b\", \"--str\", \"ok\", \"child\", \"--int\"})\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\tif len(args) != 1 && args[0] != \"--add\" {\n\t\tt.Errorf(\"Wrong args: %v\", args)\n\t}\n\tif c.Name() != childCmd.Name() {\n\t\tt.Errorf(\"Expected command: %q, got: %q\", childCmd.Name(), c.Name())\n\t}\n}\n\nfunc TestTraverseNoParentFlags(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", TraverseChildren: true}\n\trootCmd.Flags().String(\"foo\", \"\", \"foo things\")\n\n\tchildCmd := &Command{Use: \"child\"}\n\tchildCmd.Flags().String(\"str\", \"\", \"\")\n\trootCmd.AddCommand(childCmd)\n\n\tc, args, err := rootCmd.Traverse([]string{\"child\"})\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\tif len(args) != 0 {\n\t\tt.Errorf(\"Wrong args %v\", args)\n\t}\n\tif c.Name() != childCmd.Name() {\n\t\tt.Errorf(\"Expected command: %q, got: %q\", childCmd.Name(), c.Name())\n\t}\n}\n\nfunc TestTraverseWithBadParentFlags(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", TraverseChildren: true}\n\n\tchildCmd := &Command{Use: \"child\"}\n\tchildCmd.Flags().String(\"str\", \"\", \"\")\n\trootCmd.AddCommand(childCmd)\n\n\texpected := \"unknown flag: --str\"\n\n\tc, _, err := rootCmd.Traverse([]string{\"--str\", \"ok\", \"child\"})\n\tif err == nil || !strings.Contains(err.Error(), expected) {\n\t\tt.Errorf(\"Expected error, %q, got %q\", expected, err)\n\t}\n\tif c != nil {\n\t\tt.Errorf(\"Expected nil command\")\n\t}\n}\n\nfunc TestTraverseWithBadChildFlag(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", TraverseChildren: true}\n\trootCmd.Flags().String(\"str\", \"\", \"\")\n\n\tchildCmd := &Command{Use: \"child\"}\n\trootCmd.AddCommand(childCmd)\n\n\t// Expect no error because the last commands args shouldn't be parsed in\n\t// Traverse.\n\tc, args, err := rootCmd.Traverse([]string{\"child\", \"--str\"})\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\tif len(args) != 1 && args[0] != \"--str\" {\n\t\tt.Errorf(\"Wrong args: %v\", args)\n\t}\n\tif c.Name() != childCmd.Name() {\n\t\tt.Errorf(\"Expected command %q, got: %q\", childCmd.Name(), c.Name())\n\t}\n}\n\nfunc TestTraverseWithTwoSubcommands(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", TraverseChildren: true}\n\n\tsubCmd := &Command{Use: \"sub\", TraverseChildren: true}\n\trootCmd.AddCommand(subCmd)\n\n\tsubsubCmd := &Command{\n\t\tUse: \"subsub\",\n\t}\n\tsubCmd.AddCommand(subsubCmd)\n\n\tc, _, err := rootCmd.Traverse([]string{\"sub\", \"subsub\"})\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t}\n\tif c.Name() != subsubCmd.Name() {\n\t\tt.Fatalf(\"Expected command: %q, got %q\", subsubCmd.Name(), c.Name())\n\t}\n}\n\n// TestUpdateName checks if c.Name() updates on changed c.Use.\n// Related to https://github.com/spf13/cobra/pull/422#discussion_r143918343.\nfunc TestUpdateName(t *testing.T) {\n\tc := &Command{Use: \"name xyz\"}\n\toriginalName := c.Name()\n\n\tc.Use = \"changedName abc\"\n\tif originalName == c.Name() || c.Name() != \"changedName\" {\n\t\tt.Error(\"c.Name() should be updated on changed c.Use\")\n\t}\n}\n\ntype calledAsTestcase struct {\n\targs []string\n\tcall string\n\twant string\n\tepm  bool\n}\n\nfunc (tc *calledAsTestcase) test(t *testing.T) {\n\tdefer func(ov bool) { EnablePrefixMatching = ov }(EnablePrefixMatching)\n\tEnablePrefixMatching = tc.epm\n\n\tvar called *Command\n\trun := func(c *Command, _ []string) { t.Logf(\"called: %q\", c.Name()); called = c }\n\n\tparent := &Command{Use: \"parent\", Run: run}\n\tchild1 := &Command{Use: \"child1\", Run: run, Aliases: []string{\"this\"}}\n\tchild2 := &Command{Use: \"child2\", Run: run, Aliases: []string{\"that\"}}\n\n\tparent.AddCommand(child1)\n\tparent.AddCommand(child2)\n\tparent.SetArgs(tc.args)\n\n\toutput := new(bytes.Buffer)\n\tparent.SetOut(output)\n\tparent.SetErr(output)\n\n\t_ = parent.Execute()\n\n\tif called == nil {\n\t\tif tc.call != \"\" {\n\t\t\tt.Errorf(\"missing expected call to command: %s\", tc.call)\n\t\t}\n\t\treturn\n\t}\n\n\tif called.Name() != tc.call {\n\t\tt.Errorf(\"called command == %q; Wanted %q\", called.Name(), tc.call)\n\t} else if got := called.CalledAs(); got != tc.want {\n\t\tt.Errorf(\"%s.CalledAs() == %q; Wanted: %q\", tc.call, got, tc.want)\n\t}\n}\n\nfunc TestCalledAs(t *testing.T) {\n\ttests := map[string]calledAsTestcase{\n\t\t\"find/no-args\":            {nil, \"parent\", \"parent\", false},\n\t\t\"find/real-name\":          {[]string{\"child1\"}, \"child1\", \"child1\", false},\n\t\t\"find/full-alias\":         {[]string{\"that\"}, \"child2\", \"that\", false},\n\t\t\"find/part-no-prefix\":     {[]string{\"thi\"}, \"\", \"\", false},\n\t\t\"find/part-alias\":         {[]string{\"thi\"}, \"child1\", \"this\", true},\n\t\t\"find/conflict\":           {[]string{\"th\"}, \"\", \"\", true},\n\t\t\"traverse/no-args\":        {nil, \"parent\", \"parent\", false},\n\t\t\"traverse/real-name\":      {[]string{\"child1\"}, \"child1\", \"child1\", false},\n\t\t\"traverse/full-alias\":     {[]string{\"that\"}, \"child2\", \"that\", false},\n\t\t\"traverse/part-no-prefix\": {[]string{\"thi\"}, \"\", \"\", false},\n\t\t\"traverse/part-alias\":     {[]string{\"thi\"}, \"child1\", \"this\", true},\n\t\t\"traverse/conflict\":       {[]string{\"th\"}, \"\", \"\", true},\n\t}\n\n\tfor name, tc := range tests {\n\t\tt.Run(name, tc.test)\n\t}\n}\n\nfunc TestFParseErrWhitelistBackwardCompatibility(t *testing.T) {\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\tc.Flags().BoolP(\"boola\", \"a\", false, \"a boolean flag\")\n\n\toutput, err := executeCommand(c, \"c\", \"-a\", \"--unknown\", \"flag\")\n\tif err == nil {\n\t\tt.Error(\"expected unknown flag error\")\n\t}\n\tcheckStringContains(t, output, \"unknown flag: --unknown\")\n}\n\nfunc TestFParseErrWhitelistSameCommand(t *testing.T) {\n\tc := &Command{\n\t\tUse: \"c\",\n\t\tRun: emptyRun,\n\t\tFParseErrWhitelist: FParseErrWhitelist{\n\t\t\tUnknownFlags: true,\n\t\t},\n\t}\n\tc.Flags().BoolP(\"boola\", \"a\", false, \"a boolean flag\")\n\n\t_, err := executeCommand(c, \"c\", \"-a\", \"--unknown\", \"flag\")\n\tif err != nil {\n\t\tt.Error(\"unexpected error: \", err)\n\t}\n}\n\nfunc TestFParseErrWhitelistParentCommand(t *testing.T) {\n\troot := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t\tFParseErrWhitelist: FParseErrWhitelist{\n\t\t\tUnknownFlags: true,\n\t\t},\n\t}\n\n\tc := &Command{\n\t\tUse: \"child\",\n\t\tRun: emptyRun,\n\t}\n\tc.Flags().BoolP(\"boola\", \"a\", false, \"a boolean flag\")\n\n\troot.AddCommand(c)\n\n\toutput, err := executeCommand(root, \"child\", \"-a\", \"--unknown\", \"flag\")\n\tif err == nil {\n\t\tt.Error(\"expected unknown flag error\")\n\t}\n\tcheckStringContains(t, output, \"unknown flag: --unknown\")\n}\n\nfunc TestFParseErrWhitelistChildCommand(t *testing.T) {\n\troot := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\n\tc := &Command{\n\t\tUse: \"child\",\n\t\tRun: emptyRun,\n\t\tFParseErrWhitelist: FParseErrWhitelist{\n\t\t\tUnknownFlags: true,\n\t\t},\n\t}\n\tc.Flags().BoolP(\"boola\", \"a\", false, \"a boolean flag\")\n\n\troot.AddCommand(c)\n\n\t_, err := executeCommand(root, \"child\", \"-a\", \"--unknown\", \"flag\")\n\tif err != nil {\n\t\tt.Error(\"unexpected error: \", err.Error())\n\t}\n}\n\nfunc TestFParseErrWhitelistSiblingCommand(t *testing.T) {\n\troot := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\n\tc := &Command{\n\t\tUse: \"child\",\n\t\tRun: emptyRun,\n\t\tFParseErrWhitelist: FParseErrWhitelist{\n\t\t\tUnknownFlags: true,\n\t\t},\n\t}\n\tc.Flags().BoolP(\"boola\", \"a\", false, \"a boolean flag\")\n\n\ts := &Command{\n\t\tUse: \"sibling\",\n\t\tRun: emptyRun,\n\t}\n\ts.Flags().BoolP(\"boolb\", \"b\", false, \"a boolean flag\")\n\n\troot.AddCommand(c)\n\troot.AddCommand(s)\n\n\toutput, err := executeCommand(root, \"sibling\", \"-b\", \"--unknown\", \"flag\")\n\tif err == nil {\n\t\tt.Error(\"expected unknown flag error\")\n\t}\n\tcheckStringContains(t, output, \"unknown flag: --unknown\")\n}\n\nfunc TestSetContext(t *testing.T) {\n\ttype key struct{}\n\tval := \"foobar\"\n\troot := &Command{\n\t\tUse: \"root\",\n\t\tRun: func(cmd *Command, args []string) {\n\t\t\tkey := cmd.Context().Value(key{})\n\t\t\tgot, ok := key.(string)\n\t\t\tif !ok {\n\t\t\t\tt.Error(\"key not found in context\")\n\t\t\t}\n\t\t\tif got != val {\n\t\t\t\tt.Errorf(\"Expected value: \\n %v\\nGot:\\n %v\\n\", val, got)\n\t\t\t}\n\t\t},\n\t}\n\n\tctx := context.WithValue(context.Background(), key{}, val)\n\troot.SetContext(ctx)\n\terr := root.Execute()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestSetContextPreRun(t *testing.T) {\n\ttype key struct{}\n\tval := \"barr\"\n\troot := &Command{\n\t\tUse: \"root\",\n\t\tPreRun: func(cmd *Command, args []string) {\n\t\t\tctx := context.WithValue(cmd.Context(), key{}, val)\n\t\t\tcmd.SetContext(ctx)\n\t\t},\n\t\tRun: func(cmd *Command, args []string) {\n\t\t\tval := cmd.Context().Value(key{})\n\t\t\tgot, ok := val.(string)\n\t\t\tif !ok {\n\t\t\t\tt.Error(\"key not found in context\")\n\t\t\t}\n\t\t\tif got != val {\n\t\t\t\tt.Errorf(\"Expected value: \\n %v\\nGot:\\n %v\\n\", val, got)\n\t\t\t}\n\t\t},\n\t}\n\terr := root.Execute()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestSetContextPreRunOverwrite(t *testing.T) {\n\ttype key struct{}\n\tval := \"blah\"\n\troot := &Command{\n\t\tUse: \"root\",\n\t\tRun: func(cmd *Command, args []string) {\n\t\t\tkey := cmd.Context().Value(key{})\n\t\t\t_, ok := key.(string)\n\t\t\tif ok {\n\t\t\t\tt.Error(\"key found in context when not expected\")\n\t\t\t}\n\t\t},\n\t}\n\tctx := context.WithValue(context.Background(), key{}, val)\n\troot.SetContext(ctx)\n\terr := root.ExecuteContext(context.Background())\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestSetContextPersistentPreRun(t *testing.T) {\n\ttype key struct{}\n\tval := \"barbar\"\n\troot := &Command{\n\t\tUse: \"root\",\n\t\tPersistentPreRun: func(cmd *Command, args []string) {\n\t\t\tctx := context.WithValue(cmd.Context(), key{}, val)\n\t\t\tcmd.SetContext(ctx)\n\t\t},\n\t}\n\tchild := &Command{\n\t\tUse: \"child\",\n\t\tRun: func(cmd *Command, args []string) {\n\t\t\tkey := cmd.Context().Value(key{})\n\t\t\tgot, ok := key.(string)\n\t\t\tif !ok {\n\t\t\t\tt.Error(\"key not found in context\")\n\t\t\t}\n\t\t\tif got != val {\n\t\t\t\tt.Errorf(\"Expected value: \\n %v\\nGot:\\n %v\\n\", val, got)\n\t\t\t}\n\t\t},\n\t}\n\troot.AddCommand(child)\n\troot.SetArgs([]string{\"child\"})\n\terr := root.Execute()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nconst VersionFlag = \"--version\"\nconst HelpFlag = \"--help\"\n\nfunc TestNoRootRunCommandExecutedWithVersionSet(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Version: \"1.0.0\", Long: \"Long description\"}\n\trootCmd.AddCommand(&Command{Use: \"child\", Run: emptyRun})\n\n\toutput, err := executeCommand(rootCmd)\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, rootCmd.Long)\n\tcheckStringContains(t, output, HelpFlag)\n\tcheckStringContains(t, output, VersionFlag)\n}\n\nfunc TestNoRootRunCommandExecutedWithoutVersionSet(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Long: \"Long description\"}\n\trootCmd.AddCommand(&Command{Use: \"child\", Run: emptyRun})\n\n\toutput, err := executeCommand(rootCmd)\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, rootCmd.Long)\n\tcheckStringContains(t, output, HelpFlag)\n\tcheckStringOmits(t, output, VersionFlag)\n}\n\nfunc TestHelpCommandExecutedWithVersionSet(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Version: \"1.0.0\", Long: \"Long description\", Run: emptyRun}\n\trootCmd.AddCommand(&Command{Use: \"child\", Run: emptyRun})\n\n\toutput, err := executeCommand(rootCmd, \"help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, rootCmd.Long)\n\tcheckStringContains(t, output, HelpFlag)\n\tcheckStringContains(t, output, VersionFlag)\n}\n\nfunc TestHelpCommandExecutedWithoutVersionSet(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Long: \"Long description\", Run: emptyRun}\n\trootCmd.AddCommand(&Command{Use: \"child\", Run: emptyRun})\n\n\toutput, err := executeCommand(rootCmd, \"help\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, rootCmd.Long)\n\tcheckStringContains(t, output, HelpFlag)\n\tcheckStringOmits(t, output, VersionFlag)\n}\n\nfunc TestHelpflagCommandExecutedWithVersionSet(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Version: \"1.0.0\", Long: \"Long description\", Run: emptyRun}\n\trootCmd.AddCommand(&Command{Use: \"child\", Run: emptyRun})\n\n\toutput, err := executeCommand(rootCmd, HelpFlag)\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, rootCmd.Long)\n\tcheckStringContains(t, output, HelpFlag)\n\tcheckStringContains(t, output, VersionFlag)\n}\n\nfunc TestHelpflagCommandExecutedWithoutVersionSet(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Long: \"Long description\", Run: emptyRun}\n\trootCmd.AddCommand(&Command{Use: \"child\", Run: emptyRun})\n\n\toutput, err := executeCommand(rootCmd, HelpFlag)\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, rootCmd.Long)\n\tcheckStringContains(t, output, HelpFlag)\n\tcheckStringOmits(t, output, VersionFlag)\n}\n\nfunc TestFind(t *testing.T) {\n\tvar foo, bar string\n\troot := &Command{\n\t\tUse: \"root\",\n\t}\n\troot.PersistentFlags().StringVarP(&foo, \"foo\", \"f\", \"\", \"\")\n\troot.PersistentFlags().StringVarP(&bar, \"bar\", \"b\", \"something\", \"\")\n\n\tchild := &Command{\n\t\tUse: \"child\",\n\t}\n\troot.AddCommand(child)\n\n\ttestCases := []struct {\n\t\targs              []string\n\t\texpectedFoundArgs []string\n\t}{\n\t\t{\n\t\t\t[]string{\"child\"},\n\t\t\t[]string{},\n\t\t},\n\t\t{\n\t\t\t[]string{\"child\", \"child\"},\n\t\t\t[]string{\"child\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"child\", \"foo\", \"child\", \"bar\", \"child\", \"baz\", \"child\"},\n\t\t\t[]string{\"foo\", \"child\", \"bar\", \"child\", \"baz\", \"child\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"-f\", \"child\", \"child\"},\n\t\t\t[]string{\"-f\", \"child\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"child\", \"-f\", \"child\"},\n\t\t\t[]string{\"-f\", \"child\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"-b\", \"child\", \"child\"},\n\t\t\t[]string{\"-b\", \"child\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"child\", \"-b\", \"child\"},\n\t\t\t[]string{\"-b\", \"child\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"child\", \"-b\"},\n\t\t\t[]string{\"-b\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"-b\", \"-f\", \"child\", \"child\"},\n\t\t\t[]string{\"-b\", \"-f\", \"child\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"-f\", \"child\", \"-b\", \"something\", \"child\"},\n\t\t\t[]string{\"-f\", \"child\", \"-b\", \"something\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"-f\", \"child\", \"child\", \"-b\"},\n\t\t\t[]string{\"-f\", \"child\", \"-b\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"-f=child\", \"-b=something\", \"child\"},\n\t\t\t[]string{\"-f=child\", \"-b=something\"},\n\t\t},\n\t\t{\n\t\t\t[]string{\"--foo\", \"child\", \"--bar\", \"something\", \"child\"},\n\t\t\t[]string{\"--foo\", \"child\", \"--bar\", \"something\"},\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(fmt.Sprintf(\"%v\", tc.args), func(t *testing.T) {\n\t\t\tcmd, foundArgs, err := root.Find(tc.args)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tif cmd != child {\n\t\t\t\tt.Fatal(\"Expected cmd to be child, but it was not\")\n\t\t\t}\n\n\t\t\tif !reflect.DeepEqual(tc.expectedFoundArgs, foundArgs) {\n\t\t\t\tt.Fatalf(\"Wrong args\\nExpected: %v\\nGot: %v\", tc.expectedFoundArgs, foundArgs)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestUnknownFlagShouldReturnSameErrorRegardlessOfArgPosition(t *testing.T) {\n\ttestCases := [][]string{\n\t\t// {\"--unknown\", \"--namespace\", \"foo\", \"child\", \"--bar\"}, // FIXME: This test case fails, returning the error `unknown command \"foo\" for \"root\"` instead of the expected error `unknown flag: --unknown`\n\t\t{\"--namespace\", \"foo\", \"--unknown\", \"child\", \"--bar\"},\n\t\t{\"--namespace\", \"foo\", \"child\", \"--unknown\", \"--bar\"},\n\t\t{\"--namespace\", \"foo\", \"child\", \"--bar\", \"--unknown\"},\n\n\t\t{\"--unknown\", \"--namespace=foo\", \"child\", \"--bar\"},\n\t\t{\"--namespace=foo\", \"--unknown\", \"child\", \"--bar\"},\n\t\t{\"--namespace=foo\", \"child\", \"--unknown\", \"--bar\"},\n\t\t{\"--namespace=foo\", \"child\", \"--bar\", \"--unknown\"},\n\n\t\t{\"--unknown\", \"--namespace=foo\", \"child\", \"--bar=true\"},\n\t\t{\"--namespace=foo\", \"--unknown\", \"child\", \"--bar=true\"},\n\t\t{\"--namespace=foo\", \"child\", \"--unknown\", \"--bar=true\"},\n\t\t{\"--namespace=foo\", \"child\", \"--bar=true\", \"--unknown\"},\n\t}\n\n\troot := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\troot.PersistentFlags().String(\"namespace\", \"\", \"a string flag\")\n\n\tc := &Command{\n\t\tUse: \"child\",\n\t\tRun: emptyRun,\n\t}\n\tc.Flags().Bool(\"bar\", false, \"a boolean flag\")\n\n\troot.AddCommand(c)\n\n\tfor _, tc := range testCases {\n\t\tt.Run(strings.Join(tc, \" \"), func(t *testing.T) {\n\t\t\toutput, err := executeCommand(root, tc...)\n\t\t\tif err == nil {\n\t\t\t\tt.Error(\"expected unknown flag error\")\n\t\t\t}\n\t\t\tcheckStringContains(t, output, \"unknown flag: --unknown\")\n\t\t})\n\t}\n}\n\nfunc TestHelpFuncExecuted(t *testing.T) {\n\thelpText := \"Long description\"\n\n\t// Create a context that will be unique, not just the background context\n\t//nolint:staticcheck // We can safely use a basic type as key in tests.\n\texecutionCtx := context.WithValue(context.Background(), \"testKey\", \"123\")\n\n\tchild := &Command{Use: \"child\", Run: emptyRun}\n\tchild.SetHelpFunc(func(cmd *Command, args []string) {\n\t\t_, err := cmd.OutOrStdout().Write([]byte(helpText))\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\n\t\t// Test for https://github.com/spf13/cobra/issues/2240\n\t\tif cmd.Context() != executionCtx {\n\t\t\tt.Error(\"Context doesn't equal the execution context\")\n\t\t}\n\t})\n\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\trootCmd.AddCommand(child)\n\n\toutput, err := executeCommandWithContext(executionCtx, rootCmd, \"help\", \"child\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheckStringContains(t, output, helpText)\n}\n"
  },
  {
    "path": "command_win.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n//go:build windows\n// +build windows\n\npackage cobra\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/inconshreveable/mousetrap\"\n)\n\nvar preExecHookFn = preExecHook\n\nfunc preExecHook(c *Command) {\n\tif MousetrapHelpText != \"\" && mousetrap.StartedByExplorer() {\n\t\tc.Print(MousetrapHelpText)\n\t\tif MousetrapDisplayDuration > 0 {\n\t\t\ttime.Sleep(MousetrapDisplayDuration)\n\t\t} else {\n\t\t\tc.Println(\"Press return to continue...\")\n\t\t\tfmt.Scanln()\n\t\t}\n\t\tos.Exit(1)\n\t}\n}\n"
  },
  {
    "path": "completions.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/spf13/pflag\"\n)\n\nconst (\n\t// ShellCompRequestCmd is the name of the hidden command that is used to request\n\t// completion results from the program.  It is used by the shell completion scripts.\n\tShellCompRequestCmd = \"__complete\"\n\t// ShellCompNoDescRequestCmd is the name of the hidden command that is used to request\n\t// completion results without their description.  It is used by the shell completion scripts.\n\tShellCompNoDescRequestCmd = \"__completeNoDesc\"\n)\n\n// Global map of flag completion functions. Make sure to use flagCompletionMutex before you try to read and write from it.\nvar flagCompletionFunctions = map[*pflag.Flag]CompletionFunc{}\n\n// lock for reading and writing from flagCompletionFunctions\nvar flagCompletionMutex = &sync.RWMutex{}\n\n// ShellCompDirective is a bit map representing the different behaviors the shell\n// can be instructed to have once completions have been provided.\ntype ShellCompDirective int\n\ntype flagCompError struct {\n\tsubCommand string\n\tflagName   string\n}\n\nfunc (e *flagCompError) Error() string {\n\treturn \"Subcommand '\" + e.subCommand + \"' does not support flag '\" + e.flagName + \"'\"\n}\n\nconst (\n\t// ShellCompDirectiveError indicates an error occurred and completions should be ignored.\n\tShellCompDirectiveError ShellCompDirective = 1 << iota\n\n\t// ShellCompDirectiveNoSpace indicates that the shell should not add a space\n\t// after the completion even if there is a single completion provided.\n\tShellCompDirectiveNoSpace\n\n\t// ShellCompDirectiveNoFileComp indicates that the shell should not provide\n\t// file completion even when no completion is provided.\n\tShellCompDirectiveNoFileComp\n\n\t// ShellCompDirectiveFilterFileExt indicates that the provided completions\n\t// should be used as file extension filters.\n\t// For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename()\n\t// is a shortcut to using this directive explicitly.  The BashCompFilenameExt\n\t// annotation can also be used to obtain the same behavior for flags.\n\tShellCompDirectiveFilterFileExt\n\n\t// ShellCompDirectiveFilterDirs indicates that only directory names should\n\t// be provided in file completion.  To request directory names within another\n\t// directory, the returned completions should specify the directory within\n\t// which to search.  The BashCompSubdirsInDir annotation can be used to\n\t// obtain the same behavior but only for flags.\n\tShellCompDirectiveFilterDirs\n\n\t// ShellCompDirectiveKeepOrder indicates that the shell should preserve the order\n\t// in which the completions are provided\n\tShellCompDirectiveKeepOrder\n\n\t// ===========================================================================\n\n\t// All directives using iota should be above this one.\n\t// For internal use.\n\tshellCompDirectiveMaxValue\n\n\t// ShellCompDirectiveDefault indicates to let the shell perform its default\n\t// behavior after completions have been provided.\n\t// This one must be last to avoid messing up the iota count.\n\tShellCompDirectiveDefault ShellCompDirective = 0\n)\n\nconst (\n\t// Constants for the completion command\n\tcompCmdName              = \"completion\"\n\tcompCmdNoDescFlagName    = \"no-descriptions\"\n\tcompCmdNoDescFlagDesc    = \"disable completion descriptions\"\n\tcompCmdNoDescFlagDefault = false\n)\n\n// CompletionOptions are the options to control shell completion\ntype CompletionOptions struct {\n\t// DisableDefaultCmd prevents Cobra from creating a default 'completion' command\n\tDisableDefaultCmd bool\n\t// DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag\n\t// for shells that support completion descriptions\n\tDisableNoDescFlag bool\n\t// DisableDescriptions turns off all completion descriptions for shells\n\t// that support them\n\tDisableDescriptions bool\n\t// HiddenDefaultCmd makes the default 'completion' command hidden\n\tHiddenDefaultCmd bool\n\t// DefaultShellCompDirective sets the ShellCompDirective that is returned\n\t// if no special directive can be determined\n\tDefaultShellCompDirective *ShellCompDirective\n}\n\nfunc (receiver *CompletionOptions) SetDefaultShellCompDirective(directive ShellCompDirective) {\n\treceiver.DefaultShellCompDirective = &directive\n}\n\n// Completion is a string that can be used for completions\n//\n// two formats are supported:\n//   - the completion choice\n//   - the completion choice with a textual description (separated by a TAB).\n//\n// [CompletionWithDesc] can be used to create a completion string with a textual description.\n//\n// Note: Go type alias is used to provide a more descriptive name in the documentation, but any string can be used.\ntype Completion = string\n\n// CompletionFunc is a function that provides completion results.\ntype CompletionFunc = func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective)\n\n// CompletionWithDesc returns a [Completion] with a description by using the TAB delimited format.\nfunc CompletionWithDesc(choice string, description string) Completion {\n\treturn choice + \"\\t\" + description\n}\n\n// NoFileCompletions can be used to disable file completion for commands that should\n// not trigger file completions.\n//\n// This method satisfies [CompletionFunc].\n// It can be used with [Command.RegisterFlagCompletionFunc] and for [Command.ValidArgsFunction].\nfunc NoFileCompletions(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) {\n\treturn nil, ShellCompDirectiveNoFileComp\n}\n\n// FixedCompletions can be used to create a completion function which always\n// returns the same results.\n//\n// This method returns a function that satisfies [CompletionFunc]\n// It can be used with [Command.RegisterFlagCompletionFunc] and for [Command.ValidArgsFunction].\nfunc FixedCompletions(choices []Completion, directive ShellCompDirective) CompletionFunc {\n\treturn func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) {\n\t\treturn choices, directive\n\t}\n}\n\n// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.\n//\n// You can use pre-defined completion functions such as [FixedCompletions] or [NoFileCompletions],\n// or you can define your own.\nfunc (c *Command) RegisterFlagCompletionFunc(flagName string, f CompletionFunc) error {\n\tflag := c.Flag(flagName)\n\tif flag == nil {\n\t\treturn fmt.Errorf(\"RegisterFlagCompletionFunc: flag '%s' does not exist\", flagName)\n\t}\n\tflagCompletionMutex.Lock()\n\tdefer flagCompletionMutex.Unlock()\n\n\tif _, exists := flagCompletionFunctions[flag]; exists {\n\t\treturn fmt.Errorf(\"RegisterFlagCompletionFunc: flag '%s' already registered\", flagName)\n\t}\n\tflagCompletionFunctions[flag] = f\n\treturn nil\n}\n\n// GetFlagCompletionFunc returns the completion function for the given flag of the command, if available.\nfunc (c *Command) GetFlagCompletionFunc(flagName string) (CompletionFunc, bool) {\n\tflag := c.Flag(flagName)\n\tif flag == nil {\n\t\treturn nil, false\n\t}\n\n\tflagCompletionMutex.RLock()\n\tdefer flagCompletionMutex.RUnlock()\n\n\tcompletionFunc, exists := flagCompletionFunctions[flag]\n\treturn completionFunc, exists\n}\n\n// Returns a string listing the different directive enabled in the specified parameter\nfunc (d ShellCompDirective) string() string {\n\tvar directives []string\n\tif d&ShellCompDirectiveError != 0 {\n\t\tdirectives = append(directives, \"ShellCompDirectiveError\")\n\t}\n\tif d&ShellCompDirectiveNoSpace != 0 {\n\t\tdirectives = append(directives, \"ShellCompDirectiveNoSpace\")\n\t}\n\tif d&ShellCompDirectiveNoFileComp != 0 {\n\t\tdirectives = append(directives, \"ShellCompDirectiveNoFileComp\")\n\t}\n\tif d&ShellCompDirectiveFilterFileExt != 0 {\n\t\tdirectives = append(directives, \"ShellCompDirectiveFilterFileExt\")\n\t}\n\tif d&ShellCompDirectiveFilterDirs != 0 {\n\t\tdirectives = append(directives, \"ShellCompDirectiveFilterDirs\")\n\t}\n\tif d&ShellCompDirectiveKeepOrder != 0 {\n\t\tdirectives = append(directives, \"ShellCompDirectiveKeepOrder\")\n\t}\n\tif len(directives) == 0 {\n\t\tdirectives = append(directives, \"ShellCompDirectiveDefault\")\n\t}\n\n\tif d >= shellCompDirectiveMaxValue {\n\t\treturn fmt.Sprintf(\"ERROR: unexpected ShellCompDirective value: %d\", d)\n\t}\n\treturn strings.Join(directives, \", \")\n}\n\n// initCompleteCmd adds a special hidden command that can be used to request custom completions.\nfunc (c *Command) initCompleteCmd(args []string) {\n\tcompleteCmd := &Command{\n\t\tUse:                   fmt.Sprintf(\"%s [command-line]\", ShellCompRequestCmd),\n\t\tAliases:               []string{ShellCompNoDescRequestCmd},\n\t\tDisableFlagsInUseLine: true,\n\t\tHidden:                true,\n\t\tDisableFlagParsing:    true,\n\t\tArgs:                  MinimumNArgs(1),\n\t\tShort:                 \"Request shell completion choices for the specified command-line\",\n\t\tLong: fmt.Sprintf(\"%[2]s is a special command that is used by the shell completion logic\\n%[1]s\",\n\t\t\t\"to request completion choices for the specified command-line.\", ShellCompRequestCmd),\n\t\tRun: func(cmd *Command, args []string) {\n\t\t\tfinalCmd, completions, directive, err := cmd.getCompletions(args)\n\t\t\tif err != nil {\n\t\t\t\tCompErrorln(err.Error())\n\t\t\t\t// Keep going for multiple reasons:\n\t\t\t\t// 1- There could be some valid completions even though there was an error\n\t\t\t\t// 2- Even without completions, we need to print the directive\n\t\t\t}\n\n\t\t\tnoDescriptions := cmd.CalledAs() == ShellCompNoDescRequestCmd\n\t\t\tif !noDescriptions {\n\t\t\t\tif doDescriptions, err := strconv.ParseBool(getEnvConfig(cmd, configEnvVarSuffixDescriptions)); err == nil {\n\t\t\t\t\tnoDescriptions = !doDescriptions\n\t\t\t\t}\n\t\t\t}\n\t\t\tnoActiveHelp := GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable\n\t\t\tout := finalCmd.OutOrStdout()\n\t\t\tfor _, comp := range completions {\n\t\t\t\tif noActiveHelp && strings.HasPrefix(comp, activeHelpMarker) {\n\t\t\t\t\t// Remove all activeHelp entries if it's disabled.\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif noDescriptions {\n\t\t\t\t\t// Remove any description that may be included following a tab character.\n\t\t\t\t\tcomp = strings.SplitN(comp, \"\\t\", 2)[0]\n\t\t\t\t}\n\n\t\t\t\t// Make sure we only write the first line to the output.\n\t\t\t\t// This is needed if a description contains a linebreak.\n\t\t\t\t// Otherwise the shell scripts will interpret the other lines as new flags\n\t\t\t\t// and could therefore provide a wrong completion.\n\t\t\t\tcomp = strings.SplitN(comp, \"\\n\", 2)[0]\n\n\t\t\t\t// Finally trim the completion.  This is especially important to get rid\n\t\t\t\t// of a trailing tab when there are no description following it.\n\t\t\t\t// For example, a sub-command without a description should not be completed\n\t\t\t\t// with a tab at the end (or else zsh will show a -- following it\n\t\t\t\t// although there is no description).\n\t\t\t\tcomp = strings.TrimSpace(comp)\n\n\t\t\t\t// Print each possible completion to the output for the completion script to consume.\n\t\t\t\tfmt.Fprintln(out, comp)\n\t\t\t}\n\n\t\t\t// As the last printout, print the completion directive for the completion script to parse.\n\t\t\t// The directive integer must be that last character following a single colon (:).\n\t\t\t// The completion script expects :<directive>\n\t\t\tfmt.Fprintf(out, \":%d\\n\", directive)\n\n\t\t\t// Print some helpful info to stderr for the user to understand.\n\t\t\t// Output from stderr must be ignored by the completion script.\n\t\t\tfmt.Fprintf(finalCmd.ErrOrStderr(), \"Completion ended with directive: %s\\n\", directive.string())\n\t\t},\n\t}\n\tc.AddCommand(completeCmd)\n\tsubCmd, _, err := c.Find(args)\n\tif err != nil || subCmd.Name() != ShellCompRequestCmd {\n\t\t// Only create this special command if it is actually being called.\n\t\t// This reduces possible side-effects of creating such a command;\n\t\t// for example, having this command would cause problems to a\n\t\t// cobra program that only consists of the root command, since this\n\t\t// command would cause the root command to suddenly have a subcommand.\n\t\tc.RemoveCommand(completeCmd)\n\t}\n}\n\n// SliceValue is a reduced version of [pflag.SliceValue]. It is used to detect\n// flags that accept multiple values and therefore can provide completion\n// multiple times.\ntype SliceValue interface {\n\t// GetSlice returns the flag value list as an array of strings.\n\tGetSlice() []string\n}\n\nfunc (c *Command) getCompletions(args []string) (*Command, []Completion, ShellCompDirective, error) {\n\t// The last argument, which is not completely typed by the user,\n\t// should not be part of the list of arguments\n\ttoComplete := args[len(args)-1]\n\ttrimmedArgs := args[:len(args)-1]\n\n\tvar finalCmd *Command\n\tvar finalArgs []string\n\tvar err error\n\t// Find the real command for which completion must be performed\n\t// check if we need to traverse here to parse local flags on parent commands\n\tif c.Root().TraverseChildren {\n\t\tfinalCmd, finalArgs, err = c.Root().Traverse(trimmedArgs)\n\t} else {\n\t\t// For Root commands that don't specify any value for their Args fields, when we call\n\t\t// Find(), if those Root commands don't have any sub-commands, they will accept arguments.\n\t\t// However, because we have added the __complete sub-command in the current code path, the\n\t\t// call to Find() -> legacyArgs() will return an error if there are any arguments.\n\t\t// To avoid this, we first remove the __complete command to get back to having no sub-commands.\n\t\trootCmd := c.Root()\n\t\tif len(rootCmd.Commands()) == 1 {\n\t\t\trootCmd.RemoveCommand(c)\n\t\t}\n\n\t\tfinalCmd, finalArgs, err = rootCmd.Find(trimmedArgs)\n\t}\n\tif err != nil {\n\t\t// Unable to find the real command. E.g., <program> someInvalidCmd <TAB>\n\t\treturn c, []Completion{}, ShellCompDirectiveDefault, fmt.Errorf(\"unable to find a command for arguments: %v\", trimmedArgs)\n\t}\n\tfinalCmd.ctx = c.ctx\n\n\t// These flags are normally added when `execute()` is called on `finalCmd`,\n\t// however, when doing completion, we don't call `finalCmd.execute()`.\n\t// Let's add the --help and --version flag ourselves but only if the finalCmd\n\t// has not disabled flag parsing; if flag parsing is disabled, it is up to the\n\t// finalCmd itself to handle the completion of *all* flags.\n\tif !finalCmd.DisableFlagParsing {\n\t\tfinalCmd.InitDefaultHelpFlag()\n\t\tfinalCmd.InitDefaultVersionFlag()\n\t}\n\n\t// Check if we are doing flag value completion before parsing the flags.\n\t// This is important because if we are completing a flag value, we need to also\n\t// remove the flag name argument from the list of finalArgs or else the parsing\n\t// could fail due to an invalid value (incomplete) for the flag.\n\tflag, finalArgs, toComplete, flagErr := checkIfFlagCompletion(finalCmd, finalArgs, toComplete)\n\n\t// Check if interspersed is false or -- was set on a previous arg.\n\t// This works by counting the arguments. Normally -- is not counted as arg but\n\t// if -- was already set or interspersed is false and there is already one arg then\n\t// the extra added -- is counted as arg.\n\tflagCompletion := true\n\t_ = finalCmd.ParseFlags(append(finalArgs, \"--\"))\n\tnewArgCount := finalCmd.Flags().NArg()\n\n\t// Parse the flags early so we can check if required flags are set\n\tif err = finalCmd.ParseFlags(finalArgs); err != nil {\n\t\treturn finalCmd, []Completion{}, ShellCompDirectiveDefault, fmt.Errorf(\"Error while parsing flags from args %v: %s\", finalArgs, err.Error())\n\t}\n\n\trealArgCount := finalCmd.Flags().NArg()\n\tif newArgCount > realArgCount {\n\t\t// don't do flag completion (see above)\n\t\tflagCompletion = false\n\t}\n\t// Error while attempting to parse flags\n\tif flagErr != nil {\n\t\t// If error type is flagCompError and we don't want flagCompletion we should ignore the error\n\t\tif _, ok := flagErr.(*flagCompError); !ok || flagCompletion {\n\t\t\treturn finalCmd, []Completion{}, ShellCompDirectiveDefault, flagErr\n\t\t}\n\t}\n\n\t// Look for the --help or --version flags.  If they are present,\n\t// there should be no further completions.\n\tif helpOrVersionFlagPresent(finalCmd) {\n\t\treturn finalCmd, []Completion{}, ShellCompDirectiveNoFileComp, nil\n\t}\n\n\t// We only remove the flags from the arguments if DisableFlagParsing is not set.\n\t// This is important for commands which have requested to do their own flag completion.\n\tif !finalCmd.DisableFlagParsing {\n\t\tfinalArgs = finalCmd.Flags().Args()\n\t}\n\n\tif flag != nil && flagCompletion {\n\t\t// Check if we are completing a flag value subject to annotations\n\t\tif validExts, present := flag.Annotations[BashCompFilenameExt]; present {\n\t\t\tif len(validExts) != 0 {\n\t\t\t\t// File completion filtered by extensions\n\t\t\t\treturn finalCmd, validExts, ShellCompDirectiveFilterFileExt, nil\n\t\t\t}\n\n\t\t\t// The annotation requests simple file completion.  There is no reason to do\n\t\t\t// that since it is the default behavior anyway.  Let's ignore this annotation\n\t\t\t// in case the program also registered a completion function for this flag.\n\t\t\t// Even though it is a mistake on the program's side, let's be nice when we can.\n\t\t}\n\n\t\tif subDir, present := flag.Annotations[BashCompSubdirsInDir]; present {\n\t\t\tif len(subDir) == 1 {\n\t\t\t\t// Directory completion from within a directory\n\t\t\t\treturn finalCmd, subDir, ShellCompDirectiveFilterDirs, nil\n\t\t\t}\n\t\t\t// Directory completion\n\t\t\treturn finalCmd, []Completion{}, ShellCompDirectiveFilterDirs, nil\n\t\t}\n\t}\n\n\tvar completions []Completion\n\tvar directive ShellCompDirective\n\n\t// Enforce flag groups before doing flag completions\n\tfinalCmd.enforceFlagGroupsForCompletion()\n\n\t// Note that we want to perform flagname completion even if finalCmd.DisableFlagParsing==true;\n\t// doing this allows for completion of persistent flag names even for commands that disable flag parsing.\n\t//\n\t// When doing completion of a flag name, as soon as an argument starts with\n\t// a '-' we know it is a flag.  We cannot use isFlagArg() here as it requires\n\t// the flag name to be complete\n\tif flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, \"=\") && flagCompletion {\n\t\t// First check for required flags\n\t\tcompletions = completeRequireFlags(finalCmd, toComplete)\n\n\t\t// If we have not found any required flags, only then can we show regular flags\n\t\tif len(completions) == 0 {\n\t\t\tdoCompleteFlags := func(flag *pflag.Flag) {\n\t\t\t\t_, acceptsMultiple := flag.Value.(SliceValue)\n\t\t\t\tacceptsMultiple = acceptsMultiple ||\n\t\t\t\t\tstrings.Contains(flag.Value.Type(), \"Slice\") ||\n\t\t\t\t\tstrings.Contains(flag.Value.Type(), \"Array\") ||\n\t\t\t\t\tstrings.HasPrefix(flag.Value.Type(), \"stringTo\")\n\n\t\t\t\tif !flag.Changed || acceptsMultiple {\n\t\t\t\t\t// If the flag is not already present, or if it can be specified multiple times (Array, Slice, or stringTo)\n\t\t\t\t\t// we suggest it as a completion\n\t\t\t\t\tcompletions = append(completions, getFlagNameCompletions(flag, toComplete)...)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands\n\t\t\t// that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and\n\t\t\t// non-inherited flags.\n\t\t\tfinalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {\n\t\t\t\tdoCompleteFlags(flag)\n\t\t\t})\n\t\t\t// Try to complete non-inherited flags even if DisableFlagParsing==true.\n\t\t\t// This allows programs to tell Cobra about flags for completion even\n\t\t\t// if the actual parsing of flags is not done by Cobra.\n\t\t\t// For instance, Helm uses this to provide flag name completion for\n\t\t\t// some of its plugins.\n\t\t\tfinalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {\n\t\t\t\tdoCompleteFlags(flag)\n\t\t\t})\n\t\t}\n\n\t\tdirective = ShellCompDirectiveNoFileComp\n\t\tif len(completions) == 1 && strings.HasSuffix(completions[0], \"=\") {\n\t\t\t// If there is a single completion, the shell usually adds a space\n\t\t\t// after the completion.  We don't want that if the flag ends with an =\n\t\t\tdirective = ShellCompDirectiveNoSpace\n\t\t}\n\n\t\tif !finalCmd.DisableFlagParsing {\n\t\t\t// If DisableFlagParsing==false, we have completed the flags as known by Cobra;\n\t\t\t// we can return what we found.\n\t\t\t// If DisableFlagParsing==true, Cobra may not be aware of all flags, so we\n\t\t\t// let the logic continue to see if ValidArgsFunction needs to be called.\n\t\t\treturn finalCmd, completions, directive, nil\n\t\t}\n\t} else {\n\t\tdirective = ShellCompDirectiveDefault\n\t\t// check current and parent commands for a custom DefaultShellCompDirective\n\t\tfor cmd := finalCmd; cmd != nil; cmd = cmd.parent {\n\t\t\tif cmd.CompletionOptions.DefaultShellCompDirective != nil {\n\t\t\t\tdirective = *cmd.CompletionOptions.DefaultShellCompDirective\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif flag == nil {\n\t\t\tfoundLocalNonPersistentFlag := false\n\t\t\t// If TraverseChildren is true on the root command we don't check for\n\t\t\t// local flags because we can use a local flag on a parent command\n\t\t\tif !finalCmd.Root().TraverseChildren {\n\t\t\t\t// Check if there are any local, non-persistent flags on the command-line\n\t\t\t\tlocalNonPersistentFlags := finalCmd.LocalNonPersistentFlags()\n\t\t\t\tfinalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {\n\t\t\t\t\tif localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed {\n\t\t\t\t\t\tfoundLocalNonPersistentFlag = true\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// Complete subcommand names, including the help command\n\t\t\tif len(finalArgs) == 0 && !foundLocalNonPersistentFlag {\n\t\t\t\t// We only complete sub-commands if:\n\t\t\t\t// - there are no arguments on the command-line and\n\t\t\t\t// - there are no local, non-persistent flags on the command-line or TraverseChildren is true\n\t\t\t\tfor _, subCmd := range finalCmd.Commands() {\n\t\t\t\t\tif subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {\n\t\t\t\t\t\tif strings.HasPrefix(subCmd.Name(), toComplete) {\n\t\t\t\t\t\t\tcompletions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short))\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdirective = ShellCompDirectiveNoFileComp\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Complete required flags even without the '-' prefix\n\t\t\tcompletions = append(completions, completeRequireFlags(finalCmd, toComplete)...)\n\n\t\t\t// Always complete ValidArgs, even if we are completing a subcommand name.\n\t\t\t// This is for commands that have both subcommands and ValidArgs.\n\t\t\tif len(finalCmd.ValidArgs) > 0 {\n\t\t\t\tif len(finalArgs) == 0 {\n\t\t\t\t\t// ValidArgs are only for the first argument\n\t\t\t\t\tfor _, validArg := range finalCmd.ValidArgs {\n\t\t\t\t\t\tif strings.HasPrefix(validArg, toComplete) {\n\t\t\t\t\t\t\tcompletions = append(completions, validArg)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdirective = ShellCompDirectiveNoFileComp\n\n\t\t\t\t\t// If no completions were found within commands or ValidArgs,\n\t\t\t\t\t// see if there are any ArgAliases that should be completed.\n\t\t\t\t\tif len(completions) == 0 {\n\t\t\t\t\t\tfor _, argAlias := range finalCmd.ArgAliases {\n\t\t\t\t\t\t\tif strings.HasPrefix(argAlias, toComplete) {\n\t\t\t\t\t\t\t\tcompletions = append(completions, argAlias)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// If there are ValidArgs specified (even if they don't match), we stop completion.\n\t\t\t\t// Only one of ValidArgs or ValidArgsFunction can be used for a single command.\n\t\t\t\treturn finalCmd, completions, directive, nil\n\t\t\t}\n\n\t\t\t// Let the logic continue so as to add any ValidArgsFunction completions,\n\t\t\t// even if we already found sub-commands.\n\t\t\t// This is for commands that have subcommands but also specify a ValidArgsFunction.\n\t\t}\n\t}\n\n\t// Find the completion function for the flag or command\n\tvar completionFn CompletionFunc\n\tif flag != nil && flagCompletion {\n\t\tflagCompletionMutex.RLock()\n\t\tcompletionFn = flagCompletionFunctions[flag]\n\t\tflagCompletionMutex.RUnlock()\n\t} else {\n\t\tcompletionFn = finalCmd.ValidArgsFunction\n\t}\n\tif completionFn != nil {\n\t\t// Go custom completion defined for this flag or command.\n\t\t// Call the registered completion function to get the completions.\n\t\tvar comps []Completion\n\t\tcomps, directive = completionFn(finalCmd, finalArgs, toComplete)\n\t\tcompletions = append(completions, comps...)\n\t}\n\n\treturn finalCmd, completions, directive, nil\n}\n\nfunc helpOrVersionFlagPresent(cmd *Command) bool {\n\tif versionFlag := cmd.Flags().Lookup(\"version\"); versionFlag != nil &&\n\t\tlen(versionFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && versionFlag.Changed {\n\t\treturn true\n\t}\n\tif helpFlag := cmd.Flags().Lookup(helpFlagName); helpFlag != nil &&\n\t\tlen(helpFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && helpFlag.Changed {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc getFlagNameCompletions(flag *pflag.Flag, toComplete string) []Completion {\n\tif nonCompletableFlag(flag) {\n\t\treturn []Completion{}\n\t}\n\n\tvar completions []Completion\n\tflagName := \"--\" + flag.Name\n\tif strings.HasPrefix(flagName, toComplete) {\n\t\t// Flag without the =\n\t\tcompletions = append(completions, CompletionWithDesc(flagName, flag.Usage))\n\n\t\t// Why suggest both long forms: --flag and --flag= ?\n\t\t// This forces the user to *always* have to type either an = or a space after the flag name.\n\t\t// Let's be nice and avoid making users have to do that.\n\t\t// Since boolean flags and shortname flags don't show the = form, let's go that route and never show it.\n\t\t// The = form will still work, we just won't suggest it.\n\t\t// This also makes the list of suggested flags shorter as we avoid all the = forms.\n\t\t//\n\t\t// if len(flag.NoOptDefVal) == 0 {\n\t\t// \t// Flag requires a value, so it can be suffixed with =\n\t\t// \tflagName += \"=\"\n\t\t// \tcompletions = append(completions, CompletionWithDesc(flagName, flag.Usage))\n\t\t// }\n\t}\n\n\tflagName = \"-\" + flag.Shorthand\n\tif len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) {\n\t\tcompletions = append(completions, CompletionWithDesc(flagName, flag.Usage))\n\t}\n\n\treturn completions\n}\n\nfunc completeRequireFlags(finalCmd *Command, toComplete string) []Completion {\n\tvar completions []Completion\n\n\tdoCompleteRequiredFlags := func(flag *pflag.Flag) {\n\t\tif _, present := flag.Annotations[BashCompOneRequiredFlag]; present {\n\t\t\tif !flag.Changed {\n\t\t\t\t// If the flag is not already present, we suggest it as a completion\n\t\t\t\tcompletions = append(completions, getFlagNameCompletions(flag, toComplete)...)\n\t\t\t}\n\t\t}\n\t}\n\n\t// We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands\n\t// that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and\n\t// non-inherited flags.\n\tfinalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {\n\t\tdoCompleteRequiredFlags(flag)\n\t})\n\tfinalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {\n\t\tdoCompleteRequiredFlags(flag)\n\t})\n\n\treturn completions\n}\n\nfunc checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) {\n\tif finalCmd.DisableFlagParsing {\n\t\t// We only do flag completion if we are allowed to parse flags\n\t\t// This is important for commands which have requested to do their own flag completion.\n\t\treturn nil, args, lastArg, nil\n\t}\n\n\tvar flagName string\n\ttrimmedArgs := args\n\tflagWithEqual := false\n\torgLastArg := lastArg\n\n\t// When doing completion of a flag name, as soon as an argument starts with\n\t// a '-' we know it is a flag.  We cannot use isFlagArg() here as that function\n\t// requires the flag name to be complete\n\tif len(lastArg) > 0 && lastArg[0] == '-' {\n\t\tif index := strings.Index(lastArg, \"=\"); index >= 0 {\n\t\t\t// Flag with an =\n\t\t\tif strings.HasPrefix(lastArg[:index], \"--\") {\n\t\t\t\t// Flag has full name\n\t\t\t\tflagName = lastArg[2:index]\n\t\t\t} else {\n\t\t\t\t// Flag is shorthand\n\t\t\t\t// We have to get the last shorthand flag name\n\t\t\t\t// e.g. `-asd` => d to provide the correct completion\n\t\t\t\t// https://github.com/spf13/cobra/issues/1257\n\t\t\t\tflagName = lastArg[index-1 : index]\n\t\t\t}\n\t\t\tlastArg = lastArg[index+1:]\n\t\t\tflagWithEqual = true\n\t\t} else {\n\t\t\t// Normal flag completion\n\t\t\treturn nil, args, lastArg, nil\n\t\t}\n\t}\n\n\tif len(flagName) == 0 {\n\t\tif len(args) > 0 {\n\t\t\tprevArg := args[len(args)-1]\n\t\t\tif isFlagArg(prevArg) {\n\t\t\t\t// Only consider the case where the flag does not contain an =.\n\t\t\t\t// If the flag contains an = it means it has already been fully processed,\n\t\t\t\t// so we don't need to deal with it here.\n\t\t\t\tif index := strings.Index(prevArg, \"=\"); index < 0 {\n\t\t\t\t\tif strings.HasPrefix(prevArg, \"--\") {\n\t\t\t\t\t\t// Flag has full name\n\t\t\t\t\t\tflagName = prevArg[2:]\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Flag is shorthand\n\t\t\t\t\t\t// We have to get the last shorthand flag name\n\t\t\t\t\t\t// e.g. `-asd` => d to provide the correct completion\n\t\t\t\t\t\t// https://github.com/spf13/cobra/issues/1257\n\t\t\t\t\t\tflagName = prevArg[len(prevArg)-1:]\n\t\t\t\t\t}\n\t\t\t\t\t// Remove the uncompleted flag or else there could be an error created\n\t\t\t\t\t// for an invalid value for that flag\n\t\t\t\t\ttrimmedArgs = args[:len(args)-1]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(flagName) == 0 {\n\t\t// Not doing flag completion\n\t\treturn nil, trimmedArgs, lastArg, nil\n\t}\n\n\tflag := findFlag(finalCmd, flagName)\n\tif flag == nil {\n\t\t// Flag not supported by this command, the interspersed option might be set so return the original args\n\t\treturn nil, args, orgLastArg, &flagCompError{subCommand: finalCmd.Name(), flagName: flagName}\n\t}\n\n\tif !flagWithEqual {\n\t\tif len(flag.NoOptDefVal) != 0 {\n\t\t\t// We had assumed dealing with a two-word flag but the flag is a boolean flag.\n\t\t\t// In that case, there is no value following it, so we are not really doing flag completion.\n\t\t\t// Reset everything to do noun completion.\n\t\t\ttrimmedArgs = args\n\t\t\tflag = nil\n\t\t}\n\t}\n\n\treturn flag, trimmedArgs, lastArg, nil\n}\n\n// InitDefaultCompletionCmd adds a default 'completion' command to c.\n// This function will do nothing if any of the following is true:\n// 1- the feature has been explicitly disabled by the program,\n// 2- c has no subcommands (to avoid creating one),\n// 3- c already has a 'completion' command provided by the program.\nfunc (c *Command) InitDefaultCompletionCmd(args ...string) {\n\tif c.CompletionOptions.DisableDefaultCmd {\n\t\treturn\n\t}\n\n\tfor _, cmd := range c.commands {\n\t\tif cmd.Name() == compCmdName || cmd.HasAlias(compCmdName) {\n\t\t\t// A completion command is already available\n\t\t\treturn\n\t\t}\n\t}\n\n\thaveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions\n\n\t// Special case to know if there are sub-commands or not.\n\thasSubCommands := false\n\tfor _, cmd := range c.commands {\n\t\tif cmd.Name() != ShellCompRequestCmd && cmd.Name() != helpCommandName {\n\t\t\t// We found a real sub-command (not 'help' or '__complete')\n\t\t\thasSubCommands = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tcompletionCmd := &Command{\n\t\tUse:   compCmdName,\n\t\tShort: \"Generate the autocompletion script for the specified shell\",\n\t\tLong: fmt.Sprintf(`Generate the autocompletion script for %[1]s for the specified shell.\nSee each sub-command's help for details on how to use the generated script.\n`, c.Root().Name()),\n\t\tArgs:              NoArgs,\n\t\tValidArgsFunction: NoFileCompletions,\n\t\tHidden:            c.CompletionOptions.HiddenDefaultCmd,\n\t\tGroupID:           c.completionCommandGroupID,\n\t}\n\tc.AddCommand(completionCmd)\n\n\tif !hasSubCommands {\n\t\t// If the 'completion' command will be the only sub-command,\n\t\t// we only create it if it is actually being called.\n\t\t// This avoids breaking programs that would suddenly find themselves with\n\t\t// a subcommand, which would prevent them from accepting arguments.\n\t\t// We also create the 'completion' command if the user is triggering\n\t\t// shell completion for it (prog __complete completion '')\n\t\tsubCmd, cmdArgs, err := c.Find(args)\n\t\tif err != nil || subCmd.Name() != compCmdName &&\n\t\t\t(subCmd.Name() != ShellCompRequestCmd || len(cmdArgs) <= 1 || cmdArgs[0] != compCmdName) {\n\t\t\t// The completion command is not being called or being completed so we remove it.\n\t\t\tc.RemoveCommand(completionCmd)\n\t\t\treturn\n\t\t}\n\t}\n\n\tout := c.OutOrStdout()\n\tnoDesc := c.CompletionOptions.DisableDescriptions\n\tshortDesc := \"Generate the autocompletion script for %s\"\n\tbash := &Command{\n\t\tUse:   \"bash\",\n\t\tShort: fmt.Sprintf(shortDesc, \"bash\"),\n\t\tLong: fmt.Sprintf(`Generate the autocompletion script for the bash shell.\n\nThis script depends on the 'bash-completion' package.\nIf it is not installed already, you can install it via your OS's package manager.\n\nTo load completions in your current shell session:\n\n\tsource <(%[1]s completion bash)\n\nTo load completions for every new session, execute once:\n\n#### Linux:\n\n\t%[1]s completion bash > /etc/bash_completion.d/%[1]s\n\n#### macOS:\n\n\t%[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s\n\nYou will need to start a new shell for this setup to take effect.\n`, c.Root().Name()),\n\t\tArgs:                  NoArgs,\n\t\tDisableFlagsInUseLine: true,\n\t\tValidArgsFunction:     NoFileCompletions,\n\t\tRunE: func(cmd *Command, args []string) error {\n\t\t\treturn cmd.Root().GenBashCompletionV2(out, !noDesc)\n\t\t},\n\t}\n\tif haveNoDescFlag {\n\t\tbash.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)\n\t}\n\n\tzsh := &Command{\n\t\tUse:   \"zsh\",\n\t\tShort: fmt.Sprintf(shortDesc, \"zsh\"),\n\t\tLong: fmt.Sprintf(`Generate the autocompletion script for the zsh shell.\n\nIf shell completion is not already enabled in your environment you will need\nto enable it.  You can execute the following once:\n\n\techo \"autoload -U compinit; compinit\" >> ~/.zshrc\n\nTo load completions in your current shell session:\n\n\tsource <(%[1]s completion zsh)\n\nTo load completions for every new session, execute once:\n\n#### Linux:\n\n\t%[1]s completion zsh > \"${fpath[1]}/_%[1]s\"\n\n#### macOS:\n\n\t%[1]s completion zsh > $(brew --prefix)/share/zsh/site-functions/_%[1]s\n\nYou will need to start a new shell for this setup to take effect.\n`, c.Root().Name()),\n\t\tArgs:              NoArgs,\n\t\tValidArgsFunction: NoFileCompletions,\n\t\tRunE: func(cmd *Command, args []string) error {\n\t\t\tif noDesc {\n\t\t\t\treturn cmd.Root().GenZshCompletionNoDesc(out)\n\t\t\t}\n\t\t\treturn cmd.Root().GenZshCompletion(out)\n\t\t},\n\t}\n\tif haveNoDescFlag {\n\t\tzsh.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)\n\t}\n\n\tfish := &Command{\n\t\tUse:   \"fish\",\n\t\tShort: fmt.Sprintf(shortDesc, \"fish\"),\n\t\tLong: fmt.Sprintf(`Generate the autocompletion script for the fish shell.\n\nTo load completions in your current shell session:\n\n\t%[1]s completion fish | source\n\nTo load completions for every new session, execute once:\n\n\t%[1]s completion fish > ~/.config/fish/completions/%[1]s.fish\n\nYou will need to start a new shell for this setup to take effect.\n`, c.Root().Name()),\n\t\tArgs:              NoArgs,\n\t\tValidArgsFunction: NoFileCompletions,\n\t\tRunE: func(cmd *Command, args []string) error {\n\t\t\treturn cmd.Root().GenFishCompletion(out, !noDesc)\n\t\t},\n\t}\n\tif haveNoDescFlag {\n\t\tfish.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)\n\t}\n\n\tpowershell := &Command{\n\t\tUse:   \"powershell\",\n\t\tShort: fmt.Sprintf(shortDesc, \"powershell\"),\n\t\tLong: fmt.Sprintf(`Generate the autocompletion script for powershell.\n\nTo load completions in your current shell session:\n\n\t%[1]s completion powershell | Out-String | Invoke-Expression\n\nTo load completions for every new session, add the output of the above command\nto your powershell profile.\n`, c.Root().Name()),\n\t\tArgs:              NoArgs,\n\t\tValidArgsFunction: NoFileCompletions,\n\t\tRunE: func(cmd *Command, args []string) error {\n\t\t\tif noDesc {\n\t\t\t\treturn cmd.Root().GenPowerShellCompletion(out)\n\t\t\t}\n\t\t\treturn cmd.Root().GenPowerShellCompletionWithDesc(out)\n\n\t\t},\n\t}\n\tif haveNoDescFlag {\n\t\tpowershell.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)\n\t}\n\n\tcompletionCmd.AddCommand(bash, zsh, fish, powershell)\n}\n\nfunc findFlag(cmd *Command, name string) *pflag.Flag {\n\tflagSet := cmd.Flags()\n\tif len(name) == 1 {\n\t\t// First convert the short flag into a long flag\n\t\t// as the cmd.Flag() search only accepts long flags\n\t\tif short := flagSet.ShorthandLookup(name); short != nil {\n\t\t\tname = short.Name\n\t\t} else {\n\t\t\tset := cmd.InheritedFlags()\n\t\t\tif short = set.ShorthandLookup(name); short != nil {\n\t\t\t\tname = short.Name\n\t\t\t} else {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\treturn cmd.Flag(name)\n}\n\n// CompDebug prints the specified string to the same file as where the\n// completion script prints its logs.\n// Note that completion printouts should never be on stdout as they would\n// be wrongly interpreted as actual completion choices by the completion script.\nfunc CompDebug(msg string, printToStdErr bool) {\n\tmsg = fmt.Sprintf(\"[Debug] %s\", msg)\n\n\t// Such logs are only printed when the user has set the environment\n\t// variable BASH_COMP_DEBUG_FILE to the path of some file to be used.\n\tif path := os.Getenv(\"BASH_COMP_DEBUG_FILE\"); path != \"\" {\n\t\tf, err := os.OpenFile(path,\n\t\t\tos.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\t\tif err == nil {\n\t\t\tdefer f.Close()\n\t\t\tWriteStringAndCheck(f, msg)\n\t\t}\n\t}\n\n\tif printToStdErr {\n\t\t// Must print to stderr for this not to be read by the completion script.\n\t\tfmt.Fprint(os.Stderr, msg)\n\t}\n}\n\n// CompDebugln prints the specified string with a newline at the end\n// to the same file as where the completion script prints its logs.\n// Such logs are only printed when the user has set the environment\n// variable BASH_COMP_DEBUG_FILE to the path of some file to be used.\nfunc CompDebugln(msg string, printToStdErr bool) {\n\tCompDebug(fmt.Sprintf(\"%s\\n\", msg), printToStdErr)\n}\n\n// CompError prints the specified completion message to stderr.\nfunc CompError(msg string) {\n\tmsg = fmt.Sprintf(\"[Error] %s\", msg)\n\tCompDebug(msg, true)\n}\n\n// CompErrorln prints the specified completion message to stderr with a newline at the end.\nfunc CompErrorln(msg string) {\n\tCompError(fmt.Sprintf(\"%s\\n\", msg))\n}\n\n// These values should not be changed: users will be using them explicitly.\nconst (\n\tconfigEnvVarGlobalPrefix       = \"COBRA\"\n\tconfigEnvVarSuffixDescriptions = \"COMPLETION_DESCRIPTIONS\"\n)\n\nvar configEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`)\n\n// configEnvVar returns the name of the program-specific configuration environment\n// variable.  It has the format <PROGRAM>_<SUFFIX> where <PROGRAM> is the name of the\n// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`.\nfunc configEnvVar(name, suffix string) string {\n\t// This format should not be changed: users will be using it explicitly.\n\tv := strings.ToUpper(fmt.Sprintf(\"%s_%s\", name, suffix))\n\tv = configEnvVarPrefixSubstRegexp.ReplaceAllString(v, \"_\")\n\treturn v\n}\n\n// getEnvConfig returns the value of the configuration environment variable\n// <PROGRAM>_<SUFFIX> where <PROGRAM> is the name of the root command in upper\n// case, with all non-ASCII-alphanumeric characters replaced by `_`.\n// If the value is empty or not set, the value of the environment variable\n// COBRA_<SUFFIX> is returned instead.\nfunc getEnvConfig(cmd *Command, suffix string) string {\n\tv := os.Getenv(configEnvVar(cmd.Root().Name(), suffix))\n\tif v == \"\" {\n\t\tv = os.Getenv(configEnvVar(configEnvVarGlobalPrefix, suffix))\n\t}\n\treturn v\n}\n"
  },
  {
    "path": "completions_test.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n)\n\nfunc validArgsFunc(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\tif len(args) != 0 {\n\t\treturn nil, ShellCompDirectiveNoFileComp\n\t}\n\n\tvar completions []string\n\tfor _, comp := range []string{\"one\\tThe first\", \"two\\tThe second\"} {\n\t\tif strings.HasPrefix(comp, toComplete) {\n\t\t\tcompletions = append(completions, comp)\n\t\t}\n\t}\n\treturn completions, ShellCompDirectiveDefault\n}\n\nfunc validArgsFunc2(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\tif len(args) != 0 {\n\t\treturn nil, ShellCompDirectiveNoFileComp\n\t}\n\n\tvar completions []string\n\tfor _, comp := range []string{\"three\\tThe third\", \"four\\tThe fourth\"} {\n\t\tif strings.HasPrefix(comp, toComplete) {\n\t\t\tcompletions = append(completions, comp)\n\t\t}\n\t}\n\treturn completions, ShellCompDirectiveDefault\n}\n\nfunc TestCmdNameCompletionInGo(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\tchildCmd1 := &Command{\n\t\tUse:   \"firstChild\",\n\t\tShort: \"First command\",\n\t\tRun:   emptyRun,\n\t}\n\tchildCmd2 := &Command{\n\t\tUse: \"secondChild\",\n\t\tRun: emptyRun,\n\t}\n\thiddenCmd := &Command{\n\t\tUse:    \"testHidden\",\n\t\tHidden: true, // Not completed\n\t\tRun:    emptyRun,\n\t}\n\tdeprecatedCmd := &Command{\n\t\tUse:        \"testDeprecated\",\n\t\tDeprecated: \"deprecated\", // Not completed\n\t\tRun:        emptyRun,\n\t}\n\taliasedCmd := &Command{\n\t\tUse:     \"aliased\",\n\t\tShort:   \"A command with aliases\",\n\t\tAliases: []string{\"testAlias\", \"testSynonym\"}, // Not completed\n\t\tRun:     emptyRun,\n\t}\n\n\trootCmd.AddCommand(childCmd1, childCmd2, hiddenCmd, deprecatedCmd, aliasedCmd)\n\n\t// Test that sub-command names are completed\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"aliased\",\n\t\t\"completion\",\n\t\t\"firstChild\",\n\t\t\"help\",\n\t\t\"secondChild\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that sub-command names are completed with prefix\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"s\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"secondChild\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that even with no valid sub-command matches, hidden, deprecated and\n\t// aliases are not completed\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"test\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that sub-command names are completed with description\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"aliased\\tA command with aliases\",\n\t\t\"completion\\tGenerate the autocompletion script for the specified shell\",\n\t\t\"firstChild\\tFirst command\",\n\t\t\"help\\tHelp about any command\",\n\t\t\"secondChild\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestNoCmdNameCompletionInGo(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\trootCmd.Flags().String(\"localroot\", \"\", \"local root flag\")\n\n\tchildCmd1 := &Command{\n\t\tUse:   \"childCmd1\",\n\t\tShort: \"First command\",\n\t\tArgs:  MinimumNArgs(0),\n\t\tRun:   emptyRun,\n\t}\n\trootCmd.AddCommand(childCmd1)\n\tchildCmd1.PersistentFlags().StringP(\"persistent\", \"p\", \"\", \"persistent flag\")\n\tpersistentFlag := childCmd1.PersistentFlags().Lookup(\"persistent\")\n\tchildCmd1.Flags().StringP(\"nonPersistent\", \"n\", \"\", \"non-persistent flag\")\n\tnonPersistentFlag := childCmd1.Flags().Lookup(\"nonPersistent\")\n\n\tchildCmd2 := &Command{\n\t\tUse: \"childCmd2\",\n\t\tRun: emptyRun,\n\t}\n\tchildCmd1.AddCommand(childCmd2)\n\n\t// Test that sub-command names are not completed if there is an argument already\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"childCmd1\", \"arg1\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that sub-command names are not completed if a local non-persistent flag is present\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"childCmd1\", \"--nonPersistent\", \"value\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\t// Reset the flag for the next command\n\tnonPersistentFlag.Changed = false\n\n\texpected = strings.Join([]string{\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that sub-command names are completed if a local non-persistent flag is present and TraverseChildren is set to true\n\t// set TraverseChildren to true on the root cmd\n\trootCmd.TraverseChildren = true\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--localroot\", \"value\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\t// Reset TraverseChildren for next command\n\trootCmd.TraverseChildren = false\n\n\texpected = strings.Join([]string{\n\t\t\"childCmd1\",\n\t\t\"completion\",\n\t\t\"help\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that sub-command names from a child cmd are completed if a local non-persistent flag is present\n\t// and TraverseChildren is set to true on the root cmd\n\trootCmd.TraverseChildren = true\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--localroot\", \"value\", \"childCmd1\", \"--nonPersistent\", \"value\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\t// Reset TraverseChildren for next command\n\trootCmd.TraverseChildren = false\n\t// Reset the flag for the next command\n\tnonPersistentFlag.Changed = false\n\n\texpected = strings.Join([]string{\n\t\t\"childCmd2\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that we don't use Traverse when we shouldn't.\n\t// This command should not return a completion since the command line is invalid without TraverseChildren.\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--localroot\", \"value\", \"childCmd1\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that sub-command names are not completed if a local non-persistent short flag is present\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"childCmd1\", \"-n\", \"value\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\t// Reset the flag for the next command\n\tnonPersistentFlag.Changed = false\n\n\texpected = strings.Join([]string{\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that sub-command names are completed with a persistent flag\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"childCmd1\", \"--persistent\", \"value\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\t// Reset the flag for the next command\n\tpersistentFlag.Changed = false\n\n\texpected = strings.Join([]string{\n\t\t\"childCmd2\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that sub-command names are completed with a persistent short flag\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"childCmd1\", \"-p\", \"value\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\t// Reset the flag for the next command\n\tpersistentFlag.Changed = false\n\n\texpected = strings.Join([]string{\n\t\t\"childCmd2\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestValidArgsCompletionInGo(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse:       \"root\",\n\t\tValidArgs: []string{\"one\", \"two\", \"three\"},\n\t\tArgs:      MinimumNArgs(1),\n\t}\n\n\t// Test that validArgs are completed\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"one\",\n\t\t\"two\",\n\t\t\"three\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that validArgs are completed with prefix\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"o\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"one\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that validArgs don't repeat\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"one\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestValidArgsAndCmdCompletionInGo(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse:       \"root\",\n\t\tValidArgs: []string{\"one\", \"two\"},\n\t\tRun:       emptyRun,\n\t}\n\n\tchildCmd := &Command{\n\t\tUse: \"thechild\",\n\t\tRun: emptyRun,\n\t}\n\n\trootCmd.AddCommand(childCmd)\n\n\t// Test that both sub-commands and validArgs are completed\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"completion\",\n\t\t\"help\",\n\t\t\"thechild\",\n\t\t\"one\",\n\t\t\"two\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that both sub-commands and validArgs are completed with prefix\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"t\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"thechild\",\n\t\t\"two\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestValidArgsFuncAndCmdCompletionInGo(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse:               \"root\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun:               emptyRun,\n\t}\n\n\tchildCmd := &Command{\n\t\tUse:   \"thechild\",\n\t\tShort: \"The child command\",\n\t\tRun:   emptyRun,\n\t}\n\n\trootCmd.AddCommand(childCmd)\n\n\t// Test that both sub-commands and validArgsFunction are completed\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"completion\",\n\t\t\"help\",\n\t\t\"thechild\",\n\t\t\"one\",\n\t\t\"two\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that both sub-commands and validArgs are completed with prefix\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"t\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"thechild\",\n\t\t\"two\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that both sub-commands and validArgs are completed with description\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"t\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"thechild\\tThe child command\",\n\t\t\"two\\tThe second\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestFlagNameCompletionInGo(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\tchildCmd := &Command{\n\t\tUse:     \"childCmd\",\n\t\tVersion: \"1.2.3\",\n\t\tRun:     emptyRun,\n\t}\n\trootCmd.AddCommand(childCmd)\n\n\trootCmd.Flags().IntP(\"first\", \"f\", -1, \"first flag\")\n\trootCmd.PersistentFlags().BoolP(\"second\", \"s\", false, \"second flag\")\n\tchildCmd.Flags().String(\"subFlag\", \"\", \"sub flag\")\n\n\t// Test that flag names are not shown if the user has not given the '-' prefix\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"childCmd\",\n\t\t\"completion\",\n\t\t\"help\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that flag names are completed\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"-\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--first\",\n\t\t\"-f\",\n\t\t\"--help\",\n\t\t\"-h\",\n\t\t\"--second\",\n\t\t\"-s\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that flag names are completed when a prefix is given\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--f\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--first\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that flag names are completed in a sub-cmd\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"childCmd\", \"-\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--second\",\n\t\t\"-s\",\n\t\t\"--help\",\n\t\t\"-h\",\n\t\t\"--subFlag\",\n\t\t\"--version\",\n\t\t\"-v\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestFlagNameCompletionInGoWithDesc(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\tchildCmd := &Command{\n\t\tUse:     \"childCmd\",\n\t\tShort:   \"first command\",\n\t\tVersion: \"1.2.3\",\n\t\tRun:     emptyRun,\n\t}\n\trootCmd.AddCommand(childCmd)\n\n\trootCmd.Flags().IntP(\"first\", \"f\", -1, \"first flag\\nlonger description for flag\")\n\trootCmd.PersistentFlags().BoolP(\"second\", \"s\", false, \"second flag\")\n\tchildCmd.Flags().String(\"subFlag\", \"\", \"sub flag\")\n\n\t// Test that flag names are not shown if the user has not given the '-' prefix\n\toutput, err := executeCommand(rootCmd, ShellCompRequestCmd, \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"childCmd\\tfirst command\",\n\t\t\"completion\\tGenerate the autocompletion script for the specified shell\",\n\t\t\"help\\tHelp about any command\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that flag names are completed\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"-\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--first\\tfirst flag\",\n\t\t\"-f\\tfirst flag\",\n\t\t\"--help\\thelp for root\",\n\t\t\"-h\\thelp for root\",\n\t\t\"--second\\tsecond flag\",\n\t\t\"-s\\tsecond flag\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that flag names are completed when a prefix is given\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"--f\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--first\\tfirst flag\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that flag names are completed in a sub-cmd\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"childCmd\", \"-\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--second\\tsecond flag\",\n\t\t\"-s\\tsecond flag\",\n\t\t\"--help\\thelp for childCmd\",\n\t\t\"-h\\thelp for childCmd\",\n\t\t\"--subFlag\\tsub flag\",\n\t\t\"--version\\tversion for childCmd\",\n\t\t\"-v\\tversion for childCmd\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\n// customMultiString is a custom Value type that accepts multiple values,\n// but does not include \"Slice\" or \"Array\" in its \"Type\" string.\ntype customMultiString []string\n\nvar _ SliceValue = (*customMultiString)(nil)\n\nfunc (s *customMultiString) String() string {\n\treturn fmt.Sprintf(\"%v\", *s)\n}\n\nfunc (s *customMultiString) Set(v string) error {\n\t*s = append(*s, v)\n\treturn nil\n}\n\nfunc (s *customMultiString) Type() string {\n\treturn \"multi string\"\n}\n\nfunc (s *customMultiString) GetSlice() []string {\n\treturn *s\n}\n\nfunc TestFlagNameCompletionRepeat(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\tchildCmd := &Command{\n\t\tUse:   \"childCmd\",\n\t\tShort: \"first command\",\n\t\tRun:   emptyRun,\n\t}\n\trootCmd.AddCommand(childCmd)\n\n\trootCmd.Flags().IntP(\"first\", \"f\", -1, \"first flag\")\n\tfirstFlag := rootCmd.Flags().Lookup(\"first\")\n\trootCmd.Flags().BoolP(\"second\", \"s\", false, \"second flag\")\n\tsecondFlag := rootCmd.Flags().Lookup(\"second\")\n\trootCmd.Flags().StringArrayP(\"array\", \"a\", nil, \"array flag\")\n\tarrayFlag := rootCmd.Flags().Lookup(\"array\")\n\trootCmd.Flags().IntSliceP(\"slice\", \"l\", nil, \"slice flag\")\n\tsliceFlag := rootCmd.Flags().Lookup(\"slice\")\n\trootCmd.Flags().BoolSliceP(\"bslice\", \"b\", nil, \"bool slice flag\")\n\tbsliceFlag := rootCmd.Flags().Lookup(\"bslice\")\n\trootCmd.Flags().VarP(&customMultiString{}, \"multi\", \"m\", \"multi string flag\")\n\tmultiFlag := rootCmd.Flags().Lookup(\"multi\")\n\n\t// Test that flag names are not repeated unless they are an array or slice\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--first\", \"1\", \"--\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\t// Reset the flag for the next command\n\tfirstFlag.Changed = false\n\n\texpected := strings.Join([]string{\n\t\t\"--array\",\n\t\t\"--bslice\",\n\t\t\"--help\",\n\t\t\"--multi\",\n\t\t\"--second\",\n\t\t\"--slice\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that flag names are not repeated unless they are an array or slice\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--first\", \"1\", \"--second=false\", \"--\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\t// Reset the flag for the next command\n\tfirstFlag.Changed = false\n\tsecondFlag.Changed = false\n\n\texpected = strings.Join([]string{\n\t\t\"--array\",\n\t\t\"--bslice\",\n\t\t\"--help\",\n\t\t\"--multi\",\n\t\t\"--slice\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that flag names are not repeated unless they are an array or slice\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--slice\", \"1\", \"--slice=2\", \"--array\", \"val\", \"--bslice\", \"true\", \"--multi\", \"val\", \"--\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\t// Reset the flag for the next command\n\tsliceFlag.Changed = false\n\tarrayFlag.Changed = false\n\tbsliceFlag.Changed = false\n\tmultiFlag.Changed = false\n\n\texpected = strings.Join([]string{\n\t\t\"--array\",\n\t\t\"--bslice\",\n\t\t\"--first\",\n\t\t\"--help\",\n\t\t\"--multi\",\n\t\t\"--second\",\n\t\t\"--slice\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that flag names are not repeated unless they are an array or slice, using shortname\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"-l\", \"1\", \"-l=2\", \"-a\", \"val\", \"-\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\t// Reset the flag for the next command\n\tsliceFlag.Changed = false\n\tarrayFlag.Changed = false\n\tmultiFlag.Changed = false\n\n\texpected = strings.Join([]string{\n\t\t\"--array\",\n\t\t\"-a\",\n\t\t\"--bslice\",\n\t\t\"-b\",\n\t\t\"--first\",\n\t\t\"-f\",\n\t\t\"--help\",\n\t\t\"-h\",\n\t\t\"--multi\",\n\t\t\"-m\",\n\t\t\"--second\",\n\t\t\"-s\",\n\t\t\"--slice\",\n\t\t\"-l\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that flag names are not repeated unless they are an array or slice, using shortname with prefix\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"-l\", \"1\", \"-l=2\", \"-a\", \"val\", \"-a\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\t// Reset the flag for the next command\n\tsliceFlag.Changed = false\n\tarrayFlag.Changed = false\n\tmultiFlag.Changed = false\n\n\texpected = strings.Join([]string{\n\t\t\"-a\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestRequiredFlagNameCompletionInGo(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse:       \"root\",\n\t\tValidArgs: []string{\"realArg\"},\n\t\tRun:       emptyRun,\n\t}\n\tchildCmd := &Command{\n\t\tUse: \"childCmd\",\n\t\tValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\t\treturn []string{\"subArg\"}, ShellCompDirectiveNoFileComp\n\t\t},\n\t\tRun: emptyRun,\n\t}\n\trootCmd.AddCommand(childCmd)\n\n\trootCmd.Flags().IntP(\"requiredFlag\", \"r\", -1, \"required flag\")\n\tassertNoErr(t, rootCmd.MarkFlagRequired(\"requiredFlag\"))\n\trequiredFlag := rootCmd.Flags().Lookup(\"requiredFlag\")\n\n\trootCmd.PersistentFlags().IntP(\"requiredPersistent\", \"p\", -1, \"required persistent\")\n\tassertNoErr(t, rootCmd.MarkPersistentFlagRequired(\"requiredPersistent\"))\n\trequiredPersistent := rootCmd.PersistentFlags().Lookup(\"requiredPersistent\")\n\n\trootCmd.Flags().StringP(\"release\", \"R\", \"\", \"Release name\")\n\n\tchildCmd.Flags().BoolP(\"subRequired\", \"s\", false, \"sub required flag\")\n\tassertNoErr(t, childCmd.MarkFlagRequired(\"subRequired\"))\n\tchildCmd.Flags().BoolP(\"subNotRequired\", \"n\", false, \"sub not required flag\")\n\n\t// Test that a required flag is suggested even without the - prefix\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"childCmd\",\n\t\t\"completion\",\n\t\t\"help\",\n\t\t\"--requiredFlag\",\n\t\t\"-r\",\n\t\t\"--requiredPersistent\",\n\t\t\"-p\",\n\t\t\"realArg\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that a required flag is suggested without other flags when using the '-' prefix\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"-\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--requiredFlag\",\n\t\t\"-r\",\n\t\t\"--requiredPersistent\",\n\t\t\"-p\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that if no required flag matches, the normal flags are suggested\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--relea\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--release\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test required flags for sub-commands\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"childCmd\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--requiredPersistent\",\n\t\t\"-p\",\n\t\t\"--subRequired\",\n\t\t\"-s\",\n\t\t\"subArg\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"childCmd\", \"-\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--requiredPersistent\",\n\t\t\"-p\",\n\t\t\"--subRequired\",\n\t\t\"-s\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"childCmd\", \"--subNot\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--subNotRequired\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that when a required flag is present, it is not suggested anymore\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--requiredFlag\", \"1\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\t// Reset the flag for the next command\n\trequiredFlag.Changed = false\n\n\texpected = strings.Join([]string{\n\t\t\"--requiredPersistent\",\n\t\t\"-p\",\n\t\t\"realArg\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that when a persistent required flag is present, it is not suggested anymore\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--requiredPersistent\", \"1\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\t// Reset the flag for the next command\n\trequiredPersistent.Changed = false\n\n\texpected = strings.Join([]string{\n\t\t\"childCmd\",\n\t\t\"completion\",\n\t\t\"help\",\n\t\t\"--requiredFlag\",\n\t\t\"-r\",\n\t\t\"realArg\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that when all required flags are present, normal completion is done\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--requiredFlag\", \"1\", \"--requiredPersistent\", \"1\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\t// Reset the flags for the next command\n\trequiredFlag.Changed = false\n\trequiredPersistent.Changed = false\n\n\texpected = strings.Join([]string{\n\t\t\"realArg\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestFlagFileExtFilterCompletionInGo(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\n\t// No extensions.  Should be ignored.\n\trootCmd.Flags().StringP(\"file\", \"f\", \"\", \"file flag\")\n\tassertNoErr(t, rootCmd.MarkFlagFilename(\"file\"))\n\n\t// Single extension\n\trootCmd.Flags().StringP(\"log\", \"l\", \"\", \"log flag\")\n\tassertNoErr(t, rootCmd.MarkFlagFilename(\"log\", \"log\"))\n\n\t// Multiple extensions\n\trootCmd.Flags().StringP(\"yaml\", \"y\", \"\", \"yaml flag\")\n\tassertNoErr(t, rootCmd.MarkFlagFilename(\"yaml\", \"yaml\", \"yml\"))\n\n\t// Directly using annotation\n\trootCmd.Flags().StringP(\"text\", \"t\", \"\", \"text flag\")\n\tassertNoErr(t, rootCmd.Flags().SetAnnotation(\"text\", BashCompFilenameExt, []string{\"txt\"}))\n\n\t// Test that the completion logic returns the proper info for the completion\n\t// script to handle the file filtering\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--file\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--log\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"log\",\n\t\t\":8\",\n\t\t\"Completion ended with directive: ShellCompDirectiveFilterFileExt\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--yaml\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"yaml\", \"yml\",\n\t\t\":8\",\n\t\t\"Completion ended with directive: ShellCompDirectiveFilterFileExt\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--yaml=\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"yaml\", \"yml\",\n\t\t\":8\",\n\t\t\"Completion ended with directive: ShellCompDirectiveFilterFileExt\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"-y\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"yaml\", \"yml\",\n\t\t\":8\",\n\t\t\"Completion ended with directive: ShellCompDirectiveFilterFileExt\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"-y=\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"yaml\", \"yml\",\n\t\t\":8\",\n\t\t\"Completion ended with directive: ShellCompDirectiveFilterFileExt\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--text\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"txt\",\n\t\t\":8\",\n\t\t\"Completion ended with directive: ShellCompDirectiveFilterFileExt\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestFlagDirFilterCompletionInGo(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\n\t// Filter directories\n\trootCmd.Flags().StringP(\"dir\", \"d\", \"\", \"dir flag\")\n\tassertNoErr(t, rootCmd.MarkFlagDirname(\"dir\"))\n\n\t// Filter directories within a directory\n\trootCmd.Flags().StringP(\"subdir\", \"s\", \"\", \"subdir\")\n\tassertNoErr(t, rootCmd.Flags().SetAnnotation(\"subdir\", BashCompSubdirsInDir, []string{\"themes\"}))\n\n\t// Multiple directory specification get ignored\n\trootCmd.Flags().StringP(\"manydir\", \"m\", \"\", \"manydir\")\n\tassertNoErr(t, rootCmd.Flags().SetAnnotation(\"manydir\", BashCompSubdirsInDir, []string{\"themes\", \"colors\"}))\n\n\t// Test that the completion logic returns the proper info for the completion\n\t// script to handle the directory filtering\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--dir\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\":16\",\n\t\t\"Completion ended with directive: ShellCompDirectiveFilterDirs\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"-d\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\":16\",\n\t\t\"Completion ended with directive: ShellCompDirectiveFilterDirs\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--subdir\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"themes\",\n\t\t\":16\",\n\t\t\"Completion ended with directive: ShellCompDirectiveFilterDirs\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--subdir=\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"themes\",\n\t\t\":16\",\n\t\t\"Completion ended with directive: ShellCompDirectiveFilterDirs\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"-s\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"themes\",\n\t\t\":16\",\n\t\t\"Completion ended with directive: ShellCompDirectiveFilterDirs\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"-s=\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"themes\",\n\t\t\":16\",\n\t\t\"Completion ended with directive: ShellCompDirectiveFilterDirs\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--manydir\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\":16\",\n\t\t\"Completion ended with directive: ShellCompDirectiveFilterDirs\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestValidArgsFuncCmdContext(t *testing.T) {\n\tvalidArgsFunc := func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\tctx := cmd.Context()\n\n\t\tif ctx == nil {\n\t\t\tt.Error(\"Received nil context in completion func\")\n\t\t} else if ctx.Value(\"testKey\") != \"123\" {\n\t\t\tt.Error(\"Received invalid context\")\n\t\t}\n\n\t\treturn nil, ShellCompDirectiveDefault\n\t}\n\n\trootCmd := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\tchildCmd := &Command{\n\t\tUse:               \"childCmd\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun:               emptyRun,\n\t}\n\trootCmd.AddCommand(childCmd)\n\n\t//nolint:staticcheck // We can safely use a basic type as key in tests.\n\tctx := context.WithValue(context.Background(), \"testKey\", \"123\")\n\n\t// Test completing an empty string on the childCmd\n\t_, output, err := executeCommandWithContextC(ctx, rootCmd, ShellCompNoDescRequestCmd, \"childCmd\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestValidArgsFuncSingleCmd(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse:               \"root\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun:               emptyRun,\n\t}\n\n\t// Test completing an empty string\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"one\",\n\t\t\"two\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Check completing with a prefix\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"t\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"two\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestValidArgsFuncSingleCmdInvalidArg(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse: \"root\",\n\t\t// If we don't specify a value for Args, this test fails.\n\t\t// This is only true for a root command without any subcommands, and is caused\n\t\t// by the fact that the __complete command becomes a subcommand when there should not be one.\n\t\t// The problem is in the implementation of legacyArgs().\n\t\tArgs:              MinimumNArgs(1),\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun:               emptyRun,\n\t}\n\n\t// Check completing with wrong number of args\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"unexpectedArg\", \"t\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestValidArgsFuncChildCmds(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild1Cmd := &Command{\n\t\tUse:               \"child1\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun:               emptyRun,\n\t}\n\tchild2Cmd := &Command{\n\t\tUse:               \"child2\",\n\t\tValidArgsFunction: validArgsFunc2,\n\t\tRun:               emptyRun,\n\t}\n\trootCmd.AddCommand(child1Cmd, child2Cmd)\n\n\t// Test completion of first sub-command with empty argument\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"child1\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"one\",\n\t\t\"two\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test completion of first sub-command with a prefix to complete\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"child1\", \"t\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"two\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Check completing with wrong number of args\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"child1\", \"unexpectedArg\", \"t\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test completion of second sub-command with empty argument\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"child2\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"three\",\n\t\t\"four\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"child2\", \"t\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"three\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Check completing with wrong number of args\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"child2\", \"unexpectedArg\", \"t\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestValidArgsFuncAliases(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild := &Command{\n\t\tUse:               \"child\",\n\t\tAliases:           []string{\"son\", \"daughter\"},\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun:               emptyRun,\n\t}\n\trootCmd.AddCommand(child)\n\n\t// Test completion of first sub-command with empty argument\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"son\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"one\",\n\t\t\"two\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test completion of first sub-command with a prefix to complete\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"daughter\", \"t\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"two\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Check completing with wrong number of args\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"son\", \"unexpectedArg\", \"t\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestValidArgsFuncInBashScript(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild := &Command{\n\t\tUse:               \"child\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun:               emptyRun,\n\t}\n\trootCmd.AddCommand(child)\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenBashCompletion(buf))\n\toutput := buf.String()\n\n\tcheck(t, output, \"has_completion_function=1\")\n}\n\nfunc TestNoValidArgsFuncInBashScript(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild := &Command{\n\t\tUse: \"child\",\n\t\tRun: emptyRun,\n\t}\n\trootCmd.AddCommand(child)\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenBashCompletion(buf))\n\toutput := buf.String()\n\n\tcheckOmit(t, output, \"has_completion_function=1\")\n}\n\nfunc TestCompleteCmdInBashScript(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild := &Command{\n\t\tUse:               \"child\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun:               emptyRun,\n\t}\n\trootCmd.AddCommand(child)\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenBashCompletion(buf))\n\toutput := buf.String()\n\n\tcheck(t, output, ShellCompNoDescRequestCmd)\n}\n\nfunc TestCompleteNoDesCmdInZshScript(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild := &Command{\n\t\tUse:               \"child\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun:               emptyRun,\n\t}\n\trootCmd.AddCommand(child)\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenZshCompletionNoDesc(buf))\n\toutput := buf.String()\n\n\tcheck(t, output, ShellCompNoDescRequestCmd)\n}\n\nfunc TestCompleteCmdInZshScript(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild := &Command{\n\t\tUse:               \"child\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun:               emptyRun,\n\t}\n\trootCmd.AddCommand(child)\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenZshCompletion(buf))\n\toutput := buf.String()\n\n\tcheck(t, output, ShellCompRequestCmd)\n\tcheckOmit(t, output, ShellCompNoDescRequestCmd)\n}\n\nfunc TestFlagCompletionInGo(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\trootCmd.Flags().IntP(\"introot\", \"i\", -1, \"help message for flag introot\")\n\tassertNoErr(t, rootCmd.RegisterFlagCompletionFunc(\"introot\", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\tcompletions := []string{}\n\t\tfor _, comp := range []string{\"1\\tThe first\", \"2\\tThe second\", \"10\\tThe tenth\"} {\n\t\t\tif strings.HasPrefix(comp, toComplete) {\n\t\t\t\tcompletions = append(completions, comp)\n\t\t\t}\n\t\t}\n\t\treturn completions, ShellCompDirectiveDefault\n\t}))\n\trootCmd.Flags().String(\"filename\", \"\", \"Enter a filename\")\n\tassertNoErr(t, rootCmd.RegisterFlagCompletionFunc(\"filename\", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\tcompletions := []string{}\n\t\tfor _, comp := range []string{\"file.yaml\\tYAML format\", \"myfile.json\\tJSON format\", \"file.xml\\tXML format\"} {\n\t\t\tif strings.HasPrefix(comp, toComplete) {\n\t\t\t\tcompletions = append(completions, comp)\n\t\t\t}\n\t\t}\n\t\treturn completions, ShellCompDirectiveNoSpace | ShellCompDirectiveNoFileComp\n\t}))\n\n\t// Test completing an empty string\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--introot\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"1\",\n\t\t\"2\",\n\t\t\"10\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Check completing with a prefix\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--introot\", \"1\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"1\",\n\t\t\"10\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test completing an empty string\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--filename\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"file.yaml\",\n\t\t\"myfile.json\",\n\t\t\"file.xml\",\n\t\t\":6\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Check completing with a prefix\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"--filename\", \"f\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"file.yaml\",\n\t\t\"file.xml\",\n\t\t\":6\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestValidArgsFuncChildCmdsWithDesc(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild1Cmd := &Command{\n\t\tUse:               \"child1\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun:               emptyRun,\n\t}\n\tchild2Cmd := &Command{\n\t\tUse:               \"child2\",\n\t\tValidArgsFunction: validArgsFunc2,\n\t\tRun:               emptyRun,\n\t}\n\trootCmd.AddCommand(child1Cmd, child2Cmd)\n\n\t// Test completion of first sub-command with empty argument\n\toutput, err := executeCommand(rootCmd, ShellCompRequestCmd, \"child1\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"one\\tThe first\",\n\t\t\"two\\tThe second\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test completion of first sub-command with a prefix to complete\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"child1\", \"t\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"two\\tThe second\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Check completing with wrong number of args\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"child1\", \"unexpectedArg\", \"t\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test completion of second sub-command with empty argument\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"child2\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"three\\tThe third\",\n\t\t\"four\\tThe fourth\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"child2\", \"t\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"three\\tThe third\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Check completing with wrong number of args\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"child2\", \"unexpectedArg\", \"t\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestFlagCompletionWithNotInterspersedArgs(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchildCmd := &Command{\n\t\tUse: \"child\",\n\t\tRun: emptyRun,\n\t\tValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\t\treturn []string{\"--validarg\", \"test\"}, ShellCompDirectiveDefault\n\t\t},\n\t}\n\tchildCmd2 := &Command{\n\t\tUse:       \"child2\",\n\t\tRun:       emptyRun,\n\t\tValidArgs: []string{\"arg1\", \"arg2\"},\n\t}\n\trootCmd.AddCommand(childCmd, childCmd2)\n\tchildCmd.Flags().Bool(\"bool\", false, \"test bool flag\")\n\tchildCmd.Flags().String(\"string\", \"\", \"test string flag\")\n\t_ = childCmd.RegisterFlagCompletionFunc(\"string\", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\treturn []string{\"myval\"}, ShellCompDirectiveDefault\n\t})\n\n\t// Test flag completion with no argument\n\toutput, err := executeCommand(rootCmd, ShellCompRequestCmd, \"child\", \"--\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"--bool\\ttest bool flag\",\n\t\t\"--help\\thelp for child\",\n\t\t\"--string\\ttest string flag\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that no flags are completed after the -- arg\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"child\", \"--\", \"-\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--validarg\",\n\t\t\"test\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that no flags are completed after the -- arg with a flag set\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"child\", \"--bool\", \"--\", \"-\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--validarg\",\n\t\t\"test\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// set Interspersed to false which means that no flags should be completed after the first arg\n\tchildCmd.Flags().SetInterspersed(false)\n\n\t// Test that no flags are completed after the first arg\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"child\", \"arg\", \"--\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--validarg\",\n\t\t\"test\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that no flags are completed after the fist arg with a flag set\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"child\", \"--string\", \"t\", \"arg\", \"--\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--validarg\",\n\t\t\"test\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Check that args are still completed after --\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"child\", \"--\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--validarg\",\n\t\t\"test\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Check that args are still completed even if flagname with ValidArgsFunction exists\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"child\", \"--\", \"--string\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--validarg\",\n\t\t\"test\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Check that args are still completed even if flagname with ValidArgsFunction exists\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"child2\", \"--\", \"a\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"arg1\",\n\t\t\"arg2\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Check that --validarg is not parsed as flag after --\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"child\", \"--\", \"--validarg\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--validarg\",\n\t\t\"test\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Check that --validarg is not parsed as flag after an arg\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"child\", \"arg\", \"--validarg\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--validarg\",\n\t\t\"test\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Check that --validarg is added to args for the ValidArgsFunction\n\tchildCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\treturn args, ShellCompDirectiveDefault\n\t}\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"child\", \"--\", \"--validarg\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--validarg\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Check that --validarg is added to args for the ValidArgsFunction and toComplete is also set correctly\n\tchildCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\treturn append(args, toComplete), ShellCompDirectiveDefault\n\t}\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"child\", \"--\", \"--validarg\", \"--toComp=ab\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"--validarg\",\n\t\t\"--toComp=ab\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestFlagCompletionWorksRootCommandAddedAfterFlags(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tchildCmd := &Command{\n\t\tUse: \"child\",\n\t\tRun: emptyRun,\n\t\tValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\t\treturn []string{\"--validarg\", \"test\"}, ShellCompDirectiveDefault\n\t\t},\n\t}\n\tchildCmd.Flags().Bool(\"bool\", false, \"test bool flag\")\n\tchildCmd.Flags().String(\"string\", \"\", \"test string flag\")\n\t_ = childCmd.RegisterFlagCompletionFunc(\"string\", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\treturn []string{\"myval\"}, ShellCompDirectiveDefault\n\t})\n\n\t// Important: This is a test for https://github.com/spf13/cobra/issues/1437\n\t// Only add the subcommand after RegisterFlagCompletionFunc was called, do not change this order!\n\trootCmd.AddCommand(childCmd)\n\n\t// Test that flag completion works for the subcmd\n\toutput, err := executeCommand(rootCmd, ShellCompRequestCmd, \"child\", \"--string\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"myval\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestFlagCompletionForPersistentFlagsCalledFromSubCmd(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\trootCmd.PersistentFlags().String(\"string\", \"\", \"test string flag\")\n\t_ = rootCmd.RegisterFlagCompletionFunc(\"string\", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\treturn []string{\"myval\"}, ShellCompDirectiveDefault\n\t})\n\n\tchildCmd := &Command{\n\t\tUse: \"child\",\n\t\tRun: emptyRun,\n\t\tValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\t\treturn []string{\"--validarg\", \"test\"}, ShellCompDirectiveDefault\n\t\t},\n\t}\n\tchildCmd.Flags().Bool(\"bool\", false, \"test bool flag\")\n\trootCmd.AddCommand(childCmd)\n\n\t// Test that persistent flag completion works for the subcmd\n\toutput, err := executeCommand(rootCmd, ShellCompRequestCmd, \"child\", \"--string\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"myval\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\n// This test tries to register flag completion concurrently to make sure the\n// code handles concurrency properly.\n// This was reported as a problem when tests are run concurrently:\n// https://github.com/spf13/cobra/issues/1320\n//\n// NOTE: this test can sometimes pass even if the code were to not handle\n// concurrency properly. This is not great but the important part is that\n// it should never fail.  Therefore, if the tests fails sometimes, we will\n// still be able to know there is a problem.\nfunc TestFlagCompletionConcurrentRegistration(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\tconst maxFlags = 50\n\tfor i := 1; i < maxFlags; i += 2 {\n\t\tflagName := fmt.Sprintf(\"flag%d\", i)\n\t\trootCmd.Flags().String(flagName, \"\", fmt.Sprintf(\"test %s flag on root\", flagName))\n\t}\n\n\tchildCmd := &Command{\n\t\tUse: \"child\",\n\t\tRun: emptyRun,\n\t}\n\tfor i := 2; i <= maxFlags; i += 2 {\n\t\tflagName := fmt.Sprintf(\"flag%d\", i)\n\t\tchildCmd.Flags().String(flagName, \"\", fmt.Sprintf(\"test %s flag on child\", flagName))\n\t}\n\n\trootCmd.AddCommand(childCmd)\n\n\t// Register completion in different threads to test concurrency.\n\tvar wg sync.WaitGroup\n\tfor i := 1; i <= maxFlags; i++ {\n\t\tindex := i\n\t\tflagName := fmt.Sprintf(\"flag%d\", i)\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tcmd := rootCmd\n\t\t\tif index%2 == 0 {\n\t\t\t\tcmd = childCmd\n\t\t\t}\n\t\t\t_ = cmd.RegisterFlagCompletionFunc(flagName, func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\t\t\treturn []string{fmt.Sprintf(\"flag%d\", index)}, ShellCompDirectiveDefault\n\t\t\t})\n\t\t}()\n\t}\n\n\twg.Wait()\n\n\t// Test that flag completion works for each flag\n\tfor i := 1; i <= 6; i++ {\n\t\tvar output string\n\t\tvar err error\n\t\tflagName := fmt.Sprintf(\"flag%d\", i)\n\n\t\tif i%2 == 1 {\n\t\t\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"--\"+flagName, \"\")\n\t\t} else {\n\t\t\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"child\", \"--\"+flagName, \"\")\n\t\t}\n\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t}\n\n\t\texpected := strings.Join([]string{\n\t\t\tflagName,\n\t\t\t\":0\",\n\t\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\t\tif output != expected {\n\t\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t\t}\n\t}\n}\n\nfunc TestFlagCompletionInGoWithDesc(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\trootCmd.Flags().IntP(\"introot\", \"i\", -1, \"help message for flag introot\")\n\tassertNoErr(t, rootCmd.RegisterFlagCompletionFunc(\"introot\", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\tcompletions := []string{}\n\t\tfor _, comp := range []string{\"1\\tThe first\", \"2\\tThe second\", \"10\\tThe tenth\"} {\n\t\t\tif strings.HasPrefix(comp, toComplete) {\n\t\t\t\tcompletions = append(completions, comp)\n\t\t\t}\n\t\t}\n\t\treturn completions, ShellCompDirectiveDefault\n\t}))\n\trootCmd.Flags().String(\"filename\", \"\", \"Enter a filename\")\n\tassertNoErr(t, rootCmd.RegisterFlagCompletionFunc(\"filename\", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\tcompletions := []string{}\n\t\tfor _, comp := range []string{\"file.yaml\\tYAML format\", \"myfile.json\\tJSON format\", \"file.xml\\tXML format\"} {\n\t\t\tif strings.HasPrefix(comp, toComplete) {\n\t\t\t\tcompletions = append(completions, comp)\n\t\t\t}\n\t\t}\n\t\treturn completions, ShellCompDirectiveNoSpace | ShellCompDirectiveNoFileComp\n\t}))\n\n\t// Test completing an empty string\n\toutput, err := executeCommand(rootCmd, ShellCompRequestCmd, \"--introot\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"1\\tThe first\",\n\t\t\"2\\tThe second\",\n\t\t\"10\\tThe tenth\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Check completing with a prefix\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"--introot\", \"1\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"1\\tThe first\",\n\t\t\"10\\tThe tenth\",\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test completing an empty string\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"--filename\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"file.yaml\\tYAML format\",\n\t\t\"myfile.json\\tJSON format\",\n\t\t\"file.xml\\tXML format\",\n\t\t\":6\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Check completing with a prefix\n\toutput, err = executeCommand(rootCmd, ShellCompRequestCmd, \"--filename\", \"f\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"file.yaml\\tYAML format\",\n\t\t\"file.xml\\tXML format\",\n\t\t\":6\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestValidArgsNotValidArgsFunc(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse:       \"root\",\n\t\tValidArgs: []string{\"one\", \"two\"},\n\t\tValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\t\treturn []string{\"three\", \"four\"}, ShellCompDirectiveNoFileComp\n\t\t},\n\t\tRun: emptyRun,\n\t}\n\n\t// Test that if both ValidArgs and ValidArgsFunction are present\n\t// only ValidArgs is considered\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"one\",\n\t\t\"two\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Check completing with a prefix\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"t\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"two\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestArgAliasesCompletionInGo(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse:        \"root\",\n\t\tArgs:       OnlyValidArgs,\n\t\tValidArgs:  []string{\"one\", \"two\", \"three\"},\n\t\tArgAliases: []string{\"un\", \"deux\", \"trois\"},\n\t\tRun:        emptyRun,\n\t}\n\n\t// Test that argaliases are not completed when there are validargs that match\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"one\",\n\t\t\"two\",\n\t\t\"three\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that argaliases are not completed when there are validargs that match using a prefix\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"t\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"two\",\n\t\t\"three\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that argaliases are completed when there are no validargs that match\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"tr\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"trois\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestCompleteHelp(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild1Cmd := &Command{\n\t\tUse: \"child1\",\n\t\tRun: emptyRun,\n\t}\n\tchild2Cmd := &Command{\n\t\tUse: \"child2\",\n\t\tRun: emptyRun,\n\t}\n\trootCmd.AddCommand(child1Cmd, child2Cmd)\n\n\tchild3Cmd := &Command{\n\t\tUse: \"child3\",\n\t\tRun: emptyRun,\n\t}\n\tchild1Cmd.AddCommand(child3Cmd)\n\n\t// Test that completion includes the help command\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"child1\",\n\t\t\"child2\",\n\t\t\"completion\",\n\t\t\"help\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test sub-commands are completed on first level of help command\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"help\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"child1\",\n\t\t\"child2\",\n\t\t\"completion\",\n\t\t\"help\", // \"<program> help help\" is a valid command, so should be completed\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test sub-commands are completed on first level of help command\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"help\", \"child1\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"child3\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc removeCompCmd(rootCmd *Command) {\n\t// Remove completion command for the next test\n\tfor _, cmd := range rootCmd.commands {\n\t\tif cmd.Name() == compCmdName {\n\t\t\trootCmd.RemoveCommand(cmd)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc TestDefaultCompletionCmd(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse:  \"root\",\n\t\tArgs: NoArgs,\n\t\tRun:  emptyRun,\n\t}\n\n\t// Test that when there are no sub-commands, the completion command is not created if it is not called directly.\n\tassertNoErr(t, rootCmd.Execute())\n\tfor _, cmd := range rootCmd.commands {\n\t\tif cmd.Name() == compCmdName {\n\t\t\tt.Errorf(\"Should not have a 'completion' command when there are no other sub-commands of root\")\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Test that when there are no sub-commands, the completion command is created when it is called directly.\n\t_, err := executeCommand(rootCmd, compCmdName)\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\t// Reset the arguments\n\trootCmd.args = nil\n\t// Remove completion command for the next test\n\tremoveCompCmd(rootCmd)\n\n\t// Add a sub-command\n\tsubCmd := &Command{\n\t\tUse: \"sub\",\n\t\tRun: emptyRun,\n\t}\n\trootCmd.AddCommand(subCmd)\n\n\t// Test that a completion command is created if there are other sub-commands\n\tfound := false\n\tassertNoErr(t, rootCmd.Execute())\n\tfor _, cmd := range rootCmd.commands {\n\t\tif cmd.Name() == compCmdName {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\tt.Errorf(\"Should have a 'completion' command when there are other sub-commands of root\")\n\t}\n\t// Remove completion command for the next test\n\tremoveCompCmd(rootCmd)\n\n\t// Test that the default completion command can be disabled\n\trootCmd.CompletionOptions.DisableDefaultCmd = true\n\tassertNoErr(t, rootCmd.Execute())\n\tfor _, cmd := range rootCmd.commands {\n\t\tif cmd.Name() == compCmdName {\n\t\t\tt.Errorf(\"Should not have a 'completion' command when the feature is disabled\")\n\t\t\tbreak\n\t\t}\n\t}\n\t// Re-enable for next test\n\trootCmd.CompletionOptions.DisableDefaultCmd = false\n\n\t// Test that completion descriptions are enabled by default\n\toutput, err := executeCommand(rootCmd, compCmdName, \"zsh\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheck(t, output, ShellCompRequestCmd)\n\tcheckOmit(t, output, ShellCompNoDescRequestCmd)\n\t// Remove completion command for the next test\n\tremoveCompCmd(rootCmd)\n\n\t// Test that completion descriptions can be disabled completely\n\trootCmd.CompletionOptions.DisableDescriptions = true\n\toutput, err = executeCommand(rootCmd, compCmdName, \"zsh\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\tcheck(t, output, ShellCompNoDescRequestCmd)\n\t// Re-enable for next test\n\trootCmd.CompletionOptions.DisableDescriptions = false\n\t// Remove completion command for the next test\n\tremoveCompCmd(rootCmd)\n\n\tvar compCmd *Command\n\t// Test that the --no-descriptions flag is present on all shells\n\tassertNoErr(t, rootCmd.Execute())\n\tfor _, shell := range []string{\"bash\", \"fish\", \"powershell\", \"zsh\"} {\n\t\tif compCmd, _, err = rootCmd.Find([]string{compCmdName, shell}); err != nil {\n\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t}\n\t\tif flag := compCmd.Flags().Lookup(compCmdNoDescFlagName); flag == nil {\n\t\t\tt.Errorf(\"Missing --%s flag for %s shell\", compCmdNoDescFlagName, shell)\n\t\t}\n\t}\n\t// Remove completion command for the next test\n\tremoveCompCmd(rootCmd)\n\n\t// Test that the '--no-descriptions' flag can be disabled\n\trootCmd.CompletionOptions.DisableNoDescFlag = true\n\tassertNoErr(t, rootCmd.Execute())\n\tfor _, shell := range []string{\"fish\", \"zsh\", \"bash\", \"powershell\"} {\n\t\tif compCmd, _, err = rootCmd.Find([]string{compCmdName, shell}); err != nil {\n\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t}\n\t\tif flag := compCmd.Flags().Lookup(compCmdNoDescFlagName); flag != nil {\n\t\t\tt.Errorf(\"Unexpected --%s flag for %s shell\", compCmdNoDescFlagName, shell)\n\t\t}\n\t}\n\t// Re-enable for next test\n\trootCmd.CompletionOptions.DisableNoDescFlag = false\n\t// Remove completion command for the next test\n\tremoveCompCmd(rootCmd)\n\n\t// Test that the '--no-descriptions' flag is disabled when descriptions are disabled\n\trootCmd.CompletionOptions.DisableDescriptions = true\n\tassertNoErr(t, rootCmd.Execute())\n\tfor _, shell := range []string{\"fish\", \"zsh\", \"bash\", \"powershell\"} {\n\t\tif compCmd, _, err = rootCmd.Find([]string{compCmdName, shell}); err != nil {\n\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t}\n\t\tif flag := compCmd.Flags().Lookup(compCmdNoDescFlagName); flag != nil {\n\t\t\tt.Errorf(\"Unexpected --%s flag for %s shell\", compCmdNoDescFlagName, shell)\n\t\t}\n\t}\n\t// Re-enable for next test\n\trootCmd.CompletionOptions.DisableDescriptions = false\n\t// Remove completion command for the next test\n\tremoveCompCmd(rootCmd)\n\n\t// Test that the 'completion' command can be hidden\n\trootCmd.CompletionOptions.HiddenDefaultCmd = true\n\tassertNoErr(t, rootCmd.Execute())\n\tcompCmd, _, err = rootCmd.Find([]string{compCmdName})\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\tif compCmd.Hidden == false {\n\t\tt.Error(\"Default 'completion' command should be hidden but it is not\")\n\t}\n\t// Re-enable for next test\n\trootCmd.CompletionOptions.HiddenDefaultCmd = false\n\t// Remove completion command for the next test\n\tremoveCompCmd(rootCmd)\n}\n\nfunc TestCompleteCompletion(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\n\t// Test that when there are no sub-commands, the 'completion' command is not completed\n\t// (because it is not created).\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"completion\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\":0\",\n\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that when there are no sub-commands, completion can be triggered for the default\n\t// 'completion' command\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"completion\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"bash\",\n\t\t\"fish\",\n\t\t\"powershell\",\n\t\t\"zsh\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Add a sub-command\n\tsubCmd := &Command{\n\t\tUse: \"sub\",\n\t\tRun: emptyRun,\n\t}\n\trootCmd.AddCommand(subCmd)\n\n\t// Test sub-commands of the completion command\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"completion\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"bash\",\n\t\t\"fish\",\n\t\t\"powershell\",\n\t\t\"zsh\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test there are no completions for the sub-commands of the completion command\n\tvar compCmd *Command\n\tfor _, cmd := range rootCmd.Commands() {\n\t\tif cmd.Name() == compCmdName {\n\t\t\tcompCmd = cmd\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor _, shell := range compCmd.Commands() {\n\t\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, compCmdName, shell.Name(), \"\")\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t}\n\n\t\texpected = strings.Join([]string{\n\t\t\t\":4\",\n\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\t\tif output != expected {\n\t\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t\t}\n\t}\n}\n\nfunc TestMultipleShorthandFlagCompletion(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse:       \"root\",\n\t\tValidArgs: []string{\"foo\", \"bar\"},\n\t\tRun:       emptyRun,\n\t}\n\tf := rootCmd.Flags()\n\tf.BoolP(\"short\", \"s\", false, \"short flag 1\")\n\tf.BoolP(\"short2\", \"d\", false, \"short flag 2\")\n\tf.StringP(\"short3\", \"f\", \"\", \"short flag 3\")\n\t_ = rootCmd.RegisterFlagCompletionFunc(\"short3\", func(*Command, []string, string) ([]string, ShellCompDirective) {\n\t\treturn []string{\"works\"}, ShellCompDirectiveNoFileComp\n\t})\n\n\t// Test that a single shorthand flag works\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"-s\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"foo\",\n\t\t\"bar\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that multiple boolean shorthand flags work\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"-sd\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"foo\",\n\t\t\"bar\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that multiple boolean + string shorthand flags work\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"-sdf\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"works\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that multiple boolean + string with equal sign shorthand flags work\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"-sdf=\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"works\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that multiple boolean + string with equal sign with value shorthand flags work\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"-sdf=abc\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"foo\",\n\t\t\"bar\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestCompleteWithDisableFlagParsing(t *testing.T) {\n\n\tflagValidArgs := func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\treturn []string{\"--flag\", \"-f\"}, ShellCompDirectiveNoFileComp\n\t}\n\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchildCmd := &Command{\n\t\tUse:                \"child\",\n\t\tRun:                emptyRun,\n\t\tDisableFlagParsing: true,\n\t\tValidArgsFunction:  flagValidArgs,\n\t}\n\trootCmd.AddCommand(childCmd)\n\n\trootCmd.PersistentFlags().StringP(\"persistent\", \"p\", \"\", \"persistent flag\")\n\tchildCmd.Flags().StringP(\"nonPersistent\", \"n\", \"\", \"non-persistent flag\")\n\n\t// Test that when DisableFlagParsing==true, ValidArgsFunction is called to complete flag names,\n\t// after Cobra tried to complete the flags it knows about.\n\tchildCmd.DisableFlagParsing = true\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"child\", \"-\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"--persistent\",\n\t\t\"-p\",\n\t\t\"--nonPersistent\",\n\t\t\"-n\",\n\t\t\"--flag\",\n\t\t\"-f\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Test that when DisableFlagParsing==false, Cobra completes the flags itself and ValidArgsFunction is not called\n\tchildCmd.DisableFlagParsing = false\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"child\", \"-\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\t// Cobra was not told of any flags, so it returns nothing\n\texpected = strings.Join([]string{\n\t\t\"--persistent\",\n\t\t\"-p\",\n\t\t\"--help\",\n\t\t\"-h\",\n\t\t\"--nonPersistent\",\n\t\t\"-n\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestCompleteWithRootAndLegacyArgs(t *testing.T) {\n\t// Test a lonely root command which uses legacyArgs().  In such a case, the root\n\t// command should accept any number of arguments and completion should behave accordingly.\n\trootCmd := &Command{\n\t\tUse:  \"root\",\n\t\tArgs: nil, // Args must be nil to trigger the legacyArgs() function\n\t\tRun:  emptyRun,\n\t\tValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\t\treturn []string{\"arg1\", \"arg2\"}, ShellCompDirectiveNoFileComp\n\t\t},\n\t}\n\n\t// Make sure the first arg is completed\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"arg1\",\n\t\t\"arg2\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n\n\t// Make sure the completion of arguments continues\n\toutput, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"arg1\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected = strings.Join([]string{\n\t\t\"arg1\",\n\t\t\"arg2\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\",\n\t}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestCompletionFuncCompatibility(t *testing.T) {\n\tt.Run(\"validate signature\", func(t *testing.T) {\n\t\tt.Run(\"format with []string\", func(t *testing.T) {\n\t\t\tvar userComp func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)\n\n\t\t\t// check against new signature\n\t\t\tvar _ CompletionFunc = userComp //nolint:staticcheck // LHS type is needed for this use case\n\n\t\t\t// check Command accepts\n\t\t\tcmd := Command{\n\t\t\t\tValidArgsFunction: userComp,\n\t\t\t}\n\n\t\t\t_ = cmd.RegisterFlagCompletionFunc(\"foo\", userComp)\n\t\t})\n\n\t\tt.Run(\"format with []Completion\", func(t *testing.T) {\n\t\t\tvar userComp func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective)\n\n\t\t\t// check against new signature\n\t\t\tvar _ CompletionFunc = userComp //nolint:staticcheck // LHS type is needed for this use case\n\t\t\t// check Command accepts\n\t\t\tcmd := Command{\n\t\t\t\tValidArgsFunction: userComp,\n\t\t\t}\n\n\t\t\t_ = cmd.RegisterFlagCompletionFunc(\"foo\", userComp)\n\t\t})\n\n\t\tt.Run(\"format with CompletionFunc\", func(t *testing.T) {\n\t\t\tvar userComp CompletionFunc\n\n\t\t\t// check helper against old signature\n\t\t\tvar _ func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) = userComp     //nolint:staticcheck // LHS type is needed for this use case\n\t\t\tvar _ func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) = userComp //nolint:staticcheck // LHS type is needed for this use case\n\n\t\t\t// check Command accepts\n\t\t\tcmd := Command{\n\t\t\t\tValidArgsFunction: userComp,\n\t\t\t}\n\n\t\t\t_ = cmd.RegisterFlagCompletionFunc(\"foo\", userComp)\n\t\t})\n\t})\n\n\tt.Run(\"user defined completion helper\", func(t *testing.T) {\n\t\tt.Run(\"type helper\", func(t *testing.T) {\n\t\t\t// This is a type that may have been defined by the user of the library\n\t\t\t// This replicates the issue https://github.com/docker/cli/issues/5827\n\t\t\t// https://github.com/docker/cli/blob/b6e7eba4470ecdca460e4b63270fba8179674ad6/cli/command/completion/functions.go#L18\n\t\t\ttype UserCompletionTypeHelper func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)\n\n\t\t\tvar userComp UserCompletionTypeHelper\n\n\t\t\t// Here we are validating the existing type validates the CompletionFunc type\n\t\t\tvar _ CompletionFunc = userComp\n\n\t\t\tcmd := Command{\n\t\t\t\tValidArgsFunction: userComp,\n\t\t\t}\n\n\t\t\t_ = cmd.RegisterFlagCompletionFunc(\"foo\", userComp)\n\t\t})\n\n\t\tt.Run(\"type alias helper\", func(t *testing.T) {\n\t\t\t// This is a type that may have been defined by the user of the library\n\t\t\t// This replicates the possible fix that was tried here https://github.com/docker/cli/pull/5828\n\t\t\t// https://github.com/docker/cli/blob/ae3d4db9f658259dace9dee515718be7c1b1f517/cli/command/completion/functions.go#L18\n\t\t\ttype UserCompletionTypeAliasHelper = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)\n\n\t\t\tvar userComp UserCompletionTypeAliasHelper\n\n\t\t\t// Here we are validating the existing type validates the CompletionFunc type\n\t\t\tvar _ CompletionFunc = userComp //nolint:staticcheck // LHS type is needed for this use case\n\n\t\t\tcmd := Command{\n\t\t\t\tValidArgsFunction: userComp,\n\t\t\t}\n\n\t\t\t_ = cmd.RegisterFlagCompletionFunc(\"foo\", userComp)\n\t\t})\n\t})\n}\n\nfunc TestFixedCompletions(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchoices := []string{\"apple\", \"banana\", \"orange\"}\n\tchildCmd := &Command{\n\t\tUse:               \"child\",\n\t\tValidArgsFunction: FixedCompletions(choices, ShellCompDirectiveNoFileComp),\n\t\tRun:               emptyRun,\n\t}\n\trootCmd.AddCommand(childCmd)\n\n\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"child\", \"a\")\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\texpected := strings.Join([]string{\n\t\t\"apple\",\n\t\t\"banana\",\n\t\t\"orange\",\n\t\t\":4\",\n\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\")\n\n\tif output != expected {\n\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t}\n}\n\nfunc TestFixedCompletionsWithCompletionHelpers(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\t// here we are mixing string, [Completion] and [CompletionWithDesc]\n\tchoices := []string{\"apple\", Completion(\"banana\"), CompletionWithDesc(\"orange\", \"orange are orange\")}\n\tchildCmd := &Command{\n\t\tUse:               \"child\",\n\t\tValidArgsFunction: FixedCompletions(choices, ShellCompDirectiveNoFileComp),\n\t\tRun:               emptyRun,\n\t}\n\trootCmd.AddCommand(childCmd)\n\n\tt.Run(\"completion with description\", func(t *testing.T) {\n\t\toutput, err := executeCommand(rootCmd, ShellCompRequestCmd, \"child\", \"a\")\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t}\n\n\t\texpected := strings.Join([]string{\n\t\t\t\"apple\",\n\t\t\t\"banana\",\n\t\t\t\"orange\\torange are orange\", // this one has the description as expected with [ShellCompRequestCmd] flag\n\t\t\t\":4\",\n\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\",\n\t\t}, \"\\n\")\n\n\t\tif output != expected {\n\t\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t\t}\n\t})\n\n\tt.Run(\"completion with no description\", func(t *testing.T) {\n\t\toutput, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, \"child\", \"a\")\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t}\n\n\t\texpected := strings.Join([]string{\n\t\t\t\"apple\",\n\t\t\t\"banana\",\n\t\t\t\"orange\", // the description is absent as expected with [ShellCompNoDescRequestCmd] flag\n\t\t\t\":4\",\n\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\",\n\t\t}, \"\\n\")\n\n\t\tif output != expected {\n\t\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t\t}\n\t})\n}\n\nfunc TestCompletionForGroupedFlags(t *testing.T) {\n\tgetCmd := func() *Command {\n\t\trootCmd := &Command{\n\t\t\tUse: \"root\",\n\t\t\tRun: emptyRun,\n\t\t}\n\t\tchildCmd := &Command{\n\t\t\tUse: \"child\",\n\t\t\tValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\t\t\treturn []string{\"subArg\"}, ShellCompDirectiveNoFileComp\n\t\t\t},\n\t\t\tRun: emptyRun,\n\t\t}\n\t\trootCmd.AddCommand(childCmd)\n\n\t\trootCmd.PersistentFlags().Int(\"ingroup1\", -1, \"ingroup1\")\n\t\trootCmd.PersistentFlags().String(\"ingroup2\", \"\", \"ingroup2\")\n\n\t\tchildCmd.Flags().Bool(\"ingroup3\", false, \"ingroup3\")\n\t\tchildCmd.Flags().Bool(\"nogroup\", false, \"nogroup\")\n\n\t\t// Add flags to a group\n\t\tchildCmd.MarkFlagsRequiredTogether(\"ingroup1\", \"ingroup2\", \"ingroup3\")\n\n\t\treturn rootCmd\n\t}\n\n\t// Each test case uses a unique command from the function above.\n\ttestcases := []struct {\n\t\tdesc           string\n\t\targs           []string\n\t\texpectedOutput string\n\t}{\n\t\t{\n\t\t\tdesc: \"flags in group not suggested without - prefix\",\n\t\t\targs: []string{\"child\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"subArg\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"flags in group suggested with - prefix\",\n\t\t\targs: []string{\"child\", \"-\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"--ingroup1\",\n\t\t\t\t\"--ingroup2\",\n\t\t\t\t\"--help\",\n\t\t\t\t\"-h\",\n\t\t\t\t\"--ingroup3\",\n\t\t\t\t\"--nogroup\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"when flag in group present, other flags in group suggested even without - prefix\",\n\t\t\targs: []string{\"child\", \"--ingroup2\", \"value\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"--ingroup1\",\n\t\t\t\t\"--ingroup3\",\n\t\t\t\t\"subArg\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"when all flags in group present, flags not suggested without - prefix\",\n\t\t\targs: []string{\"child\", \"--ingroup1\", \"8\", \"--ingroup2\", \"value2\", \"--ingroup3\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"subArg\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"group ignored if some flags not applicable\",\n\t\t\targs: []string{\"--ingroup2\", \"value\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"child\",\n\t\t\t\t\"completion\",\n\t\t\t\t\"help\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t}\n\n\tfor _, tc := range testcases {\n\t\tt.Run(tc.desc, func(t *testing.T) {\n\t\t\tc := getCmd()\n\t\t\targs := []string{ShellCompNoDescRequestCmd}\n\t\t\targs = append(args, tc.args...)\n\t\t\toutput, err := executeCommand(c, args...)\n\t\t\tswitch {\n\t\t\tcase err == nil && output != tc.expectedOutput:\n\t\t\t\tt.Errorf(\"expected: %q, got: %q\", tc.expectedOutput, output)\n\t\t\tcase err != nil:\n\t\t\t\tt.Errorf(\"Unexpected error %q\", err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCompletionForOneRequiredGroupFlags(t *testing.T) {\n\tgetCmd := func() *Command {\n\t\trootCmd := &Command{\n\t\t\tUse: \"root\",\n\t\t\tRun: emptyRun,\n\t\t}\n\t\tchildCmd := &Command{\n\t\t\tUse: \"child\",\n\t\t\tValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\t\t\treturn []string{\"subArg\"}, ShellCompDirectiveNoFileComp\n\t\t\t},\n\t\t\tRun: emptyRun,\n\t\t}\n\t\trootCmd.AddCommand(childCmd)\n\n\t\trootCmd.PersistentFlags().Int(\"ingroup1\", -1, \"ingroup1\")\n\t\trootCmd.PersistentFlags().String(\"ingroup2\", \"\", \"ingroup2\")\n\n\t\tchildCmd.Flags().Bool(\"ingroup3\", false, \"ingroup3\")\n\t\tchildCmd.Flags().Bool(\"nogroup\", false, \"nogroup\")\n\n\t\t// Add flags to a group\n\t\tchildCmd.MarkFlagsOneRequired(\"ingroup1\", \"ingroup2\", \"ingroup3\")\n\n\t\treturn rootCmd\n\t}\n\n\t// Each test case uses a unique command from the function above.\n\ttestcases := []struct {\n\t\tdesc           string\n\t\targs           []string\n\t\texpectedOutput string\n\t}{\n\t\t{\n\t\t\tdesc: \"flags in group suggested without - prefix\",\n\t\t\targs: []string{\"child\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"--ingroup1\",\n\t\t\t\t\"--ingroup2\",\n\t\t\t\t\"--ingroup3\",\n\t\t\t\t\"subArg\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"flags in group suggested with - prefix\",\n\t\t\targs: []string{\"child\", \"-\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"--ingroup1\",\n\t\t\t\t\"--ingroup2\",\n\t\t\t\t\"--ingroup3\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"when any flag in group present, other flags in group not suggested without - prefix\",\n\t\t\targs: []string{\"child\", \"--ingroup2\", \"value\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"subArg\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"when all flags in group present, flags not suggested without - prefix\",\n\t\t\targs: []string{\"child\", \"--ingroup1\", \"8\", \"--ingroup2\", \"value2\", \"--ingroup3\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"subArg\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"group ignored if some flags not applicable\",\n\t\t\targs: []string{\"--ingroup2\", \"value\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"child\",\n\t\t\t\t\"completion\",\n\t\t\t\t\"help\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t}\n\n\tfor _, tc := range testcases {\n\t\tt.Run(tc.desc, func(t *testing.T) {\n\t\t\tc := getCmd()\n\t\t\targs := []string{ShellCompNoDescRequestCmd}\n\t\t\targs = append(args, tc.args...)\n\t\t\toutput, err := executeCommand(c, args...)\n\t\t\tswitch {\n\t\t\tcase err == nil && output != tc.expectedOutput:\n\t\t\t\tt.Errorf(\"expected: %q, got: %q\", tc.expectedOutput, output)\n\t\t\tcase err != nil:\n\t\t\t\tt.Errorf(\"Unexpected error %q\", err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCompletionForMutuallyExclusiveFlags(t *testing.T) {\n\tgetCmd := func() *Command {\n\t\trootCmd := &Command{\n\t\t\tUse: \"root\",\n\t\t\tRun: emptyRun,\n\t\t}\n\t\tchildCmd := &Command{\n\t\t\tUse: \"child\",\n\t\t\tValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\t\t\treturn []string{\"subArg\"}, ShellCompDirectiveNoFileComp\n\t\t\t},\n\t\t\tRun: emptyRun,\n\t\t}\n\t\trootCmd.AddCommand(childCmd)\n\n\t\trootCmd.PersistentFlags().IntSlice(\"ingroup1\", []int{1}, \"ingroup1\")\n\t\trootCmd.PersistentFlags().String(\"ingroup2\", \"\", \"ingroup2\")\n\n\t\tchildCmd.Flags().Bool(\"ingroup3\", false, \"ingroup3\")\n\t\tchildCmd.Flags().Bool(\"nogroup\", false, \"nogroup\")\n\n\t\t// Add flags to a group\n\t\tchildCmd.MarkFlagsMutuallyExclusive(\"ingroup1\", \"ingroup2\", \"ingroup3\")\n\n\t\treturn rootCmd\n\t}\n\n\t// Each test case uses a unique command from the function above.\n\ttestcases := []struct {\n\t\tdesc           string\n\t\targs           []string\n\t\texpectedOutput string\n\t}{\n\t\t{\n\t\t\tdesc: \"flags in mutually exclusive group not suggested without the - prefix\",\n\t\t\targs: []string{\"child\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"subArg\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"flags in mutually exclusive group suggested with the - prefix\",\n\t\t\targs: []string{\"child\", \"-\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"--ingroup1\",\n\t\t\t\t\"--ingroup2\",\n\t\t\t\t\"--help\",\n\t\t\t\t\"-h\",\n\t\t\t\t\"--ingroup3\",\n\t\t\t\t\"--nogroup\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"when flag in mutually exclusive group present, other flags in group not suggested even with the - prefix\",\n\t\t\targs: []string{\"child\", \"--ingroup1\", \"8\", \"-\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"--ingroup1\", // Should be suggested again since it is a slice\n\t\t\t\t\"--help\",\n\t\t\t\t\"-h\",\n\t\t\t\t\"--nogroup\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"group ignored if some flags not applicable\",\n\t\t\targs: []string{\"--ingroup1\", \"8\", \"-\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"--help\",\n\t\t\t\t\"-h\",\n\t\t\t\t\"--ingroup1\",\n\t\t\t\t\"--ingroup2\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t}\n\n\tfor _, tc := range testcases {\n\t\tt.Run(tc.desc, func(t *testing.T) {\n\t\t\tc := getCmd()\n\t\t\targs := []string{ShellCompNoDescRequestCmd}\n\t\t\targs = append(args, tc.args...)\n\t\t\toutput, err := executeCommand(c, args...)\n\t\t\tswitch {\n\t\t\tcase err == nil && output != tc.expectedOutput:\n\t\t\t\tt.Errorf(\"expected: %q, got: %q\", tc.expectedOutput, output)\n\t\t\tcase err != nil:\n\t\t\t\tt.Errorf(\"Unexpected error %q\", err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCompletionCobraFlags(t *testing.T) {\n\tgetCmd := func() *Command {\n\t\trootCmd := &Command{\n\t\t\tUse:     \"root\",\n\t\t\tVersion: \"1.1.1\",\n\t\t\tRun:     emptyRun,\n\t\t}\n\t\tchildCmd := &Command{\n\t\t\tUse:     \"child\",\n\t\t\tVersion: \"1.1.1\",\n\t\t\tRun:     emptyRun,\n\t\t\tValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\t\t\treturn []string{\"extra\"}, ShellCompDirectiveNoFileComp\n\t\t\t},\n\t\t}\n\t\tchildCmd2 := &Command{\n\t\t\tUse:     \"child2\",\n\t\t\tVersion: \"1.1.1\",\n\t\t\tRun:     emptyRun,\n\t\t\tValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\t\t\treturn []string{\"extra2\"}, ShellCompDirectiveNoFileComp\n\t\t\t},\n\t\t}\n\t\tchildCmd3 := &Command{\n\t\t\tUse:     \"child3\",\n\t\t\tVersion: \"1.1.1\",\n\t\t\tRun:     emptyRun,\n\t\t\tValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\t\t\treturn []string{\"extra3\"}, ShellCompDirectiveNoFileComp\n\t\t\t},\n\t\t}\n\t\tchildCmd4 := &Command{\n\t\t\tUse:     \"child4\",\n\t\t\tVersion: \"1.1.1\",\n\t\t\tRun:     emptyRun,\n\t\t\tValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\t\t\treturn []string{\"extra4\"}, ShellCompDirectiveNoFileComp\n\t\t\t},\n\t\t\tDisableFlagParsing: true,\n\t\t}\n\t\tchildCmd5 := &Command{\n\t\t\tUse:     \"child5\",\n\t\t\tVersion: \"1.1.1\",\n\t\t\tRun:     emptyRun,\n\t\t\tValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\t\t\treturn []string{\"extra5\"}, ShellCompDirectiveNoFileComp\n\t\t\t},\n\t\t\tDisableFlagParsing: true,\n\t\t}\n\n\t\trootCmd.AddCommand(childCmd, childCmd2, childCmd3, childCmd4, childCmd5)\n\n\t\t_ = childCmd.Flags().Bool(\"bool\", false, \"A bool flag\")\n\t\t_ = childCmd.MarkFlagRequired(\"bool\")\n\n\t\t// Have a command that adds its own help and version flag\n\t\t_ = childCmd2.Flags().BoolP(\"help\", \"h\", false, \"My own help\")\n\t\t_ = childCmd2.Flags().BoolP(\"version\", \"v\", false, \"My own version\")\n\n\t\t// Have a command that only adds its own -v flag\n\t\t_ = childCmd3.Flags().BoolP(\"verbose\", \"v\", false, \"Not a version flag\")\n\n\t\t// Have a command that DisablesFlagParsing but that also adds its own help and version flags\n\t\t_ = childCmd5.Flags().BoolP(\"help\", \"h\", false, \"My own help\")\n\t\t_ = childCmd5.Flags().BoolP(\"version\", \"v\", false, \"My own version\")\n\n\t\treturn rootCmd\n\t}\n\n\t// Each test case uses a unique command from the function above.\n\ttestcases := []struct {\n\t\tdesc           string\n\t\targs           []string\n\t\texpectedOutput string\n\t}{\n\t\t{\n\t\t\tdesc: \"completion of help and version flags\",\n\t\t\targs: []string{\"-\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"--help\",\n\t\t\t\t\"-h\",\n\t\t\t\t\"--version\",\n\t\t\t\t\"-v\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"no completion after --help flag\",\n\t\t\targs: []string{\"--help\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"no completion after -h flag\",\n\t\t\targs: []string{\"-h\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"no completion after --version flag\",\n\t\t\targs: []string{\"--version\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"no completion after -v flag\",\n\t\t\targs: []string{\"-v\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"no completion after --help flag even with other completions\",\n\t\t\targs: []string{\"child\", \"--help\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"no completion after -h flag even with other completions\",\n\t\t\targs: []string{\"child\", \"-h\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"no completion after --version flag even with other completions\",\n\t\t\targs: []string{\"child\", \"--version\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"no completion after -v flag even with other completions\",\n\t\t\targs: []string{\"child\", \"-v\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"no completion after -v flag even with other flag completions\",\n\t\t\targs: []string{\"child\", \"-v\", \"-\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"completion after --help flag when created by program\",\n\t\t\targs: []string{\"child2\", \"--help\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"extra2\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"completion after -h flag when created by program\",\n\t\t\targs: []string{\"child2\", \"-h\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"extra2\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"completion after --version flag when created by program\",\n\t\t\targs: []string{\"child2\", \"--version\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"extra2\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"completion after -v flag when created by program\",\n\t\t\targs: []string{\"child2\", \"-v\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"extra2\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"completion after --version when only -v flag was created by program\",\n\t\t\targs: []string{\"child3\", \"--version\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"completion after -v flag when only -v flag was created by program\",\n\t\t\targs: []string{\"child3\", \"-v\", \"\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"extra3\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"no completion for --help/-h and --version/-v flags when DisableFlagParsing=true\",\n\t\t\targs: []string{\"child4\", \"-\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"extra4\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"completions for program-defined --help/-h and --version/-v flags even when DisableFlagParsing=true\",\n\t\t\targs: []string{\"child5\", \"-\"},\n\t\t\texpectedOutput: strings.Join([]string{\n\t\t\t\t\"--help\",\n\t\t\t\t\"-h\",\n\t\t\t\t\"--version\",\n\t\t\t\t\"-v\",\n\t\t\t\t\"extra5\",\n\t\t\t\t\":4\",\n\t\t\t\t\"Completion ended with directive: ShellCompDirectiveNoFileComp\", \"\"}, \"\\n\"),\n\t\t},\n\t}\n\n\tfor _, tc := range testcases {\n\t\tt.Run(tc.desc, func(t *testing.T) {\n\t\t\tc := getCmd()\n\t\t\targs := []string{ShellCompNoDescRequestCmd}\n\t\t\targs = append(args, tc.args...)\n\t\t\toutput, err := executeCommand(c, args...)\n\t\t\tswitch {\n\t\t\tcase err == nil && output != tc.expectedOutput:\n\t\t\t\tt.Errorf(\"expected: %q, got: %q\", tc.expectedOutput, output)\n\t\t\tcase err != nil:\n\t\t\t\tt.Errorf(\"Unexpected error %q\", err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestArgsNotDetectedAsFlagsCompletionInGo(t *testing.T) {\n\t// Regression test that ensures the bug described in\n\t// https://github.com/spf13/cobra/issues/1816 does not occur anymore.\n\n\troot := Command{\n\t\tUse: \"root\",\n\t\tValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\t\treturn []string{\"service\", \"1-123\", \"11-123\"}, ShellCompDirectiveNoFileComp\n\t\t},\n\t}\n\n\tcompletion := `service\n1-123\n11-123\n:4\nCompletion ended with directive: ShellCompDirectiveNoFileComp\n`\n\n\ttestcases := []struct {\n\t\tdesc           string\n\t\targs           []string\n\t\texpectedOutput string\n\t}{\n\t\t{\n\t\t\tdesc:           \"empty\",\n\t\t\targs:           []string{\"\"},\n\t\t\texpectedOutput: completion,\n\t\t},\n\t\t{\n\t\t\tdesc:           \"service only\",\n\t\t\targs:           []string{\"service\", \"\"},\n\t\t\texpectedOutput: completion,\n\t\t},\n\t\t{\n\t\t\tdesc:           \"service last\",\n\t\t\targs:           []string{\"1-123\", \"service\", \"\"},\n\t\t\texpectedOutput: completion,\n\t\t},\n\t\t{\n\t\t\tdesc:           \"two digit prefixed dash last\",\n\t\t\targs:           []string{\"service\", \"11-123\", \"\"},\n\t\t\texpectedOutput: completion,\n\t\t},\n\t\t{\n\t\t\tdesc:           \"one digit prefixed dash last\",\n\t\t\targs:           []string{\"service\", \"1-123\", \"\"},\n\t\t\texpectedOutput: completion,\n\t\t},\n\t}\n\tfor _, tc := range testcases {\n\t\tt.Run(tc.desc, func(t *testing.T) {\n\t\t\targs := []string{ShellCompNoDescRequestCmd}\n\t\t\targs = append(args, tc.args...)\n\t\t\toutput, err := executeCommand(&root, args...)\n\t\t\tswitch {\n\t\t\tcase err == nil && output != tc.expectedOutput:\n\t\t\t\tt.Errorf(\"expected: %q, got: %q\", tc.expectedOutput, output)\n\t\t\tcase err != nil:\n\t\t\t\tt.Errorf(\"Unexpected error %q\", err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGetFlagCompletion(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\n\trootCmd.Flags().String(\"rootflag\", \"\", \"root flag\")\n\t_ = rootCmd.RegisterFlagCompletionFunc(\"rootflag\", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\treturn []string{\"rootvalue\"}, ShellCompDirectiveKeepOrder\n\t})\n\n\trootCmd.PersistentFlags().String(\"persistentflag\", \"\", \"persistent flag\")\n\t_ = rootCmd.RegisterFlagCompletionFunc(\"persistentflag\", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\treturn []string{\"persistentvalue\"}, ShellCompDirectiveDefault\n\t})\n\n\tchildCmd := &Command{Use: \"child\", Run: emptyRun}\n\n\tchildCmd.Flags().String(\"childflag\", \"\", \"child flag\")\n\t_ = childCmd.RegisterFlagCompletionFunc(\"childflag\", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\treturn []string{\"childvalue\"}, ShellCompDirectiveNoFileComp | ShellCompDirectiveNoSpace\n\t})\n\n\trootCmd.AddCommand(childCmd)\n\n\ttestcases := []struct {\n\t\tdesc      string\n\t\tcmd       *Command\n\t\tflagName  string\n\t\texists    bool\n\t\tcomps     []string\n\t\tdirective ShellCompDirective\n\t}{\n\t\t{\n\t\t\tdesc:      \"get flag completion function for command\",\n\t\t\tcmd:       rootCmd,\n\t\t\tflagName:  \"rootflag\",\n\t\t\texists:    true,\n\t\t\tcomps:     []string{\"rootvalue\"},\n\t\t\tdirective: ShellCompDirectiveKeepOrder,\n\t\t},\n\t\t{\n\t\t\tdesc:      \"get persistent flag completion function for command\",\n\t\t\tcmd:       rootCmd,\n\t\t\tflagName:  \"persistentflag\",\n\t\t\texists:    true,\n\t\t\tcomps:     []string{\"persistentvalue\"},\n\t\t\tdirective: ShellCompDirectiveDefault,\n\t\t},\n\t\t{\n\t\t\tdesc:      \"get flag completion function for child command\",\n\t\t\tcmd:       childCmd,\n\t\t\tflagName:  \"childflag\",\n\t\t\texists:    true,\n\t\t\tcomps:     []string{\"childvalue\"},\n\t\t\tdirective: ShellCompDirectiveNoFileComp | ShellCompDirectiveNoSpace,\n\t\t},\n\t\t{\n\t\t\tdesc:      \"get persistent flag completion function for child command\",\n\t\t\tcmd:       childCmd,\n\t\t\tflagName:  \"persistentflag\",\n\t\t\texists:    true,\n\t\t\tcomps:     []string{\"persistentvalue\"},\n\t\t\tdirective: ShellCompDirectiveDefault,\n\t\t},\n\t\t{\n\t\t\tdesc:     \"cannot get flag completion function for local parent flag\",\n\t\t\tcmd:      childCmd,\n\t\t\tflagName: \"rootflag\",\n\t\t\texists:   false,\n\t\t},\n\t}\n\n\tfor _, tc := range testcases {\n\t\tt.Run(tc.desc, func(t *testing.T) {\n\t\t\tcompFunc, exists := tc.cmd.GetFlagCompletionFunc(tc.flagName)\n\t\t\tif tc.exists != exists {\n\t\t\t\tt.Errorf(\"Unexpected result looking for flag completion function\")\n\t\t\t}\n\n\t\t\tif exists {\n\t\t\t\tcomps, directive := compFunc(tc.cmd, []string{}, \"\")\n\t\t\t\tif strings.Join(tc.comps, \" \") != strings.Join(comps, \" \") {\n\t\t\t\t\tt.Errorf(\"Unexpected completions %q\", comps)\n\t\t\t\t}\n\t\t\t\tif tc.directive != directive {\n\t\t\t\t\tt.Errorf(\"Unexpected directive %q\", directive)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGetEnvConfig(t *testing.T) {\n\ttestCases := []struct {\n\t\tdesc      string\n\t\tuse       string\n\t\tsuffix    string\n\t\tcmdVar    string\n\t\tglobalVar string\n\t\tcmdVal    string\n\t\tglobalVal string\n\t\texpected  string\n\t}{\n\t\t{\n\t\t\tdesc:      \"Command envvar overrides global\",\n\t\t\tuse:       \"root\",\n\t\t\tsuffix:    \"test\",\n\t\t\tcmdVar:    \"ROOT_TEST\",\n\t\t\tglobalVar: \"COBRA_TEST\",\n\t\t\tcmdVal:    \"cmd\",\n\t\t\tglobalVal: \"global\",\n\t\t\texpected:  \"cmd\",\n\t\t},\n\t\t{\n\t\t\tdesc:      \"Missing/empty command envvar falls back to global\",\n\t\t\tuse:       \"root\",\n\t\t\tsuffix:    \"test\",\n\t\t\tcmdVar:    \"ROOT_TEST\",\n\t\t\tglobalVar: \"COBRA_TEST\",\n\t\t\tcmdVal:    \"\",\n\t\t\tglobalVal: \"global\",\n\t\t\texpected:  \"global\",\n\t\t},\n\t\t{\n\t\t\tdesc:      \"Missing/empty command and global envvars fall back to empty\",\n\t\t\tuse:       \"root\",\n\t\t\tsuffix:    \"test\",\n\t\t\tcmdVar:    \"ROOT_TEST\",\n\t\t\tglobalVar: \"COBRA_TEST\",\n\t\t\tcmdVal:    \"\",\n\t\t\tglobalVal: \"\",\n\t\t\texpected:  \"\",\n\t\t},\n\t\t{\n\t\t\tdesc:      \"Periods in command use transform to underscores in env var name\",\n\t\t\tuse:       \"foo.bar\",\n\t\t\tsuffix:    \"test\",\n\t\t\tcmdVar:    \"FOO_BAR_TEST\",\n\t\t\tglobalVar: \"COBRA_TEST\",\n\t\t\tcmdVal:    \"cmd\",\n\t\t\tglobalVal: \"global\",\n\t\t\texpected:  \"cmd\",\n\t\t},\n\t\t{\n\t\t\tdesc:      \"Dashes in command use transform to underscores in env var name\",\n\t\t\tuse:       \"quux-BAZ\",\n\t\t\tsuffix:    \"test\",\n\t\t\tcmdVar:    \"QUUX_BAZ_TEST\",\n\t\t\tglobalVar: \"COBRA_TEST\",\n\t\t\tcmdVal:    \"cmd\",\n\t\t\tglobalVal: \"global\",\n\t\t\texpected:  \"cmd\",\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.desc, func(t *testing.T) {\n\t\t\t// Could make env handling cleaner with t.Setenv with Go >= 1.17\n\t\t\terr := os.Setenv(tc.cmdVar, tc.cmdVal)\n\t\t\tdefer func() {\n\t\t\t\tassertNoErr(t, os.Unsetenv(tc.cmdVar))\n\t\t\t}()\n\t\t\tassertNoErr(t, err)\n\t\t\terr = os.Setenv(tc.globalVar, tc.globalVal)\n\t\t\tdefer func() {\n\t\t\t\tassertNoErr(t, os.Unsetenv(tc.globalVar))\n\t\t\t}()\n\t\t\tassertNoErr(t, err)\n\t\t\tcmd := &Command{Use: tc.use}\n\t\t\tgot := getEnvConfig(cmd, tc.suffix)\n\t\t\tif got != tc.expected {\n\t\t\t\tt.Errorf(\"expected: %q, got: %q\", tc.expected, got)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestDisableDescriptions(t *testing.T) {\n\trootCmd := &Command{\n\t\tUse: \"root\",\n\t\tRun: emptyRun,\n\t}\n\n\tchildCmd := &Command{\n\t\tUse:   \"thechild\",\n\t\tShort: \"The child command\",\n\t\tRun:   emptyRun,\n\t}\n\trootCmd.AddCommand(childCmd)\n\n\tspecificDescriptionsEnvVar := configEnvVar(rootCmd.Name(), configEnvVarSuffixDescriptions)\n\tglobalDescriptionsEnvVar := configEnvVar(configEnvVarGlobalPrefix, configEnvVarSuffixDescriptions)\n\n\tconst (\n\t\tdescLineWithDescription    = \"first\\tdescription\"\n\t\tdescLineWithoutDescription = \"first\"\n\t)\n\tchildCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {\n\t\tcomps := []string{descLineWithDescription}\n\t\treturn comps, ShellCompDirectiveDefault\n\t}\n\n\ttestCases := []struct {\n\t\tdesc             string\n\t\tglobalEnvValue   string\n\t\tspecificEnvValue string\n\t\texpectedLine     string\n\t}{\n\t\t{\n\t\t\t\"No env variables set\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\tdescLineWithDescription,\n\t\t},\n\t\t{\n\t\t\t\"Global value false\",\n\t\t\t\"false\",\n\t\t\t\"\",\n\t\t\tdescLineWithoutDescription,\n\t\t},\n\t\t{\n\t\t\t\"Specific value false\",\n\t\t\t\"\",\n\t\t\t\"false\",\n\t\t\tdescLineWithoutDescription,\n\t\t},\n\t\t{\n\t\t\t\"Both values false\",\n\t\t\t\"false\",\n\t\t\t\"false\",\n\t\t\tdescLineWithoutDescription,\n\t\t},\n\t\t{\n\t\t\t\"Both values true\",\n\t\t\t\"true\",\n\t\t\t\"true\",\n\t\t\tdescLineWithDescription,\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.desc, func(t *testing.T) {\n\t\t\tif err := os.Setenv(specificDescriptionsEnvVar, tc.specificEnvValue); err != nil {\n\t\t\t\tt.Errorf(\"Unexpected error setting %s: %v\", specificDescriptionsEnvVar, err)\n\t\t\t}\n\t\t\tif err := os.Setenv(globalDescriptionsEnvVar, tc.globalEnvValue); err != nil {\n\t\t\t\tt.Errorf(\"Unexpected error setting %s: %v\", globalDescriptionsEnvVar, err)\n\t\t\t}\n\n\t\t\tvar run = func() {\n\t\t\t\toutput, err := executeCommand(rootCmd, ShellCompRequestCmd, \"thechild\", \"\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t\t\t}\n\n\t\t\t\texpected := strings.Join([]string{\n\t\t\t\t\ttc.expectedLine,\n\t\t\t\t\t\":0\",\n\t\t\t\t\t\"Completion ended with directive: ShellCompDirectiveDefault\", \"\"}, \"\\n\")\n\t\t\t\tif output != expected {\n\t\t\t\t\tt.Errorf(\"expected: %q, got: %q\", expected, output)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\trun()\n\n\t\t\t// For empty cases, test also unset state\n\t\t\tif tc.specificEnvValue == \"\" {\n\t\t\t\tif err := os.Unsetenv(specificDescriptionsEnvVar); err != nil {\n\t\t\t\t\tt.Errorf(\"Unexpected error unsetting %s: %v\", specificDescriptionsEnvVar, err)\n\t\t\t\t}\n\t\t\t\trun()\n\t\t\t}\n\t\t\tif tc.globalEnvValue == \"\" {\n\t\t\t\tif err := os.Unsetenv(globalDescriptionsEnvVar); err != nil {\n\t\t\t\t\tt.Errorf(\"Unexpected error unsetting %s: %v\", globalDescriptionsEnvVar, err)\n\t\t\t\t}\n\t\t\t\trun()\n\t\t\t}\n\t\t})\n\t}\n}\n\n// A test to make sure the InitDefaultCompletionCmd function works as expected\n// in case a project calls it directly.\nfunc TestInitDefaultCompletionCmd(t *testing.T) {\n\n\ttestCases := []struct {\n\t\tdesc          string\n\t\thasChildCmd   bool\n\t\targs          []string\n\t\texpectCompCmd bool\n\t}{\n\t\t{\n\t\t\tdesc:          \"no child command and not calling the completion command\",\n\t\t\thasChildCmd:   false,\n\t\t\targs:          []string{\"somearg\"},\n\t\t\texpectCompCmd: false,\n\t\t},\n\t\t{\n\t\t\tdesc:          \"no child command but calling the completion command\",\n\t\t\thasChildCmd:   false,\n\t\t\targs:          []string{\"completion\"},\n\t\t\texpectCompCmd: true,\n\t\t},\n\t\t{\n\t\t\tdesc:          \"no child command but calling __complete on the root command\",\n\t\t\thasChildCmd:   false,\n\t\t\targs:          []string{\"__complete\", \"\"},\n\t\t\texpectCompCmd: false,\n\t\t},\n\t\t{\n\t\t\tdesc:          \"no child command but calling __complete on the completion command\",\n\t\t\thasChildCmd:   false,\n\t\t\targs:          []string{\"__complete\", \"completion\", \"\"},\n\t\t\texpectCompCmd: true,\n\t\t},\n\t\t{\n\t\t\tdesc:          \"with child command\",\n\t\t\thasChildCmd:   true,\n\t\t\targs:          []string{\"child\"},\n\t\t\texpectCompCmd: true,\n\t\t},\n\t\t{\n\t\t\tdesc:          \"no child command not passing args\",\n\t\t\thasChildCmd:   false,\n\t\t\targs:          nil,\n\t\t\texpectCompCmd: false,\n\t\t},\n\t\t{\n\t\t\tdesc:          \"with child command not passing args\",\n\t\t\thasChildCmd:   true,\n\t\t\targs:          nil,\n\t\t\texpectCompCmd: true,\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.desc, func(t *testing.T) {\n\t\t\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\t\t\tchildCmd := &Command{Use: \"child\", Run: emptyRun}\n\n\t\t\texpectedNumSubCommands := 0\n\t\t\tif tc.hasChildCmd {\n\t\t\t\trootCmd.AddCommand(childCmd)\n\t\t\t\texpectedNumSubCommands++\n\t\t\t}\n\n\t\t\tif tc.expectCompCmd {\n\t\t\t\texpectedNumSubCommands++\n\t\t\t}\n\n\t\t\tif len(tc.args) > 0 && tc.args[0] == \"__complete\" {\n\t\t\t\texpectedNumSubCommands++\n\t\t\t}\n\n\t\t\t// Setup the __complete command to mimic real world scenarios\n\t\t\trootCmd.initCompleteCmd(tc.args)\n\n\t\t\t// Call the InitDefaultCompletionCmd function directly\n\t\t\tif tc.args == nil {\n\t\t\t\trootCmd.InitDefaultCompletionCmd()\n\t\t\t} else {\n\t\t\t\trootCmd.InitDefaultCompletionCmd(tc.args...)\n\t\t\t}\n\n\t\t\t// Check if the completion command was added\n\t\t\tif len(rootCmd.Commands()) != expectedNumSubCommands {\n\t\t\t\tt.Errorf(\"Expected %d subcommands, got %d\", expectedNumSubCommands, len(rootCmd.Commands()))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCustomDefaultShellCompDirective(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Run: emptyRun}\n\trootCmd.PersistentFlags().String(\"string\", \"\", \"test string flag\")\n\t// use ShellCompDirectiveNoFileComp instead of the default, which is ShellCompDirectiveDefault.\n\trootCmd.CompletionOptions.SetDefaultShellCompDirective(ShellCompDirectiveNoFileComp)\n\n\t// child1 inherits the custom DefaultShellCompDirective.\n\tchildCmd1 := &Command{Use: \"child1\", Run: emptyRun}\n\t// child2 resets the custom DefaultShellCompDirective to the default value.\n\tchildCmd2 := &Command{Use: \"child2\", Run: emptyRun}\n\tchildCmd2.CompletionOptions.SetDefaultShellCompDirective(ShellCompDirectiveDefault)\n\n\trootCmd.AddCommand(childCmd1, childCmd2)\n\n\ttestCases := []struct {\n\t\tdesc              string\n\t\targs              []string\n\t\texpectedDirective string\n\t}{\n\t\t{\n\t\t\t\"flag completion on root command with custom DefaultShellCompDirective\",\n\t\t\t[]string{\"--string\", \"\"},\n\t\t\t\"ShellCompDirectiveNoFileComp\",\n\t\t},\n\t\t{\n\t\t\t\"flag completion on subcommand with inherited custom DefaultShellCompDirective\",\n\t\t\t[]string{\"child1\", \"--string\", \"\"},\n\t\t\t\"ShellCompDirectiveNoFileComp\",\n\t\t},\n\t\t{\n\t\t\t\"flag completion on subcommand with reset DefaultShellCompDirective\",\n\t\t\t[]string{\"child2\", \"--string\", \"\"},\n\t\t\t\"ShellCompDirectiveDefault\",\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.desc, func(t *testing.T) {\n\t\t\targs := []string{ShellCompNoDescRequestCmd}\n\t\t\targs = append(args, tc.args...)\n\n\t\t\toutput, err := executeCommand(rootCmd, args...)\n\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t\t}\n\n\t\t\toutputWords := strings.Split(strings.TrimSpace(output), \" \")\n\t\t\tdirective := outputWords[len(outputWords)-1]\n\n\t\t\tif directive != tc.expectedDirective {\n\t\t\t\tt.Errorf(\"expected: %q, got: %q\", tc.expectedDirective, directive)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "doc/cmd_test.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage doc\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nfunc emptyRun(*cobra.Command, []string) {}\n\nfunc init() {\n\trootCmd.PersistentFlags().StringP(\"rootflag\", \"r\", \"two\", \"\")\n\trootCmd.PersistentFlags().StringP(\"strtwo\", \"t\", \"two\", \"help message for parent flag strtwo\")\n\n\techoCmd.PersistentFlags().StringP(\"strone\", \"s\", \"one\", \"help message for flag strone\")\n\techoCmd.PersistentFlags().BoolP(\"persistentbool\", \"p\", false, \"help message for flag persistentbool\")\n\techoCmd.Flags().IntP(\"intone\", \"i\", 123, \"help message for flag intone\")\n\techoCmd.Flags().BoolP(\"boolone\", \"b\", true, \"help message for flag boolone\")\n\n\ttimesCmd.PersistentFlags().StringP(\"strtwo\", \"t\", \"2\", \"help message for child flag strtwo\")\n\ttimesCmd.Flags().IntP(\"inttwo\", \"j\", 234, \"help message for flag inttwo\")\n\ttimesCmd.Flags().BoolP(\"booltwo\", \"c\", false, \"help message for flag booltwo\")\n\n\tprintCmd.PersistentFlags().StringP(\"strthree\", \"s\", \"three\", \"help message for flag strthree\")\n\tprintCmd.Flags().IntP(\"intthree\", \"i\", 345, \"help message for flag intthree\")\n\tprintCmd.Flags().BoolP(\"boolthree\", \"b\", true, \"help message for flag boolthree\")\n\n\techoCmd.AddCommand(timesCmd, echoSubCmd, deprecatedCmd)\n\trootCmd.AddCommand(printCmd, echoCmd, dummyCmd)\n}\n\nvar rootCmd = &cobra.Command{\n\tUse:   \"root\",\n\tShort: \"Root short description\",\n\tLong:  \"Root long description\",\n\tRun:   emptyRun,\n}\n\nvar echoCmd = &cobra.Command{\n\tUse:     \"echo [string to echo]\",\n\tAliases: []string{\"say\"},\n\tShort:   \"Echo anything to the screen\",\n\tLong:    \"an utterly useless command for testing\",\n\tExample: \"Just run cobra-test echo\",\n}\n\nvar echoSubCmd = &cobra.Command{\n\tUse:   \"echosub [string to print]\",\n\tShort: \"second sub command for echo\",\n\tLong:  \"an absolutely utterly useless command for testing gendocs!.\",\n\tRun:   emptyRun,\n}\n\nvar timesCmd = &cobra.Command{\n\tUse:        \"times [# times] [string to echo]\",\n\tSuggestFor: []string{\"counts\"},\n\tShort:      \"Echo anything to the screen more times\",\n\tLong:       `a slightly useless command for testing.`,\n\tRun:        emptyRun,\n}\n\nvar deprecatedCmd = &cobra.Command{\n\tUse:        \"deprecated [can't do anything here]\",\n\tShort:      \"A command which is deprecated\",\n\tLong:       `an absolutely utterly useless command for testing deprecation!.`,\n\tDeprecated: \"Please use echo instead\",\n}\n\nvar printCmd = &cobra.Command{\n\tUse:   \"print [string to print]\",\n\tShort: \"Print anything to the screen\",\n\tLong:  `an absolutely utterly useless command for testing.`,\n}\n\nvar dummyCmd = &cobra.Command{\n\tUse:   \"dummy [action]\",\n\tShort: \"Performs a dummy action\",\n}\n\nfunc checkStringContains(t *testing.T, got, expected string) {\n\tif !strings.Contains(got, expected) {\n\t\tt.Errorf(\"Expected to contain: \\n %v\\nGot:\\n %v\\n\", expected, got)\n\t}\n}\n\nfunc checkStringOmits(t *testing.T, got, expected string) {\n\tif strings.Contains(got, expected) {\n\t\tt.Errorf(\"Expected to not contain: \\n %v\\nGot: %v\", expected, got)\n\t}\n}\n"
  },
  {
    "path": "doc/man_docs.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage doc\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/cpuguy83/go-md2man/v2/md2man\"\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/pflag\"\n)\n\n// GenManTree will generate a man page for this command and all descendants\n// in the directory given. The header may be nil. This function may not work\n// correctly if your command names have `-` in them. If you have `cmd` with two\n// subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third`\n// it is undefined which help output will be in the file `cmd-sub-third.1`.\nfunc GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error {\n\treturn GenManTreeFromOpts(cmd, GenManTreeOptions{\n\t\tHeader:           header,\n\t\tPath:             dir,\n\t\tCommandSeparator: \"-\",\n\t})\n}\n\n// GenManTreeFromOpts generates a man page for the command and all descendants.\n// The pages are written to the opts.Path directory.\nfunc GenManTreeFromOpts(cmd *cobra.Command, opts GenManTreeOptions) error {\n\theader := opts.Header\n\tif header == nil {\n\t\theader = &GenManHeader{}\n\t}\n\tfor _, c := range cmd.Commands() {\n\t\tif !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {\n\t\t\tcontinue\n\t\t}\n\t\tif err := GenManTreeFromOpts(c, opts); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tsection := \"1\"\n\tif header.Section != \"\" {\n\t\tsection = header.Section\n\t}\n\n\tseparator := \"_\"\n\tif opts.CommandSeparator != \"\" {\n\t\tseparator = opts.CommandSeparator\n\t}\n\tbasename := strings.ReplaceAll(cmd.CommandPath(), \" \", separator)\n\tfilename := filepath.Join(opts.Path, basename+\".\"+section)\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\theaderCopy := *header\n\treturn GenMan(cmd, &headerCopy, f)\n}\n\n// GenManTreeOptions is the options for generating the man pages.\n// Used only in GenManTreeFromOpts.\ntype GenManTreeOptions struct {\n\tHeader           *GenManHeader\n\tPath             string\n\tCommandSeparator string\n}\n\n// GenManHeader is a lot like the .TH header at the start of man pages. These\n// include the title, section, date, source, and manual. We will use the\n// current time if Date is unset and will use \"Auto generated by spf13/cobra\"\n// if the Source is unset.\ntype GenManHeader struct {\n\tTitle   string\n\tSection string\n\tDate    *time.Time\n\tdate    string\n\tSource  string\n\tManual  string\n}\n\n// GenMan will generate a man page for the given command and write it to\n// w. The header argument may be nil, however obviously w may not.\nfunc GenMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error {\n\tif header == nil {\n\t\theader = &GenManHeader{}\n\t}\n\tif err := fillHeader(header, cmd.CommandPath(), cmd.DisableAutoGenTag); err != nil {\n\t\treturn err\n\t}\n\n\tb := genMan(cmd, header)\n\t_, err := w.Write(md2man.Render(b))\n\treturn err\n}\n\nfunc fillHeader(header *GenManHeader, name string, disableAutoGen bool) error {\n\tif header.Title == \"\" {\n\t\theader.Title = strings.ToUpper(strings.ReplaceAll(name, \" \", \"\\\\-\"))\n\t}\n\tif header.Section == \"\" {\n\t\theader.Section = \"1\"\n\t}\n\tif header.Date == nil {\n\t\tnow := time.Now()\n\t\tif epoch := os.Getenv(\"SOURCE_DATE_EPOCH\"); epoch != \"\" {\n\t\t\tunixEpoch, err := strconv.ParseInt(epoch, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"invalid SOURCE_DATE_EPOCH: %v\", err)\n\t\t\t}\n\t\t\tnow = time.Unix(unixEpoch, 0)\n\t\t}\n\t\theader.Date = &now\n\t}\n\theader.date = header.Date.Format(\"Jan 2006\")\n\tif header.Source == \"\" && !disableAutoGen {\n\t\theader.Source = \"Auto generated by spf13/cobra\"\n\t}\n\treturn nil\n}\n\nfunc manPreamble(buf io.StringWriter, header *GenManHeader, cmd *cobra.Command, dashedName string) {\n\tdescription := cmd.Long\n\tif len(description) == 0 {\n\t\tdescription = cmd.Short\n\t}\n\n\tcobra.WriteStringAndCheck(buf, fmt.Sprintf(`%% \"%s\" \"%s\" \"%s\" \"%s\" \"%s\"\n# NAME\n`, header.Title, header.Section, header.date, header.Source, header.Manual))\n\tcobra.WriteStringAndCheck(buf, fmt.Sprintf(\"%s \\\\- %s\\n\\n\", dashedName, cmd.Short))\n\tcobra.WriteStringAndCheck(buf, \"# SYNOPSIS\\n\")\n\tcobra.WriteStringAndCheck(buf, fmt.Sprintf(\"**%s**\\n\\n\", cmd.UseLine()))\n\tcobra.WriteStringAndCheck(buf, \"# DESCRIPTION\\n\")\n\tcobra.WriteStringAndCheck(buf, description+\"\\n\\n\")\n}\n\nfunc manPrintFlags(buf io.StringWriter, flags *pflag.FlagSet) {\n\tflags.VisitAll(func(flag *pflag.Flag) {\n\t\tif len(flag.Deprecated) > 0 || flag.Hidden {\n\t\t\treturn\n\t\t}\n\t\tformat := \"\"\n\t\tif len(flag.Shorthand) > 0 && len(flag.ShorthandDeprecated) == 0 {\n\t\t\tformat = fmt.Sprintf(\"**-%s**, **--%s**\", flag.Shorthand, flag.Name)\n\t\t} else {\n\t\t\tformat = fmt.Sprintf(\"**--%s**\", flag.Name)\n\t\t}\n\t\tif len(flag.NoOptDefVal) > 0 {\n\t\t\tformat += \"[\"\n\t\t}\n\t\tif flag.Value.Type() == \"string\" {\n\t\t\t// put quotes on the value\n\t\t\tformat += \"=%q\"\n\t\t} else {\n\t\t\tformat += \"=%s\"\n\t\t}\n\t\tif len(flag.NoOptDefVal) > 0 {\n\t\t\tformat += \"]\"\n\t\t}\n\t\tformat += \"\\n\\t%s\\n\\n\"\n\t\tcobra.WriteStringAndCheck(buf, fmt.Sprintf(format, flag.DefValue, flag.Usage))\n\t})\n}\n\nfunc manPrintOptions(buf io.StringWriter, command *cobra.Command) {\n\tflags := command.NonInheritedFlags()\n\tif flags.HasAvailableFlags() {\n\t\tcobra.WriteStringAndCheck(buf, \"# OPTIONS\\n\")\n\t\tmanPrintFlags(buf, flags)\n\t\tcobra.WriteStringAndCheck(buf, \"\\n\")\n\t}\n\tflags = command.InheritedFlags()\n\tif flags.HasAvailableFlags() {\n\t\tcobra.WriteStringAndCheck(buf, \"# OPTIONS INHERITED FROM PARENT COMMANDS\\n\")\n\t\tmanPrintFlags(buf, flags)\n\t\tcobra.WriteStringAndCheck(buf, \"\\n\")\n\t}\n}\n\nfunc genMan(cmd *cobra.Command, header *GenManHeader) []byte {\n\tcmd.InitDefaultHelpCmd()\n\tcmd.InitDefaultHelpFlag()\n\n\t// something like `rootcmd-subcmd1-subcmd2`\n\tdashCommandName := strings.ReplaceAll(cmd.CommandPath(), \" \", \"-\")\n\n\tbuf := new(bytes.Buffer)\n\n\tmanPreamble(buf, header, cmd, dashCommandName)\n\tmanPrintOptions(buf, cmd)\n\tif len(cmd.Example) > 0 {\n\t\tbuf.WriteString(\"# EXAMPLE\\n\")\n\t\tfmt.Fprintf(buf, \"```\\n%s\\n```\\n\", cmd.Example)\n\t}\n\tif hasSeeAlso(cmd) {\n\t\tbuf.WriteString(\"# SEE ALSO\\n\")\n\t\tseealsos := make([]string, 0)\n\t\tif cmd.HasParent() {\n\t\t\tparentPath := cmd.Parent().CommandPath()\n\t\t\tdashParentPath := strings.ReplaceAll(parentPath, \" \", \"-\")\n\t\t\tseealso := fmt.Sprintf(\"**%s(%s)**\", dashParentPath, header.Section)\n\t\t\tseealsos = append(seealsos, seealso)\n\t\t\tcmd.VisitParents(func(c *cobra.Command) {\n\t\t\t\tif c.DisableAutoGenTag {\n\t\t\t\t\tcmd.DisableAutoGenTag = c.DisableAutoGenTag\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\tchildren := cmd.Commands()\n\t\tsort.Sort(byName(children))\n\t\tfor _, c := range children {\n\t\t\tif !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tseealso := fmt.Sprintf(\"**%s-%s(%s)**\", dashCommandName, c.Name(), header.Section)\n\t\t\tseealsos = append(seealsos, seealso)\n\t\t}\n\t\tbuf.WriteString(strings.Join(seealsos, \", \") + \"\\n\")\n\t}\n\tif !cmd.DisableAutoGenTag {\n\t\tfmt.Fprintf(buf, \"# HISTORY\\n%s Auto generated by spf13/cobra\\n\", header.Date.Format(\"2-Jan-2006\"))\n\t}\n\treturn buf.Bytes()\n}\n"
  },
  {
    "path": "doc/man_docs_test.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage doc\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nfunc assertNoErr(t *testing.T, e error) {\n\tif e != nil {\n\t\tt.Error(e)\n\t}\n}\n\nfunc translate(in string) string {\n\treturn strings.ReplaceAll(in, \"-\", \"\\\\-\")\n}\n\nfunc TestGenManDoc(t *testing.T) {\n\theader := &GenManHeader{\n\t\tTitle:   \"Project\",\n\t\tSection: \"2\",\n\t}\n\n\t// We generate on a subcommand so we have both subcommands and parents\n\tbuf := new(bytes.Buffer)\n\tif err := GenMan(echoCmd, header, buf); err != nil {\n\t\tt.Fatal(err)\n\t}\n\toutput := buf.String()\n\n\t// Make sure parent has - in CommandPath() in SEE ALSO:\n\tparentPath := echoCmd.Parent().CommandPath()\n\tdashParentPath := strings.ReplaceAll(parentPath, \" \", \"-\")\n\texpected := translate(dashParentPath)\n\texpected = expected + \"(\" + header.Section + \")\"\n\tcheckStringContains(t, output, expected)\n\n\tcheckStringContains(t, output, translate(echoCmd.Name()))\n\tcheckStringContains(t, output, translate(echoCmd.Name()))\n\tcheckStringContains(t, output, \"boolone\")\n\tcheckStringContains(t, output, \"rootflag\")\n\tcheckStringContains(t, output, translate(rootCmd.Name()))\n\tcheckStringContains(t, output, translate(echoSubCmd.Name()))\n\tcheckStringOmits(t, output, translate(deprecatedCmd.Name()))\n\tcheckStringContains(t, output, translate(\"Auto generated\"))\n}\n\nfunc TestGenManNoHiddenParents(t *testing.T) {\n\theader := &GenManHeader{\n\t\tTitle:   \"Project\",\n\t\tSection: \"2\",\n\t}\n\n\t// We generate on a subcommand so we have both subcommands and parents\n\tfor _, name := range []string{\"rootflag\", \"strtwo\"} {\n\t\tf := rootCmd.PersistentFlags().Lookup(name)\n\t\tf.Hidden = true\n\t\tdefer func() { f.Hidden = false }()\n\t}\n\tbuf := new(bytes.Buffer)\n\tif err := GenMan(echoCmd, header, buf); err != nil {\n\t\tt.Fatal(err)\n\t}\n\toutput := buf.String()\n\n\t// Make sure parent has - in CommandPath() in SEE ALSO:\n\tparentPath := echoCmd.Parent().CommandPath()\n\tdashParentPath := strings.ReplaceAll(parentPath, \" \", \"-\")\n\texpected := translate(dashParentPath)\n\texpected = expected + \"(\" + header.Section + \")\"\n\tcheckStringContains(t, output, expected)\n\n\tcheckStringContains(t, output, translate(echoCmd.Name()))\n\tcheckStringContains(t, output, translate(echoCmd.Name()))\n\tcheckStringContains(t, output, \"boolone\")\n\tcheckStringOmits(t, output, \"rootflag\")\n\tcheckStringContains(t, output, translate(rootCmd.Name()))\n\tcheckStringContains(t, output, translate(echoSubCmd.Name()))\n\tcheckStringOmits(t, output, translate(deprecatedCmd.Name()))\n\tcheckStringContains(t, output, translate(\"Auto generated\"))\n\tcheckStringOmits(t, output, \"OPTIONS INHERITED FROM PARENT COMMANDS\")\n}\n\nfunc TestGenManNoGenTag(t *testing.T) {\n\techoCmd.DisableAutoGenTag = true\n\tdefer func() { echoCmd.DisableAutoGenTag = false }()\n\n\theader := &GenManHeader{\n\t\tTitle:   \"Project\",\n\t\tSection: \"2\",\n\t}\n\n\t// We generate on a subcommand so we have both subcommands and parents\n\tbuf := new(bytes.Buffer)\n\tif err := GenMan(echoCmd, header, buf); err != nil {\n\t\tt.Fatal(err)\n\t}\n\toutput := buf.String()\n\n\tunexpected := translate(\"#HISTORY\")\n\tcheckStringOmits(t, output, unexpected)\n\tunexpected = translate(\"Auto generated by spf13/cobra\")\n\tcheckStringOmits(t, output, unexpected)\n}\n\nfunc TestGenManSeeAlso(t *testing.T) {\n\trootCmd := &cobra.Command{Use: \"root\", Run: emptyRun}\n\taCmd := &cobra.Command{Use: \"aaa\", Run: emptyRun, Hidden: true} // #229\n\tbCmd := &cobra.Command{Use: \"bbb\", Run: emptyRun}\n\tcCmd := &cobra.Command{Use: \"ccc\", Run: emptyRun}\n\trootCmd.AddCommand(aCmd, bCmd, cCmd)\n\n\tbuf := new(bytes.Buffer)\n\theader := &GenManHeader{}\n\tif err := GenMan(rootCmd, header, buf); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tscanner := bufio.NewScanner(buf)\n\n\tif err := assertLineFound(scanner, \".SH SEE ALSO\"); err != nil {\n\t\tt.Fatalf(\"Couldn't find SEE ALSO section header: %v\", err)\n\t}\n\tif err := assertNextLineEquals(scanner, `\\fBroot-bbb(1)\\fP, \\fBroot-ccc(1)\\fP`); err != nil {\n\t\tt.Fatalf(\"Second line after SEE ALSO wasn't correct: %v\", err)\n\t}\n}\n\nfunc TestManPrintFlagsHidesShortDeprecated(t *testing.T) {\n\tc := &cobra.Command{}\n\tc.Flags().StringP(\"foo\", \"f\", \"default\", \"Foo flag\")\n\tassertNoErr(t, c.Flags().MarkShorthandDeprecated(\"foo\", \"don't use it no more\"))\n\n\tbuf := new(bytes.Buffer)\n\tmanPrintFlags(buf, c.Flags())\n\n\tgot := buf.String()\n\texpected := \"**--foo**=\\\"default\\\"\\n\\tFoo flag\\n\\n\"\n\tif got != expected {\n\t\tt.Errorf(\"Expected %v, got %v\", expected, got)\n\t}\n}\n\nfunc TestGenManTree(t *testing.T) {\n\tc := &cobra.Command{Use: \"do [OPTIONS] arg1 arg2\"}\n\theader := &GenManHeader{Section: \"2\"}\n\ttmpdir, err := os.MkdirTemp(\"\", \"test-gen-man-tree\")\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create tmpdir: %s\", err.Error())\n\t}\n\tdefer os.RemoveAll(tmpdir)\n\n\tif err := GenManTree(c, header, tmpdir); err != nil {\n\t\tt.Fatalf(\"GenManTree failed: %s\", err.Error())\n\t}\n\n\tif _, err := os.Stat(filepath.Join(tmpdir, \"do.2\")); err != nil {\n\t\tt.Fatalf(\"Expected file 'do.2' to exist\")\n\t}\n\n\tif header.Title != \"\" {\n\t\tt.Fatalf(\"Expected header.Title to be unmodified\")\n\t}\n}\n\nfunc assertLineFound(scanner *bufio.Scanner, expectedLine string) error {\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif line == expectedLine {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn fmt.Errorf(\"scan failed: %s\", err)\n\t}\n\n\treturn fmt.Errorf(\"hit EOF before finding %v\", expectedLine)\n}\n\nfunc assertNextLineEquals(scanner *bufio.Scanner, expectedLine string) error {\n\tif scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif line == expectedLine {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"got %v, not %v\", line, expectedLine)\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn fmt.Errorf(\"scan failed: %v\", err)\n\t}\n\n\treturn fmt.Errorf(\"hit EOF before finding %v\", expectedLine)\n}\n\nfunc BenchmarkGenManToFile(b *testing.B) {\n\tfile, err := os.CreateTemp(\"\", \"\")\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\tdefer os.Remove(file.Name())\n\tdefer file.Close()\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tif err := GenMan(rootCmd, nil, file); err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "doc/man_examples_test.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage doc_test\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/cobra/doc\"\n)\n\nfunc ExampleGenManTree() {\n\tcmd := &cobra.Command{\n\t\tUse:   \"test\",\n\t\tShort: \"my test program\",\n\t}\n\theader := &doc.GenManHeader{\n\t\tTitle:   \"MINE\",\n\t\tSection: \"3\",\n\t}\n\tcobra.CheckErr(doc.GenManTree(cmd, header, \"/tmp\"))\n}\n\nfunc ExampleGenMan() {\n\tcmd := &cobra.Command{\n\t\tUse:   \"test\",\n\t\tShort: \"my test program\",\n\t}\n\theader := &doc.GenManHeader{\n\t\tTitle:   \"MINE\",\n\t\tSection: \"3\",\n\t}\n\tout := new(bytes.Buffer)\n\tcobra.CheckErr(doc.GenMan(cmd, header, out))\n\tfmt.Print(out.String())\n}\n"
  },
  {
    "path": "doc/md_docs.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage doc\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nconst markdownExtension = \".md\"\n\nfunc printOptions(buf *bytes.Buffer, cmd *cobra.Command, name string) error {\n\tflags := cmd.NonInheritedFlags()\n\tflags.SetOutput(buf)\n\tif flags.HasAvailableFlags() {\n\t\tbuf.WriteString(\"### Options\\n\\n```\\n\")\n\t\tflags.PrintDefaults()\n\t\tbuf.WriteString(\"```\\n\\n\")\n\t}\n\n\tparentFlags := cmd.InheritedFlags()\n\tparentFlags.SetOutput(buf)\n\tif parentFlags.HasAvailableFlags() {\n\t\tbuf.WriteString(\"### Options inherited from parent commands\\n\\n```\\n\")\n\t\tparentFlags.PrintDefaults()\n\t\tbuf.WriteString(\"```\\n\\n\")\n\t}\n\treturn nil\n}\n\n// GenMarkdown creates markdown output.\nfunc GenMarkdown(cmd *cobra.Command, w io.Writer) error {\n\treturn GenMarkdownCustom(cmd, w, func(s string) string { return s })\n}\n\n// GenMarkdownCustom creates custom markdown output.\nfunc GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {\n\tcmd.InitDefaultHelpCmd()\n\tcmd.InitDefaultHelpFlag()\n\n\tbuf := new(bytes.Buffer)\n\tname := cmd.CommandPath()\n\n\tbuf.WriteString(\"## \" + name + \"\\n\\n\")\n\tbuf.WriteString(cmd.Short + \"\\n\\n\")\n\tif len(cmd.Long) > 0 {\n\t\tbuf.WriteString(\"### Synopsis\\n\\n\")\n\t\tbuf.WriteString(cmd.Long + \"\\n\\n\")\n\t}\n\n\tif cmd.Runnable() {\n\t\tfmt.Fprintf(buf, \"```\\n%s\\n```\\n\\n\", cmd.UseLine())\n\t}\n\n\tif len(cmd.Example) > 0 {\n\t\tbuf.WriteString(\"### Examples\\n\\n\")\n\t\tfmt.Fprintf(buf, \"```\\n%s\\n```\\n\\n\", cmd.Example)\n\t}\n\n\tif err := printOptions(buf, cmd, name); err != nil {\n\t\treturn err\n\t}\n\tif hasSeeAlso(cmd) {\n\t\tbuf.WriteString(\"### SEE ALSO\\n\\n\")\n\t\tif cmd.HasParent() {\n\t\t\tparent := cmd.Parent()\n\t\t\tpname := parent.CommandPath()\n\t\t\tlink := pname + markdownExtension\n\t\t\tlink = strings.ReplaceAll(link, \" \", \"_\")\n\t\t\tfmt.Fprintf(buf, \"* [%s](%s)\\t - %s\\n\", pname, linkHandler(link), parent.Short)\n\t\t\tcmd.VisitParents(func(c *cobra.Command) {\n\t\t\t\tif c.DisableAutoGenTag {\n\t\t\t\t\tcmd.DisableAutoGenTag = c.DisableAutoGenTag\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\n\t\tchildren := cmd.Commands()\n\t\tsort.Sort(byName(children))\n\n\t\tfor _, child := range children {\n\t\t\tif !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcname := name + \" \" + child.Name()\n\t\t\tlink := cname + markdownExtension\n\t\t\tlink = strings.ReplaceAll(link, \" \", \"_\")\n\t\t\tfmt.Fprintf(buf, \"* [%s](%s)\\t - %s\\n\", cname, linkHandler(link), child.Short)\n\t\t}\n\t\tbuf.WriteString(\"\\n\")\n\t}\n\tif !cmd.DisableAutoGenTag {\n\t\tbuf.WriteString(\"###### Auto generated by spf13/cobra on \" + time.Now().Format(\"2-Jan-2006\") + \"\\n\")\n\t}\n\t_, err := buf.WriteTo(w)\n\treturn err\n}\n\n// GenMarkdownTree will generate a markdown page for this command and all\n// descendants in the directory given. The header may be nil.\n// This function may not work correctly if your command names have `-` in them.\n// If you have `cmd` with two subcmds, `sub` and `sub-third`,\n// and `sub` has a subcommand called `third`, it is undefined which\n// help output will be in the file `cmd-sub-third.1`.\nfunc GenMarkdownTree(cmd *cobra.Command, dir string) error {\n\tidentity := func(s string) string { return s }\n\temptyStr := func(s string) string { return \"\" }\n\treturn GenMarkdownTreeCustom(cmd, dir, emptyStr, identity)\n}\n\n// GenMarkdownTreeCustom is the same as GenMarkdownTree, but\n// with custom filePrepender and linkHandler.\nfunc GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {\n\tfor _, c := range cmd.Commands() {\n\t\tif !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {\n\t\t\tcontinue\n\t\t}\n\t\tif err := GenMarkdownTreeCustom(c, dir, filePrepender, linkHandler); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tbasename := strings.ReplaceAll(cmd.CommandPath(), \" \", \"_\") + markdownExtension\n\tfilename := filepath.Join(dir, basename)\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tif _, err := io.WriteString(f, filePrepender(filename)); err != nil {\n\t\treturn err\n\t}\n\tif err := GenMarkdownCustom(cmd, f, linkHandler); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "doc/md_docs_test.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage doc\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nfunc TestGenMdDoc(t *testing.T) {\n\t// We generate on subcommand so we have both subcommands and parents.\n\tbuf := new(bytes.Buffer)\n\tif err := GenMarkdown(echoCmd, buf); err != nil {\n\t\tt.Fatal(err)\n\t}\n\toutput := buf.String()\n\n\tcheckStringContains(t, output, echoCmd.Long)\n\tcheckStringContains(t, output, echoCmd.Example)\n\tcheckStringContains(t, output, \"boolone\")\n\tcheckStringContains(t, output, \"rootflag\")\n\tcheckStringContains(t, output, rootCmd.Short)\n\tcheckStringContains(t, output, echoSubCmd.Short)\n\tcheckStringOmits(t, output, deprecatedCmd.Short)\n\tcheckStringContains(t, output, \"Options inherited from parent commands\")\n}\n\nfunc TestGenMdDocWithNoLongOrSynopsis(t *testing.T) {\n\t// We generate on subcommand so we have both subcommands and parents.\n\tbuf := new(bytes.Buffer)\n\tif err := GenMarkdown(dummyCmd, buf); err != nil {\n\t\tt.Fatal(err)\n\t}\n\toutput := buf.String()\n\n\tcheckStringContains(t, output, dummyCmd.Example)\n\tcheckStringContains(t, output, dummyCmd.Short)\n\tcheckStringContains(t, output, \"Options inherited from parent commands\")\n\tcheckStringOmits(t, output, \"### Synopsis\")\n}\n\nfunc TestGenMdNoHiddenParents(t *testing.T) {\n\t// We generate on subcommand so we have both subcommands and parents.\n\tfor _, name := range []string{\"rootflag\", \"strtwo\"} {\n\t\tf := rootCmd.PersistentFlags().Lookup(name)\n\t\tf.Hidden = true\n\t\tdefer func() { f.Hidden = false }()\n\t}\n\tbuf := new(bytes.Buffer)\n\tif err := GenMarkdown(echoCmd, buf); err != nil {\n\t\tt.Fatal(err)\n\t}\n\toutput := buf.String()\n\n\tcheckStringContains(t, output, echoCmd.Long)\n\tcheckStringContains(t, output, echoCmd.Example)\n\tcheckStringContains(t, output, \"boolone\")\n\tcheckStringOmits(t, output, \"rootflag\")\n\tcheckStringContains(t, output, rootCmd.Short)\n\tcheckStringContains(t, output, echoSubCmd.Short)\n\tcheckStringOmits(t, output, deprecatedCmd.Short)\n\tcheckStringOmits(t, output, \"Options inherited from parent commands\")\n}\n\nfunc TestGenMdNoTag(t *testing.T) {\n\trootCmd.DisableAutoGenTag = true\n\tdefer func() { rootCmd.DisableAutoGenTag = false }()\n\n\tbuf := new(bytes.Buffer)\n\tif err := GenMarkdown(rootCmd, buf); err != nil {\n\t\tt.Fatal(err)\n\t}\n\toutput := buf.String()\n\n\tcheckStringOmits(t, output, \"Auto generated\")\n}\n\nfunc TestGenMdTree(t *testing.T) {\n\tc := &cobra.Command{Use: \"do [OPTIONS] arg1 arg2\"}\n\ttmpdir, err := os.MkdirTemp(\"\", \"test-gen-md-tree\")\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create tmpdir: %v\", err)\n\t}\n\tdefer os.RemoveAll(tmpdir)\n\n\tif err := GenMarkdownTree(c, tmpdir); err != nil {\n\t\tt.Fatalf(\"GenMarkdownTree failed: %v\", err)\n\t}\n\n\tif _, err := os.Stat(filepath.Join(tmpdir, \"do.md\")); err != nil {\n\t\tt.Fatalf(\"Expected file 'do.md' to exist\")\n\t}\n}\n\nfunc BenchmarkGenMarkdownToFile(b *testing.B) {\n\tfile, err := os.CreateTemp(\"\", \"\")\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\tdefer os.Remove(file.Name())\n\tdefer file.Close()\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tif err := GenMarkdown(rootCmd, file); err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "doc/rest_docs.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage doc\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nfunc printOptionsReST(buf *bytes.Buffer, cmd *cobra.Command, name string) error {\n\tflags := cmd.NonInheritedFlags()\n\tflags.SetOutput(buf)\n\tif flags.HasAvailableFlags() {\n\t\tbuf.WriteString(\"Options\\n\")\n\t\tbuf.WriteString(\"~~~~~~~\\n\\n::\\n\\n\")\n\t\tflags.PrintDefaults()\n\t\tbuf.WriteString(\"\\n\")\n\t}\n\n\tparentFlags := cmd.InheritedFlags()\n\tparentFlags.SetOutput(buf)\n\tif parentFlags.HasAvailableFlags() {\n\t\tbuf.WriteString(\"Options inherited from parent commands\\n\")\n\t\tbuf.WriteString(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\\n::\\n\\n\")\n\t\tparentFlags.PrintDefaults()\n\t\tbuf.WriteString(\"\\n\")\n\t}\n\treturn nil\n}\n\n// defaultLinkHandler for default ReST hyperlink markup\nfunc defaultLinkHandler(name, ref string) string {\n\treturn fmt.Sprintf(\"`%s <%s.rst>`_\", name, ref)\n}\n\n// GenReST creates reStructured Text output.\nfunc GenReST(cmd *cobra.Command, w io.Writer) error {\n\treturn GenReSTCustom(cmd, w, defaultLinkHandler)\n}\n\n// GenReSTCustom creates custom reStructured Text output.\nfunc GenReSTCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string, string) string) error {\n\tcmd.InitDefaultHelpCmd()\n\tcmd.InitDefaultHelpFlag()\n\n\tbuf := new(bytes.Buffer)\n\tname := cmd.CommandPath()\n\n\tshort := cmd.Short\n\tlong := cmd.Long\n\tif len(long) == 0 {\n\t\tlong = short\n\t}\n\tref := strings.ReplaceAll(name, \" \", \"_\")\n\n\tbuf.WriteString(\".. _\" + ref + \":\\n\\n\")\n\tbuf.WriteString(name + \"\\n\")\n\tbuf.WriteString(strings.Repeat(\"-\", len(name)) + \"\\n\\n\")\n\tbuf.WriteString(short + \"\\n\\n\")\n\tbuf.WriteString(\"Synopsis\\n\")\n\tbuf.WriteString(\"~~~~~~~~\\n\\n\")\n\tbuf.WriteString(\"\\n\" + long + \"\\n\\n\")\n\n\tif cmd.Runnable() {\n\t\tfmt.Fprintf(buf, \"::\\n\\n  %s\\n\\n\", cmd.UseLine())\n\t}\n\n\tif len(cmd.Example) > 0 {\n\t\tbuf.WriteString(\"Examples\\n\")\n\t\tbuf.WriteString(\"~~~~~~~~\\n\\n\")\n\t\tfmt.Fprintf(buf, \"::\\n\\n%s\\n\\n\", indentString(cmd.Example, \"  \"))\n\t}\n\n\tif err := printOptionsReST(buf, cmd, name); err != nil {\n\t\treturn err\n\t}\n\tif hasSeeAlso(cmd) {\n\t\tbuf.WriteString(\"SEE ALSO\\n\")\n\t\tbuf.WriteString(\"~~~~~~~~\\n\\n\")\n\t\tif cmd.HasParent() {\n\t\t\tparent := cmd.Parent()\n\t\t\tpname := parent.CommandPath()\n\t\t\tref = strings.ReplaceAll(pname, \" \", \"_\")\n\t\t\tfmt.Fprintf(buf, \"* %s \\t - %s\\n\", linkHandler(pname, ref), parent.Short)\n\t\t\tcmd.VisitParents(func(c *cobra.Command) {\n\t\t\t\tif c.DisableAutoGenTag {\n\t\t\t\t\tcmd.DisableAutoGenTag = c.DisableAutoGenTag\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\n\t\tchildren := cmd.Commands()\n\t\tsort.Sort(byName(children))\n\n\t\tfor _, child := range children {\n\t\t\tif !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcname := name + \" \" + child.Name()\n\t\t\tref = strings.ReplaceAll(cname, \" \", \"_\")\n\t\t\tfmt.Fprintf(buf, \"* %s \\t - %s\\n\", linkHandler(cname, ref), child.Short)\n\t\t}\n\t\tbuf.WriteString(\"\\n\")\n\t}\n\tif !cmd.DisableAutoGenTag {\n\t\tbuf.WriteString(\"*Auto generated by spf13/cobra on \" + time.Now().Format(\"2-Jan-2006\") + \"*\\n\")\n\t}\n\t_, err := buf.WriteTo(w)\n\treturn err\n}\n\n// GenReSTTree will generate a ReST page for this command and all\n// descendants in the directory given.\n// This function may not work correctly if your command names have `-` in them.\n// If you have `cmd` with two subcmds, `sub` and `sub-third`,\n// and `sub` has a subcommand called `third`, it is undefined which\n// help output will be in the file `cmd-sub-third.1`.\nfunc GenReSTTree(cmd *cobra.Command, dir string) error {\n\temptyStr := func(s string) string { return \"\" }\n\treturn GenReSTTreeCustom(cmd, dir, emptyStr, defaultLinkHandler)\n}\n\n// GenReSTTreeCustom is the same as GenReSTTree, but\n// with custom filePrepender and linkHandler.\nfunc GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {\n\tfor _, c := range cmd.Commands() {\n\t\tif !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {\n\t\t\tcontinue\n\t\t}\n\t\tif err := GenReSTTreeCustom(c, dir, filePrepender, linkHandler); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tbasename := strings.ReplaceAll(cmd.CommandPath(), \" \", \"_\") + \".rst\"\n\tfilename := filepath.Join(dir, basename)\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tif _, err := io.WriteString(f, filePrepender(filename)); err != nil {\n\t\treturn err\n\t}\n\tif err := GenReSTCustom(cmd, f, linkHandler); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// indentString adapted from: https://github.com/kr/text/blob/main/indent.go\nfunc indentString(s, p string) string {\n\tvar res []byte\n\tb := []byte(s)\n\tprefix := []byte(p)\n\tbol := true\n\tfor _, c := range b {\n\t\tif bol && c != '\\n' {\n\t\t\tres = append(res, prefix...)\n\t\t}\n\t\tres = append(res, c)\n\t\tbol = c == '\\n'\n\t}\n\treturn string(res)\n}\n"
  },
  {
    "path": "doc/rest_docs_test.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage doc\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nfunc TestGenRSTDoc(t *testing.T) {\n\t// We generate on a subcommand so we have both subcommands and parents\n\tbuf := new(bytes.Buffer)\n\tif err := GenReST(echoCmd, buf); err != nil {\n\t\tt.Fatal(err)\n\t}\n\toutput := buf.String()\n\n\tcheckStringContains(t, output, echoCmd.Long)\n\tcheckStringContains(t, output, echoCmd.Example)\n\tcheckStringContains(t, output, \"boolone\")\n\tcheckStringContains(t, output, \"rootflag\")\n\tcheckStringContains(t, output, rootCmd.Short)\n\tcheckStringContains(t, output, echoSubCmd.Short)\n\tcheckStringOmits(t, output, deprecatedCmd.Short)\n}\n\nfunc TestGenRSTNoHiddenParents(t *testing.T) {\n\t// We generate on a subcommand so we have both subcommands and parents\n\tfor _, name := range []string{\"rootflag\", \"strtwo\"} {\n\t\tf := rootCmd.PersistentFlags().Lookup(name)\n\t\tf.Hidden = true\n\t\tdefer func() { f.Hidden = false }()\n\t}\n\tbuf := new(bytes.Buffer)\n\tif err := GenReST(echoCmd, buf); err != nil {\n\t\tt.Fatal(err)\n\t}\n\toutput := buf.String()\n\n\tcheckStringContains(t, output, echoCmd.Long)\n\tcheckStringContains(t, output, echoCmd.Example)\n\tcheckStringContains(t, output, \"boolone\")\n\tcheckStringOmits(t, output, \"rootflag\")\n\tcheckStringContains(t, output, rootCmd.Short)\n\tcheckStringContains(t, output, echoSubCmd.Short)\n\tcheckStringOmits(t, output, deprecatedCmd.Short)\n\tcheckStringOmits(t, output, \"Options inherited from parent commands\")\n}\n\nfunc TestGenRSTNoTag(t *testing.T) {\n\trootCmd.DisableAutoGenTag = true\n\tdefer func() { rootCmd.DisableAutoGenTag = false }()\n\n\tbuf := new(bytes.Buffer)\n\tif err := GenReST(rootCmd, buf); err != nil {\n\t\tt.Fatal(err)\n\t}\n\toutput := buf.String()\n\n\tunexpected := \"Auto generated\"\n\tcheckStringOmits(t, output, unexpected)\n}\n\nfunc TestGenRSTTree(t *testing.T) {\n\tc := &cobra.Command{Use: \"do [OPTIONS] arg1 arg2\"}\n\n\ttmpdir, err := os.MkdirTemp(\"\", \"test-gen-rst-tree\")\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create tmpdir: %s\", err.Error())\n\t}\n\tdefer os.RemoveAll(tmpdir)\n\n\tif err := GenReSTTree(c, tmpdir); err != nil {\n\t\tt.Fatalf(\"GenReSTTree failed: %s\", err.Error())\n\t}\n\n\tif _, err := os.Stat(filepath.Join(tmpdir, \"do.rst\")); err != nil {\n\t\tt.Fatalf(\"Expected file 'do.rst' to exist\")\n\t}\n}\n\nfunc BenchmarkGenReSTToFile(b *testing.B) {\n\tfile, err := os.CreateTemp(\"\", \"\")\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\tdefer os.Remove(file.Name())\n\tdefer file.Close()\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tif err := GenReST(rootCmd, file); err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "doc/util.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage doc\n\nimport (\n\t\"strings\"\n\n\t\"github.com/spf13/cobra\"\n)\n\n// Test to see if we have a reason to print See Also information in docs\n// Basically this is a test for a parent command or a subcommand which is\n// both not deprecated and not the autogenerated help command.\nfunc hasSeeAlso(cmd *cobra.Command) bool {\n\tif cmd.HasParent() {\n\t\treturn true\n\t}\n\tfor _, c := range cmd.Commands() {\n\t\tif !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {\n\t\t\tcontinue\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}\n\n// Temporary workaround for yaml lib generating incorrect yaml with long strings\n// that do not contain \\n.\nfunc forceMultiLine(s string) string {\n\tif len(s) > 60 && !strings.Contains(s, \"\\n\") {\n\t\ts += \"\\n\"\n\t}\n\treturn s\n}\n\ntype byName []*cobra.Command\n\nfunc (s byName) Len() int           { return len(s) }\nfunc (s byName) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }\nfunc (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() }\n"
  },
  {
    "path": "doc/yaml_docs.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage doc\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/pflag\"\n\t\"go.yaml.in/yaml/v3\"\n)\n\ntype cmdOption struct {\n\tName         string\n\tShorthand    string `yaml:\",omitempty\"`\n\tDefaultValue string `yaml:\"default_value,omitempty\"`\n\tUsage        string `yaml:\",omitempty\"`\n}\n\ntype cmdDoc struct {\n\tName             string\n\tSynopsis         string      `yaml:\",omitempty\"`\n\tDescription      string      `yaml:\",omitempty\"`\n\tUsage            string      `yaml:\",omitempty\"`\n\tOptions          []cmdOption `yaml:\",omitempty\"`\n\tInheritedOptions []cmdOption `yaml:\"inherited_options,omitempty\"`\n\tExample          string      `yaml:\",omitempty\"`\n\tSeeAlso          []string    `yaml:\"see_also,omitempty\"`\n}\n\n// GenYamlTree creates yaml structured ref files for this command and all descendants\n// in the directory given. This function may not work\n// correctly if your command names have `-` in them. If you have `cmd` with two\n// subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third`\n// it is undefined which help output will be in the file `cmd-sub-third.1`.\nfunc GenYamlTree(cmd *cobra.Command, dir string) error {\n\tidentity := func(s string) string { return s }\n\temptyStr := func(s string) string { return \"\" }\n\treturn GenYamlTreeCustom(cmd, dir, emptyStr, identity)\n}\n\n// GenYamlTreeCustom creates yaml structured ref files.\nfunc GenYamlTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {\n\tfor _, c := range cmd.Commands() {\n\t\tif !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {\n\t\t\tcontinue\n\t\t}\n\t\tif err := GenYamlTreeCustom(c, dir, filePrepender, linkHandler); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tbasename := strings.ReplaceAll(cmd.CommandPath(), \" \", \"_\") + \".yaml\"\n\tfilename := filepath.Join(dir, basename)\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tif _, err := io.WriteString(f, filePrepender(filename)); err != nil {\n\t\treturn err\n\t}\n\tif err := GenYamlCustom(cmd, f, linkHandler); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// GenYaml creates yaml output.\nfunc GenYaml(cmd *cobra.Command, w io.Writer) error {\n\treturn GenYamlCustom(cmd, w, func(s string) string { return s })\n}\n\n// GenYamlCustom creates custom yaml output.\nfunc GenYamlCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {\n\tcmd.InitDefaultHelpCmd()\n\tcmd.InitDefaultHelpFlag()\n\n\tyamlDoc := cmdDoc{}\n\tyamlDoc.Name = cmd.CommandPath()\n\n\tyamlDoc.Synopsis = forceMultiLine(cmd.Short)\n\tyamlDoc.Description = forceMultiLine(cmd.Long)\n\n\tif cmd.Runnable() {\n\t\tyamlDoc.Usage = cmd.UseLine()\n\t}\n\n\tif len(cmd.Example) > 0 {\n\t\tyamlDoc.Example = cmd.Example\n\t}\n\n\tflags := cmd.NonInheritedFlags()\n\tif flags.HasFlags() {\n\t\tyamlDoc.Options = genFlagResult(flags)\n\t}\n\tflags = cmd.InheritedFlags()\n\tif flags.HasFlags() {\n\t\tyamlDoc.InheritedOptions = genFlagResult(flags)\n\t}\n\n\tif hasSeeAlso(cmd) {\n\t\tresult := []string{}\n\t\tif cmd.HasParent() {\n\t\t\tparent := cmd.Parent()\n\t\t\tresult = append(result, parent.CommandPath()+\" - \"+parent.Short)\n\t\t}\n\t\tchildren := cmd.Commands()\n\t\tsort.Sort(byName(children))\n\t\tfor _, child := range children {\n\t\t\tif !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresult = append(result, child.CommandPath()+\" - \"+child.Short)\n\t\t}\n\t\tyamlDoc.SeeAlso = result\n\t}\n\n\tfinal, err := yaml.Marshal(&yamlDoc)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tif _, err := w.Write(final); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc genFlagResult(flags *pflag.FlagSet) []cmdOption {\n\tvar result []cmdOption\n\n\tflags.VisitAll(func(flag *pflag.Flag) {\n\t\t// Todo, when we mark a shorthand is deprecated, but specify an empty message.\n\t\t// The flag.ShorthandDeprecated is empty as the shorthand is deprecated.\n\t\t// Using len(flag.ShorthandDeprecated) > 0 can't handle this, others are ok.\n\t\tif len(flag.ShorthandDeprecated) == 0 && len(flag.Shorthand) > 0 {\n\t\t\topt := cmdOption{\n\t\t\t\tflag.Name,\n\t\t\t\tflag.Shorthand,\n\t\t\t\tflag.DefValue,\n\t\t\t\tforceMultiLine(flag.Usage),\n\t\t\t}\n\t\t\tresult = append(result, opt)\n\t\t} else {\n\t\t\topt := cmdOption{\n\t\t\t\tName:         flag.Name,\n\t\t\t\tDefaultValue: forceMultiLine(flag.DefValue),\n\t\t\t\tUsage:        forceMultiLine(flag.Usage),\n\t\t\t}\n\t\t\tresult = append(result, opt)\n\t\t}\n\t})\n\n\treturn result\n}\n"
  },
  {
    "path": "doc/yaml_docs_test.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage doc\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nfunc TestGenYamlDoc(t *testing.T) {\n\t// We generate on s subcommand so we have both subcommands and parents\n\tbuf := new(bytes.Buffer)\n\tif err := GenYaml(echoCmd, buf); err != nil {\n\t\tt.Fatal(err)\n\t}\n\toutput := buf.String()\n\n\tcheckStringContains(t, output, echoCmd.Long)\n\tcheckStringContains(t, output, echoCmd.Example)\n\tcheckStringContains(t, output, \"boolone\")\n\tcheckStringContains(t, output, \"rootflag\")\n\tcheckStringContains(t, output, rootCmd.Short)\n\tcheckStringContains(t, output, echoSubCmd.Short)\n\tcheckStringContains(t, output, fmt.Sprintf(\"- %s - %s\", echoSubCmd.CommandPath(), echoSubCmd.Short))\n}\n\nfunc TestGenYamlNoTag(t *testing.T) {\n\trootCmd.DisableAutoGenTag = true\n\tdefer func() { rootCmd.DisableAutoGenTag = false }()\n\n\tbuf := new(bytes.Buffer)\n\tif err := GenYaml(rootCmd, buf); err != nil {\n\t\tt.Fatal(err)\n\t}\n\toutput := buf.String()\n\n\tcheckStringOmits(t, output, \"Auto generated\")\n}\n\nfunc TestGenYamlTree(t *testing.T) {\n\tc := &cobra.Command{Use: \"do [OPTIONS] arg1 arg2\"}\n\n\ttmpdir, err := os.MkdirTemp(\"\", \"test-gen-yaml-tree\")\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create tmpdir: %s\", err.Error())\n\t}\n\tdefer os.RemoveAll(tmpdir)\n\n\tif err := GenYamlTree(c, tmpdir); err != nil {\n\t\tt.Fatalf(\"GenYamlTree failed: %s\", err.Error())\n\t}\n\n\tif _, err := os.Stat(filepath.Join(tmpdir, \"do.yaml\")); err != nil {\n\t\tt.Fatalf(\"Expected file 'do.yaml' to exist\")\n\t}\n}\n\nfunc TestGenYamlDocRunnable(t *testing.T) {\n\t// Testing a runnable command: should contain the \"usage\" field\n\tbuf := new(bytes.Buffer)\n\tif err := GenYaml(rootCmd, buf); err != nil {\n\t\tt.Fatal(err)\n\t}\n\toutput := buf.String()\n\n\tcheckStringContains(t, output, \"usage: \"+rootCmd.Use)\n}\n\nfunc BenchmarkGenYamlToFile(b *testing.B) {\n\tfile, err := os.CreateTemp(\"\", \"\")\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\tdefer os.Remove(file.Name())\n\tdefer file.Close()\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tif err := GenYaml(rootCmd, file); err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "fish_completions.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc genFishComp(buf io.StringWriter, name string, includeDesc bool) {\n\t// Variables should not contain a '-' or ':' character\n\tnameForVar := name\n\tnameForVar = strings.ReplaceAll(nameForVar, \"-\", \"_\")\n\tnameForVar = strings.ReplaceAll(nameForVar, \":\", \"_\")\n\n\tcompCmd := ShellCompRequestCmd\n\tif !includeDesc {\n\t\tcompCmd = ShellCompNoDescRequestCmd\n\t}\n\tWriteStringAndCheck(buf, fmt.Sprintf(\"# fish completion for %-36s -*- shell-script -*-\\n\", name))\n\tWriteStringAndCheck(buf, fmt.Sprintf(`\nfunction __%[1]s_debug\n    set -l file \"$BASH_COMP_DEBUG_FILE\"\n    if test -n \"$file\"\n        echo \"$argv\" >> $file\n    end\nend\n\nfunction __%[1]s_perform_completion\n    __%[1]s_debug \"Starting __%[1]s_perform_completion\"\n\n    # Extract all args except the last one\n    set -l args (commandline -opc)\n    # Extract the last arg and escape it in case it is a space or wildcard\n    set -l lastArg (string escape -- (commandline -ct))\n\n    __%[1]s_debug \"args: $args\"\n    __%[1]s_debug \"last arg: $lastArg\"\n\n    # Disable ActiveHelp which is not supported for fish shell\n    set -l requestComp \"%[10]s=0 $args[1] %[3]s $(string join ' ' -- (string escape -- $args[2..-1])) $lastArg\"\n\n    __%[1]s_debug \"Calling $requestComp\"\n    set -l results (eval $requestComp 2> /dev/null)\n\n    # Some programs may output extra empty lines after the directive.\n    # Let's ignore them or else it will break completion.\n    # Ref: https://github.com/spf13/cobra/issues/1279\n    for line in $results[-1..1]\n        if test (string trim -- $line) = \"\"\n            # Found an empty line, remove it\n            set results $results[1..-2]\n        else\n            # Found non-empty line, we have our proper output\n            break\n        end\n    end\n\n    set -l comps $results[1..-2]\n    set -l directiveLine $results[-1]\n\n    # For Fish, when completing a flag with an = (e.g., <program> -n=<TAB>)\n    # completions must be prefixed with the flag\n    set -l flagPrefix (string match -r -- '-.*=' \"$lastArg\")\n\n    __%[1]s_debug \"Comps: $comps\"\n    __%[1]s_debug \"DirectiveLine: $directiveLine\"\n    __%[1]s_debug \"flagPrefix: $flagPrefix\"\n\n    for comp in $comps\n        printf \"%%s%%s\\n\" \"$flagPrefix\" \"$comp\"\n    end\n\n    printf \"%%s\\n\" \"$directiveLine\"\nend\n\n# this function limits calls to __%[1]s_perform_completion, by caching the result behind $__%[1]s_perform_completion_once_result\nfunction __%[1]s_perform_completion_once\n    __%[1]s_debug \"Starting __%[1]s_perform_completion_once\"\n\n    if test -n \"$__%[1]s_perform_completion_once_result\"\n        __%[1]s_debug \"Seems like a valid result already exists, skipping __%[1]s_perform_completion\"\n        return 0\n    end\n\n    set --global __%[1]s_perform_completion_once_result (__%[1]s_perform_completion)\n    if test -z \"$__%[1]s_perform_completion_once_result\"\n        __%[1]s_debug \"No completions, probably due to a failure\"\n        return 1\n    end\n\n    __%[1]s_debug \"Performed completions and set __%[1]s_perform_completion_once_result\"\n    return 0\nend\n\n# this function is used to clear the $__%[1]s_perform_completion_once_result variable after completions are run\nfunction __%[1]s_clear_perform_completion_once_result\n    __%[1]s_debug \"\"\n    __%[1]s_debug \"========= clearing previously set __%[1]s_perform_completion_once_result variable ==========\"\n    set --erase __%[1]s_perform_completion_once_result\n    __%[1]s_debug \"Successfully erased the variable __%[1]s_perform_completion_once_result\"\nend\n\nfunction __%[1]s_requires_order_preservation\n    __%[1]s_debug \"\"\n    __%[1]s_debug \"========= checking if order preservation is required ==========\"\n\n    __%[1]s_perform_completion_once\n    if test -z \"$__%[1]s_perform_completion_once_result\"\n        __%[1]s_debug \"Error determining if order preservation is required\"\n        return 1\n    end\n\n    set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1])\n    __%[1]s_debug \"Directive is: $directive\"\n\n    set -l shellCompDirectiveKeepOrder %[9]d\n    set -l keeporder (math (math --scale 0 $directive / $shellCompDirectiveKeepOrder) %% 2)\n    __%[1]s_debug \"Keeporder is: $keeporder\"\n\n    if test $keeporder -ne 0\n        __%[1]s_debug \"This does require order preservation\"\n        return 0\n    end\n\n    __%[1]s_debug \"This doesn't require order preservation\"\n    return 1\nend\n\n\n# This function does two things:\n# - Obtain the completions and store them in the global __%[1]s_comp_results\n# - Return false if file completion should be performed\nfunction __%[1]s_prepare_completions\n    __%[1]s_debug \"\"\n    __%[1]s_debug \"========= starting completion logic ==========\"\n\n    # Start fresh\n    set --erase __%[1]s_comp_results\n\n    __%[1]s_perform_completion_once\n    __%[1]s_debug \"Completion results: $__%[1]s_perform_completion_once_result\"\n\n    if test -z \"$__%[1]s_perform_completion_once_result\"\n        __%[1]s_debug \"No completion, probably due to a failure\"\n        # Might as well do file completion, in case it helps\n        return 1\n    end\n\n    set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1])\n    set --global __%[1]s_comp_results $__%[1]s_perform_completion_once_result[1..-2]\n\n    __%[1]s_debug \"Completions are: $__%[1]s_comp_results\"\n    __%[1]s_debug \"Directive is: $directive\"\n\n    set -l shellCompDirectiveError %[4]d\n    set -l shellCompDirectiveNoSpace %[5]d\n    set -l shellCompDirectiveNoFileComp %[6]d\n    set -l shellCompDirectiveFilterFileExt %[7]d\n    set -l shellCompDirectiveFilterDirs %[8]d\n\n    if test -z \"$directive\"\n        set directive 0\n    end\n\n    set -l compErr (math (math --scale 0 $directive / $shellCompDirectiveError) %% 2)\n    if test $compErr -eq 1\n        __%[1]s_debug \"Received error directive: aborting.\"\n        # Might as well do file completion, in case it helps\n        return 1\n    end\n\n    set -l filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) %% 2)\n    set -l dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) %% 2)\n    if test $filefilter -eq 1; or test $dirfilter -eq 1\n        __%[1]s_debug \"File extension filtering or directory filtering not supported\"\n        # Do full file completion instead\n        return 1\n    end\n\n    set -l nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) %% 2)\n    set -l nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) %% 2)\n\n    __%[1]s_debug \"nospace: $nospace, nofiles: $nofiles\"\n\n    # If we want to prevent a space, or if file completion is NOT disabled,\n    # we need to count the number of valid completions.\n    # To do so, we will filter on prefix as the completions we have received\n    # may not already be filtered so as to allow fish to match on different\n    # criteria than the prefix.\n    if test $nospace -ne 0; or test $nofiles -eq 0\n        set -l prefix (commandline -t | string escape --style=regex)\n        __%[1]s_debug \"prefix: $prefix\"\n\n        set -l completions (string match -r -- \"^$prefix.*\" $__%[1]s_comp_results)\n        set --global __%[1]s_comp_results $completions\n        __%[1]s_debug \"Filtered completions are: $__%[1]s_comp_results\"\n\n        # Important not to quote the variable for count to work\n        set -l numComps (count $__%[1]s_comp_results)\n        __%[1]s_debug \"numComps: $numComps\"\n\n        if test $numComps -eq 1; and test $nospace -ne 0\n            # We must first split on \\t to get rid of the descriptions to be\n            # able to check what the actual completion will be.\n            # We don't need descriptions anyway since there is only a single\n            # real completion which the shell will expand immediately.\n            set -l split (string split --max 1 \\t $__%[1]s_comp_results[1])\n\n            # Fish won't add a space if the completion ends with any\n            # of the following characters: @=/:.,\n            set -l lastChar (string sub -s -1 -- $split)\n            if not string match -r -q \"[@=/:.,]\" -- \"$lastChar\"\n                # In other cases, to support the \"nospace\" directive we trick the shell\n                # by outputting an extra, longer completion.\n                __%[1]s_debug \"Adding second completion to perform nospace directive\"\n                set --global __%[1]s_comp_results $split[1] $split[1].\n                __%[1]s_debug \"Completions are now: $__%[1]s_comp_results\"\n            end\n        end\n\n        if test $numComps -eq 0; and test $nofiles -eq 0\n            # To be consistent with bash and zsh, we only trigger file\n            # completion when there are no other completions\n            __%[1]s_debug \"Requesting file completion\"\n            return 1\n        end\n    end\n\n    return 0\nend\n\n# Since Fish completions are only loaded once the user triggers them, we trigger them ourselves\n# so we can properly delete any completions provided by another script.\n# Only do this if the program can be found, or else fish may print some errors; besides,\n# the existing completions will only be loaded if the program can be found.\nif type -q \"%[2]s\"\n    # The space after the program name is essential to trigger completion for the program\n    # and not completion of the program name itself.\n    # Also, we use '> /dev/null 2>&1' since '&>' is not supported in older versions of fish.\n    complete --do-complete \"%[2]s \" > /dev/null 2>&1\nend\n\n# Remove any pre-existing completions for the program since we will be handling all of them.\ncomplete -c %[2]s -e\n\n# this will get called after the two calls below and clear the $__%[1]s_perform_completion_once_result global\ncomplete -c %[2]s -n '__%[1]s_clear_perform_completion_once_result'\n# The call to __%[1]s_prepare_completions will setup __%[1]s_comp_results\n# which provides the program's completion choices.\n# If this doesn't require order preservation, we don't use the -k flag\ncomplete -c %[2]s -n 'not __%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'\n# otherwise we use the -k flag\ncomplete -k -c %[2]s -n '__%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'\n`, nameForVar, name, compCmd,\n\t\tShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,\n\t\tShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name)))\n}\n\n// GenFishCompletion generates fish completion file and writes to the passed writer.\nfunc (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error {\n\tbuf := new(bytes.Buffer)\n\tgenFishComp(buf, c.Name(), includeDesc)\n\t_, err := buf.WriteTo(w)\n\treturn err\n}\n\n// GenFishCompletionFile generates fish completion file.\nfunc (c *Command) GenFishCompletionFile(filename string, includeDesc bool) error {\n\toutFile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer outFile.Close()\n\n\treturn c.GenFishCompletion(outFile, includeDesc)\n}\n"
  },
  {
    "path": "fish_completions_test.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n)\n\nfunc TestCompleteNoDesCmdInFishScript(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild := &Command{\n\t\tUse:               \"child\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun:               emptyRun,\n\t}\n\trootCmd.AddCommand(child)\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, false))\n\toutput := buf.String()\n\n\tcheck(t, output, ShellCompNoDescRequestCmd)\n}\n\nfunc TestCompleteCmdInFishScript(t *testing.T) {\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild := &Command{\n\t\tUse:               \"child\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun:               emptyRun,\n\t}\n\trootCmd.AddCommand(child)\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, true))\n\toutput := buf.String()\n\n\tcheck(t, output, ShellCompRequestCmd)\n\tcheckOmit(t, output, ShellCompNoDescRequestCmd)\n}\n\nfunc TestProgWithDash(t *testing.T) {\n\trootCmd := &Command{Use: \"root-dash\", Args: NoArgs, Run: emptyRun}\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, false))\n\toutput := buf.String()\n\n\t// Functions name should have replace the '-'\n\tcheck(t, output, \"__root_dash_perform_completion\")\n\tcheckOmit(t, output, \"__root-dash_perform_completion\")\n\n\t// The command name should not have replaced the '-'\n\tcheck(t, output, \"-c root-dash\")\n\tcheckOmit(t, output, \"-c root_dash\")\n}\n\nfunc TestProgWithColon(t *testing.T) {\n\trootCmd := &Command{Use: \"root:colon\", Args: NoArgs, Run: emptyRun}\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, rootCmd.GenFishCompletion(buf, false))\n\toutput := buf.String()\n\n\t// Functions name should have replace the ':'\n\tcheck(t, output, \"__root_colon_perform_completion\")\n\tcheckOmit(t, output, \"__root:colon_perform_completion\")\n\n\t// The command name should not have replaced the ':'\n\tcheck(t, output, \"-c root:colon\")\n\tcheckOmit(t, output, \"-c root_colon\")\n}\n\nfunc TestFishCompletionNoActiveHelp(t *testing.T) {\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, c.GenFishCompletion(buf, true))\n\toutput := buf.String()\n\n\t// check that active help is being disabled\n\tactiveHelpVar := activeHelpEnvVar(c.Name())\n\tcheck(t, output, fmt.Sprintf(\"%s=0\", activeHelpVar))\n}\n\nfunc TestGenFishCompletionFile(t *testing.T) {\n\ttmpFile, err := os.CreateTemp(\"\", \"cobra-test\")\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\n\tdefer os.Remove(tmpFile.Name())\n\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild := &Command{\n\t\tUse:               \"child\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun:               emptyRun,\n\t}\n\trootCmd.AddCommand(child)\n\n\tassertNoErr(t, rootCmd.GenFishCompletionFile(tmpFile.Name(), false))\n}\n\nfunc TestFailGenFishCompletionFile(t *testing.T) {\n\ttmpDir, err := os.MkdirTemp(\"\", \"cobra-test\")\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\n\tdefer os.RemoveAll(tmpDir)\n\n\tf, _ := os.OpenFile(filepath.Join(tmpDir, \"test\"), os.O_CREATE, 0400)\n\tdefer f.Close()\n\n\trootCmd := &Command{Use: \"root\", Args: NoArgs, Run: emptyRun}\n\tchild := &Command{\n\t\tUse:               \"child\",\n\t\tValidArgsFunction: validArgsFunc,\n\t\tRun:               emptyRun,\n\t}\n\trootCmd.AddCommand(child)\n\n\tgot := rootCmd.GenFishCompletionFile(f.Name(), false)\n\tif !errors.Is(got, os.ErrPermission) {\n\t\tt.Errorf(\"got: %s, want: %s\", got.Error(), os.ErrPermission.Error())\n\t}\n}\n"
  },
  {
    "path": "flag_groups.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\n\tflag \"github.com/spf13/pflag\"\n)\n\nconst (\n\trequiredAsGroupAnnotation   = \"cobra_annotation_required_if_others_set\"\n\toneRequiredAnnotation       = \"cobra_annotation_one_required\"\n\tmutuallyExclusiveAnnotation = \"cobra_annotation_mutually_exclusive\"\n)\n\n// MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors\n// if the command is invoked with a subset (but not all) of the given flags.\nfunc (c *Command) MarkFlagsRequiredTogether(flagNames ...string) {\n\tc.mergePersistentFlags()\n\tfor _, v := range flagNames {\n\t\tf := c.Flags().Lookup(v)\n\t\tif f == nil {\n\t\t\tpanic(fmt.Sprintf(\"Failed to find flag %q and mark it as being required in a flag group\", v))\n\t\t}\n\t\tif err := c.Flags().SetAnnotation(v, requiredAsGroupAnnotation, append(f.Annotations[requiredAsGroupAnnotation], strings.Join(flagNames, \" \"))); err != nil {\n\t\t\t// Only errs if the flag isn't found.\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\n// MarkFlagsOneRequired marks the given flags with annotations so that Cobra errors\n// if the command is invoked without at least one flag from the given set of flags.\nfunc (c *Command) MarkFlagsOneRequired(flagNames ...string) {\n\tc.mergePersistentFlags()\n\tfor _, v := range flagNames {\n\t\tf := c.Flags().Lookup(v)\n\t\tif f == nil {\n\t\t\tpanic(fmt.Sprintf(\"Failed to find flag %q and mark it as being in a one-required flag group\", v))\n\t\t}\n\t\tif err := c.Flags().SetAnnotation(v, oneRequiredAnnotation, append(f.Annotations[oneRequiredAnnotation], strings.Join(flagNames, \" \"))); err != nil {\n\t\t\t// Only errs if the flag isn't found.\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\n// MarkFlagsMutuallyExclusive marks the given flags with annotations so that Cobra errors\n// if the command is invoked with more than one flag from the given set of flags.\nfunc (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) {\n\tc.mergePersistentFlags()\n\tfor _, v := range flagNames {\n\t\tf := c.Flags().Lookup(v)\n\t\tif f == nil {\n\t\t\tpanic(fmt.Sprintf(\"Failed to find flag %q and mark it as being in a mutually exclusive flag group\", v))\n\t\t}\n\t\t// Each time this is called is a single new entry; this allows it to be a member of multiple groups if needed.\n\t\tif err := c.Flags().SetAnnotation(v, mutuallyExclusiveAnnotation, append(f.Annotations[mutuallyExclusiveAnnotation], strings.Join(flagNames, \" \"))); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\n// ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the\n// first error encountered.\nfunc (c *Command) ValidateFlagGroups() error {\n\tif c.DisableFlagParsing {\n\t\treturn nil\n\t}\n\n\tflags := c.Flags()\n\n\t// groupStatus format is the list of flags as a unique ID,\n\t// then a map of each flag name and whether it is set or not.\n\tgroupStatus := map[string]map[string]bool{}\n\toneRequiredGroupStatus := map[string]map[string]bool{}\n\tmutuallyExclusiveGroupStatus := map[string]map[string]bool{}\n\tflags.VisitAll(func(pflag *flag.Flag) {\n\t\tprocessFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus)\n\t\tprocessFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus)\n\t\tprocessFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus)\n\t})\n\n\tif err := validateRequiredFlagGroups(groupStatus); err != nil {\n\t\treturn err\n\t}\n\tif err := validateOneRequiredFlagGroups(oneRequiredGroupStatus); err != nil {\n\t\treturn err\n\t}\n\tif err := validateExclusiveFlagGroups(mutuallyExclusiveGroupStatus); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc hasAllFlags(fs *flag.FlagSet, flagnames ...string) bool {\n\tfor _, fname := range flagnames {\n\t\tf := fs.Lookup(fname)\n\t\tif f == nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc processFlagForGroupAnnotation(flags *flag.FlagSet, pflag *flag.Flag, annotation string, groupStatus map[string]map[string]bool) {\n\tgroupInfo, found := pflag.Annotations[annotation]\n\tif found {\n\t\tfor _, group := range groupInfo {\n\t\t\tif groupStatus[group] == nil {\n\t\t\t\tflagnames := strings.Split(group, \" \")\n\n\t\t\t\t// Only consider this flag group at all if all the flags are defined.\n\t\t\t\tif !hasAllFlags(flags, flagnames...) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tgroupStatus[group] = make(map[string]bool, len(flagnames))\n\t\t\t\tfor _, name := range flagnames {\n\t\t\t\t\tgroupStatus[group][name] = false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgroupStatus[group][pflag.Name] = pflag.Changed\n\t\t}\n\t}\n}\n\nfunc validateRequiredFlagGroups(data map[string]map[string]bool) error {\n\tkeys := sortedKeys(data)\n\tfor _, flagList := range keys {\n\t\tflagnameAndStatus := data[flagList]\n\n\t\tunset := []string{}\n\t\tfor flagname, isSet := range flagnameAndStatus {\n\t\t\tif !isSet {\n\t\t\t\tunset = append(unset, flagname)\n\t\t\t}\n\t\t}\n\t\tif len(unset) == len(flagnameAndStatus) || len(unset) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Sort values, so they can be tested/scripted against consistently.\n\t\tsort.Strings(unset)\n\t\treturn fmt.Errorf(\"if any flags in the group [%v] are set they must all be set; missing %v\", flagList, unset)\n\t}\n\n\treturn nil\n}\n\nfunc validateOneRequiredFlagGroups(data map[string]map[string]bool) error {\n\tkeys := sortedKeys(data)\n\tfor _, flagList := range keys {\n\t\tflagnameAndStatus := data[flagList]\n\t\tvar set []string\n\t\tfor flagname, isSet := range flagnameAndStatus {\n\t\t\tif isSet {\n\t\t\t\tset = append(set, flagname)\n\t\t\t}\n\t\t}\n\t\tif len(set) >= 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Sort values, so they can be tested/scripted against consistently.\n\t\tsort.Strings(set)\n\t\treturn fmt.Errorf(\"at least one of the flags in the group [%v] is required\", flagList)\n\t}\n\treturn nil\n}\n\nfunc validateExclusiveFlagGroups(data map[string]map[string]bool) error {\n\tkeys := sortedKeys(data)\n\tfor _, flagList := range keys {\n\t\tflagnameAndStatus := data[flagList]\n\t\tvar set []string\n\t\tfor flagname, isSet := range flagnameAndStatus {\n\t\t\tif isSet {\n\t\t\t\tset = append(set, flagname)\n\t\t\t}\n\t\t}\n\t\tif len(set) == 0 || len(set) == 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Sort values, so they can be tested/scripted against consistently.\n\t\tsort.Strings(set)\n\t\treturn fmt.Errorf(\"if any flags in the group [%v] are set none of the others can be; %v were all set\", flagList, set)\n\t}\n\treturn nil\n}\n\nfunc sortedKeys(m map[string]map[string]bool) []string {\n\tkeys := make([]string, len(m))\n\ti := 0\n\tfor k := range m {\n\t\tkeys[i] = k\n\t\ti++\n\t}\n\tsort.Strings(keys)\n\treturn keys\n}\n\n// enforceFlagGroupsForCompletion will do the following:\n// - when a flag in a group is present, other flags in the group will be marked required\n// - when none of the flags in a one-required group are present, all flags in the group will be marked required\n// - when a flag in a mutually exclusive group is present, other flags in the group will be marked as hidden\n// This allows the standard completion logic to behave appropriately for flag groups\nfunc (c *Command) enforceFlagGroupsForCompletion() {\n\tif c.DisableFlagParsing {\n\t\treturn\n\t}\n\n\tflags := c.Flags()\n\tgroupStatus := map[string]map[string]bool{}\n\toneRequiredGroupStatus := map[string]map[string]bool{}\n\tmutuallyExclusiveGroupStatus := map[string]map[string]bool{}\n\tc.Flags().VisitAll(func(pflag *flag.Flag) {\n\t\tprocessFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus)\n\t\tprocessFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus)\n\t\tprocessFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus)\n\t})\n\n\t// If a flag that is part of a group is present, we make all the other flags\n\t// of that group required so that the shell completion suggests them automatically\n\tfor flagList, flagnameAndStatus := range groupStatus {\n\t\tfor _, isSet := range flagnameAndStatus {\n\t\t\tif isSet {\n\t\t\t\t// One of the flags of the group is set, mark the other ones as required\n\t\t\t\tfor _, fName := range strings.Split(flagList, \" \") {\n\t\t\t\t\t_ = c.MarkFlagRequired(fName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// If none of the flags of a one-required group are present, we make all the flags\n\t// of that group required so that the shell completion suggests them automatically\n\tfor flagList, flagnameAndStatus := range oneRequiredGroupStatus {\n\t\tisSet := false\n\n\t\tfor _, isSet = range flagnameAndStatus {\n\t\t\tif isSet {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// None of the flags of the group are set, mark all flags in the group\n\t\t// as required\n\t\tif !isSet {\n\t\t\tfor _, fName := range strings.Split(flagList, \" \") {\n\t\t\t\t_ = c.MarkFlagRequired(fName)\n\t\t\t}\n\t\t}\n\t}\n\n\t// If a flag that is mutually exclusive to others is present, we hide the other\n\t// flags of that group so the shell completion does not suggest them\n\tfor flagList, flagnameAndStatus := range mutuallyExclusiveGroupStatus {\n\t\tfor flagName, isSet := range flagnameAndStatus {\n\t\t\tif isSet {\n\t\t\t\t// One of the flags of the mutually exclusive group is set, mark the other ones as hidden\n\t\t\t\t// Don't mark the flag that is already set as hidden because it may be an\n\t\t\t\t// array or slice flag and therefore must continue being suggested\n\t\t\t\tfor _, fName := range strings.Split(flagList, \" \") {\n\t\t\t\t\tif fName != flagName {\n\t\t\t\t\t\tflag := c.Flags().Lookup(fName)\n\t\t\t\t\t\tflag.Hidden = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "flag_groups_test.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestValidateFlagGroups(t *testing.T) {\n\tgetCmd := func() *Command {\n\t\tc := &Command{\n\t\t\tUse: \"testcmd\",\n\t\t\tRun: func(cmd *Command, args []string) {\n\t\t\t}}\n\t\t// Define lots of flags to utilize for testing.\n\t\tfor _, v := range []string{\"a\", \"b\", \"c\", \"d\"} {\n\t\t\tc.Flags().String(v, \"\", \"\")\n\t\t}\n\t\tfor _, v := range []string{\"e\", \"f\", \"g\"} {\n\t\t\tc.PersistentFlags().String(v, \"\", \"\")\n\t\t}\n\t\tsubC := &Command{\n\t\t\tUse: \"subcmd\",\n\t\t\tRun: func(cmd *Command, args []string) {\n\t\t\t}}\n\t\tsubC.Flags().String(\"subonly\", \"\", \"\")\n\t\tc.AddCommand(subC)\n\t\treturn c\n\t}\n\n\t// Each test case uses a unique command from the function above.\n\ttestcases := []struct {\n\t\tdesc                        string\n\t\tflagGroupsRequired          []string\n\t\tflagGroupsOneRequired       []string\n\t\tflagGroupsExclusive         []string\n\t\tsubCmdFlagGroupsRequired    []string\n\t\tsubCmdFlagGroupsOneRequired []string\n\t\tsubCmdFlagGroupsExclusive   []string\n\t\targs                        []string\n\t\texpectErr                   string\n\t}{\n\t\t{\n\t\t\tdesc: \"No flags no problem\",\n\t\t}, {\n\t\t\tdesc:                \"No flags no problem even with conflicting groups\",\n\t\t\tflagGroupsRequired:  []string{\"a b\"},\n\t\t\tflagGroupsExclusive: []string{\"a b\"},\n\t\t}, {\n\t\t\tdesc:               \"Required flag group not satisfied\",\n\t\t\tflagGroupsRequired: []string{\"a b c\"},\n\t\t\targs:               []string{\"--a=foo\"},\n\t\t\texpectErr:          \"if any flags in the group [a b c] are set they must all be set; missing [b c]\",\n\t\t}, {\n\t\t\tdesc:                  \"One-required flag group not satisfied\",\n\t\t\tflagGroupsOneRequired: []string{\"a b\"},\n\t\t\targs:                  []string{\"--c=foo\"},\n\t\t\texpectErr:             \"at least one of the flags in the group [a b] is required\",\n\t\t}, {\n\t\t\tdesc:                \"Exclusive flag group not satisfied\",\n\t\t\tflagGroupsExclusive: []string{\"a b c\"},\n\t\t\targs:                []string{\"--a=foo\", \"--b=foo\"},\n\t\t\texpectErr:           \"if any flags in the group [a b c] are set none of the others can be; [a b] were all set\",\n\t\t}, {\n\t\t\tdesc:               \"Multiple required flag group not satisfied returns first error\",\n\t\t\tflagGroupsRequired: []string{\"a b c\", \"a d\"},\n\t\t\targs:               []string{\"--c=foo\", \"--d=foo\"},\n\t\t\texpectErr:          `if any flags in the group [a b c] are set they must all be set; missing [a b]`,\n\t\t}, {\n\t\t\tdesc:                  \"Multiple one-required flag group not satisfied returns first error\",\n\t\t\tflagGroupsOneRequired: []string{\"a b\", \"d e\"},\n\t\t\targs:                  []string{\"--c=foo\", \"--f=foo\"},\n\t\t\texpectErr:             `at least one of the flags in the group [a b] is required`,\n\t\t}, {\n\t\t\tdesc:                \"Multiple exclusive flag group not satisfied returns first error\",\n\t\t\tflagGroupsExclusive: []string{\"a b c\", \"a d\"},\n\t\t\targs:                []string{\"--a=foo\", \"--c=foo\", \"--d=foo\"},\n\t\t\texpectErr:           `if any flags in the group [a b c] are set none of the others can be; [a c] were all set`,\n\t\t}, {\n\t\t\tdesc:               \"Validation of required groups occurs on groups in sorted order\",\n\t\t\tflagGroupsRequired: []string{\"a d\", \"a b\", \"a c\"},\n\t\t\targs:               []string{\"--a=foo\"},\n\t\t\texpectErr:          `if any flags in the group [a b] are set they must all be set; missing [b]`,\n\t\t}, {\n\t\t\tdesc:                  \"Validation of one-required groups occurs on groups in sorted order\",\n\t\t\tflagGroupsOneRequired: []string{\"d e\", \"a b\", \"f g\"},\n\t\t\targs:                  []string{\"--c=foo\"},\n\t\t\texpectErr:             `at least one of the flags in the group [a b] is required`,\n\t\t}, {\n\t\t\tdesc:                \"Validation of exclusive groups occurs on groups in sorted order\",\n\t\t\tflagGroupsExclusive: []string{\"a d\", \"a b\", \"a c\"},\n\t\t\targs:                []string{\"--a=foo\", \"--b=foo\", \"--c=foo\"},\n\t\t\texpectErr:           `if any flags in the group [a b] are set none of the others can be; [a b] were all set`,\n\t\t}, {\n\t\t\tdesc:                \"Persistent flags utilize required and exclusive groups and can fail required groups\",\n\t\t\tflagGroupsRequired:  []string{\"a e\", \"e f\"},\n\t\t\tflagGroupsExclusive: []string{\"f g\"},\n\t\t\targs:                []string{\"--a=foo\", \"--f=foo\", \"--g=foo\"},\n\t\t\texpectErr:           `if any flags in the group [a e] are set they must all be set; missing [e]`,\n\t\t}, {\n\t\t\tdesc:                  \"Persistent flags utilize one-required and exclusive groups and can fail one-required groups\",\n\t\t\tflagGroupsOneRequired: []string{\"a b\", \"e f\"},\n\t\t\tflagGroupsExclusive:   []string{\"e f\"},\n\t\t\targs:                  []string{\"--e=foo\"},\n\t\t\texpectErr:             `at least one of the flags in the group [a b] is required`,\n\t\t}, {\n\t\t\tdesc:                \"Persistent flags utilize required and exclusive groups and can fail mutually exclusive groups\",\n\t\t\tflagGroupsRequired:  []string{\"a e\", \"e f\"},\n\t\t\tflagGroupsExclusive: []string{\"f g\"},\n\t\t\targs:                []string{\"--a=foo\", \"--e=foo\", \"--f=foo\", \"--g=foo\"},\n\t\t\texpectErr:           `if any flags in the group [f g] are set none of the others can be; [f g] were all set`,\n\t\t}, {\n\t\t\tdesc:                \"Persistent flags utilize required and exclusive groups and can pass\",\n\t\t\tflagGroupsRequired:  []string{\"a e\", \"e f\"},\n\t\t\tflagGroupsExclusive: []string{\"f g\"},\n\t\t\targs:                []string{\"--a=foo\", \"--e=foo\", \"--f=foo\"},\n\t\t}, {\n\t\t\tdesc:                  \"Persistent flags utilize one-required and exclusive groups and can pass\",\n\t\t\tflagGroupsOneRequired: []string{\"a e\", \"e f\"},\n\t\t\tflagGroupsExclusive:   []string{\"f g\"},\n\t\t\targs:                  []string{\"--a=foo\", \"--e=foo\", \"--f=foo\"},\n\t\t}, {\n\t\t\tdesc:                     \"Subcmds can use required groups using inherited flags\",\n\t\t\tsubCmdFlagGroupsRequired: []string{\"e subonly\"},\n\t\t\targs:                     []string{\"subcmd\", \"--e=foo\", \"--subonly=foo\"},\n\t\t}, {\n\t\t\tdesc:                        \"Subcmds can use one-required groups using inherited flags\",\n\t\t\tsubCmdFlagGroupsOneRequired: []string{\"e subonly\"},\n\t\t\targs:                        []string{\"subcmd\", \"--e=foo\", \"--subonly=foo\"},\n\t\t}, {\n\t\t\tdesc:                        \"Subcmds can use one-required groups using inherited flags and fail one-required groups\",\n\t\t\tsubCmdFlagGroupsOneRequired: []string{\"e subonly\"},\n\t\t\targs:                        []string{\"subcmd\"},\n\t\t\texpectErr:                   \"at least one of the flags in the group [e subonly] is required\",\n\t\t}, {\n\t\t\tdesc:                      \"Subcmds can use exclusive groups using inherited flags\",\n\t\t\tsubCmdFlagGroupsExclusive: []string{\"e subonly\"},\n\t\t\targs:                      []string{\"subcmd\", \"--e=foo\", \"--subonly=foo\"},\n\t\t\texpectErr:                 \"if any flags in the group [e subonly] are set none of the others can be; [e subonly] were all set\",\n\t\t}, {\n\t\t\tdesc:                      \"Subcmds can use exclusive groups using inherited flags and pass\",\n\t\t\tsubCmdFlagGroupsExclusive: []string{\"e subonly\"},\n\t\t\targs:                      []string{\"subcmd\", \"--e=foo\"},\n\t\t}, {\n\t\t\tdesc:                     \"Flag groups not applied if not found on invoked command\",\n\t\t\tsubCmdFlagGroupsRequired: []string{\"e subonly\"},\n\t\t\targs:                     []string{\"--e=foo\"},\n\t\t},\n\t}\n\tfor _, tc := range testcases {\n\t\tt.Run(tc.desc, func(t *testing.T) {\n\t\t\tc := getCmd()\n\t\t\tsub := c.Commands()[0]\n\t\t\tfor _, flagGroup := range tc.flagGroupsRequired {\n\t\t\t\tc.MarkFlagsRequiredTogether(strings.Split(flagGroup, \" \")...)\n\t\t\t}\n\t\t\tfor _, flagGroup := range tc.flagGroupsOneRequired {\n\t\t\t\tc.MarkFlagsOneRequired(strings.Split(flagGroup, \" \")...)\n\t\t\t}\n\t\t\tfor _, flagGroup := range tc.flagGroupsExclusive {\n\t\t\t\tc.MarkFlagsMutuallyExclusive(strings.Split(flagGroup, \" \")...)\n\t\t\t}\n\t\t\tfor _, flagGroup := range tc.subCmdFlagGroupsRequired {\n\t\t\t\tsub.MarkFlagsRequiredTogether(strings.Split(flagGroup, \" \")...)\n\t\t\t}\n\t\t\tfor _, flagGroup := range tc.subCmdFlagGroupsOneRequired {\n\t\t\t\tsub.MarkFlagsOneRequired(strings.Split(flagGroup, \" \")...)\n\t\t\t}\n\t\t\tfor _, flagGroup := range tc.subCmdFlagGroupsExclusive {\n\t\t\t\tsub.MarkFlagsMutuallyExclusive(strings.Split(flagGroup, \" \")...)\n\t\t\t}\n\t\t\tc.SetArgs(tc.args)\n\t\t\terr := c.Execute()\n\t\t\tswitch {\n\t\t\tcase err == nil && len(tc.expectErr) > 0:\n\t\t\t\tt.Errorf(\"Expected error %q but got nil\", tc.expectErr)\n\t\t\tcase err != nil && err.Error() != tc.expectErr:\n\t\t\t\tt.Errorf(\"Expected error %q but got %q\", tc.expectErr, err)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "go.mod",
    "content": "module github.com/spf13/cobra\n\ngo 1.15\n\nrequire (\n\tgithub.com/cpuguy83/go-md2man/v2 v2.0.6\n\tgithub.com/inconshreveable/mousetrap v1.1.0\n\tgithub.com/spf13/pflag v1.0.9\n\tgo.yaml.in/yaml/v3 v3.0.4\n)\n"
  },
  {
    "path": "go.sum",
    "content": "github.com/cpuguy83/go-md2man/v2 v2.0.6 h1:XJtiaUW6dEEqVuZiMTn1ldk455QWwEIsMIJlo5vtkx0=\ngithub.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=\ngithub.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=\ngithub.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=\ngithub.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=\ngithub.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=\ngithub.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=\ngithub.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\n"
  },
  {
    "path": "powershell_completions.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// The generated scripts require PowerShell v5.0+ (which comes Windows 10, but\n// can be downloaded separately for windows 7 or 8.1).\n\npackage cobra\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) {\n\t// Variables should not contain a '-' or ':' character\n\tnameForVar := name\n\tnameForVar = strings.ReplaceAll(nameForVar, \"-\", \"_\")\n\tnameForVar = strings.ReplaceAll(nameForVar, \":\", \"_\")\n\n\tcompCmd := ShellCompRequestCmd\n\tif !includeDesc {\n\t\tcompCmd = ShellCompNoDescRequestCmd\n\t}\n\tWriteStringAndCheck(buf, fmt.Sprintf(`# powershell completion for %-36[1]s -*- shell-script -*-\n\nfunction __%[1]s_debug {\n    if ($env:BASH_COMP_DEBUG_FILE) {\n        \"$args\" | Out-File -Append -FilePath \"$env:BASH_COMP_DEBUG_FILE\"\n    }\n}\n\nfilter __%[1]s_escapeStringWithSpecialChars {\n`+\"    $_ -replace '\\\\s|#|@|\\\\$|;|,|''|\\\\{|\\\\}|\\\\(|\\\\)|\\\"|`|\\\\||<|>|&','`$&'\"+`\n}\n\n[scriptblock]${__%[2]sCompleterBlock} = {\n    param(\n            $WordToComplete,\n            $CommandAst,\n            $CursorPosition\n        )\n\n    # Get the current command line and convert into a string\n    $Command = $CommandAst.CommandElements\n    $Command = \"$Command\"\n\n    __%[1]s_debug \"\"\n    __%[1]s_debug \"========= starting completion logic ==========\"\n    __%[1]s_debug \"WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition\"\n\n    # The user could have moved the cursor backwards on the command-line.\n    # We need to trigger completion from the $CursorPosition location, so we need\n    # to truncate the command-line ($Command) up to the $CursorPosition location.\n    # Make sure the $Command is longer then the $CursorPosition before we truncate.\n    # This happens because the $Command does not include the last space.\n    if ($Command.Length -gt $CursorPosition) {\n        $Command=$Command.Substring(0,$CursorPosition)\n    }\n    __%[1]s_debug \"Truncated command: $Command\"\n\n    $ShellCompDirectiveError=%[4]d\n    $ShellCompDirectiveNoSpace=%[5]d\n    $ShellCompDirectiveNoFileComp=%[6]d\n    $ShellCompDirectiveFilterFileExt=%[7]d\n    $ShellCompDirectiveFilterDirs=%[8]d\n    $ShellCompDirectiveKeepOrder=%[9]d\n\n    # Prepare the command to request completions for the program.\n    # Split the command at the first space to separate the program and arguments.\n    $Program,$Arguments = $Command.Split(\" \",2)\n\n    $RequestComp=\"$Program %[3]s $Arguments\"\n    __%[1]s_debug \"RequestComp: $RequestComp\"\n\n    # we cannot use $WordToComplete because it\n    # has the wrong values if the cursor was moved\n    # so use the last argument\n    if ($WordToComplete -ne \"\" ) {\n        $WordToComplete = $Arguments.Split(\" \")[-1]\n    }\n    __%[1]s_debug \"New WordToComplete: $WordToComplete\"\n\n\n    # Check for flag with equal sign\n    $IsEqualFlag = ($WordToComplete -Like \"--*=*\" )\n    if ( $IsEqualFlag ) {\n        __%[1]s_debug \"Completing equal sign flag\"\n        # Remove the flag part\n        $Flag,$WordToComplete = $WordToComplete.Split(\"=\",2)\n    }\n\n    if ( $WordToComplete -eq \"\" -And ( -Not $IsEqualFlag )) {\n        # If the last parameter is complete (there is a space following it)\n        # We add an extra empty parameter so we can indicate this to the go method.\n        __%[1]s_debug \"Adding extra empty parameter\"\n        # PowerShell 7.2+ changed the way how the arguments are passed to executables,\n        # so for pre-7.2 or when Legacy argument passing is enabled we need to use\n`+\"        # `\\\"`\\\" to pass an empty argument, a \\\"\\\" or '' does not work!!!\"+`\n        if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or\n            ($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled(\"PSNativeCommandArgumentPassing\")) -or\n            (($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled(\"PSNativeCommandArgumentPassing\")) -and\n              $PSNativeCommandArgumentPassing -eq 'Legacy')) {\n`+\"             $RequestComp=\\\"$RequestComp\\\" + ' `\\\"`\\\"'\"+`\n        } else {\n             $RequestComp=\"$RequestComp\" + ' \"\"'\n        }\n    }\n\n    __%[1]s_debug \"Calling $RequestComp\"\n    # First disable ActiveHelp which is not supported for Powershell\n    ${env:%[10]s}=0\n\n    #call the command store the output in $out and redirect stderr and stdout to null\n    # $Out is an array contains each line per element\n    Invoke-Expression -OutVariable out \"$RequestComp\" 2>&1 | Out-Null\n\n    # get directive from last line\n    [int]$Directive = $Out[-1].TrimStart(':')\n    if ($Directive -eq \"\") {\n        # There is no directive specified\n        $Directive = 0\n    }\n    __%[1]s_debug \"The completion directive is: $Directive\"\n\n    # remove directive (last element) from out\n    $Out = $Out | Where-Object { $_ -ne $Out[-1] }\n    __%[1]s_debug \"The completions are: $Out\"\n\n    if (($Directive -band $ShellCompDirectiveError) -ne 0 ) {\n        # Error code.  No completion.\n        __%[1]s_debug \"Received error from custom completion go code\"\n        return\n    }\n\n    $Longest = 0\n    [Array]$Values = $Out | ForEach-Object {\n        #Split the output in name and description\n`+\"        $Name, $Description = $_.Split(\\\"`t\\\",2)\"+`\n        __%[1]s_debug \"Name: $Name Description: $Description\"\n\n        # Look for the longest completion so that we can format things nicely\n        if ($Longest -lt $Name.Length) {\n            $Longest = $Name.Length\n        }\n\n        # Set the description to a one space string if there is none set.\n        # This is needed because the CompletionResult does not accept an empty string as argument\n        if (-Not $Description) {\n            $Description = \" \"\n        }\n        New-Object -TypeName PSCustomObject -Property @{\n            Name = \"$Name\"\n            Description = \"$Description\"\n        }\n    }\n\n\n    $Space = \" \"\n    if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) {\n        # remove the space here\n        __%[1]s_debug \"ShellCompDirectiveNoSpace is called\"\n        $Space = \"\"\n    }\n\n    if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or\n       (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 ))  {\n        __%[1]s_debug \"ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported\"\n\n        # return here to prevent the completion of the extensions\n        return\n    }\n\n    $Values = $Values | Where-Object {\n        # filter the result\n        $_.Name -like \"$WordToComplete*\"\n\n        # Join the flag back if we have an equal sign flag\n        if ( $IsEqualFlag ) {\n            __%[1]s_debug \"Join the equal sign flag back to the completion value\"\n            $_.Name = $Flag + \"=\" + $_.Name\n        }\n    }\n\n    # we sort the values in ascending order by name if keep order isn't passed\n    if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) {\n        $Values = $Values | Sort-Object -Property Name\n    }\n\n    if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {\n        __%[1]s_debug \"ShellCompDirectiveNoFileComp is called\"\n\n        if ($Values.Length -eq 0) {\n            # Just print an empty string here so the\n            # shell does not start to complete paths.\n            # We cannot use CompletionResult here because\n            # it does not accept an empty string as argument.\n            \"\"\n            return\n        }\n    }\n\n    # Get the current mode\n    $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq \"Tab\" }).Function\n    __%[1]s_debug \"Mode: $Mode\"\n\n    $Values | ForEach-Object {\n\n        # store temporary because switch will overwrite $_\n        $comp = $_\n\n        # PowerShell supports three different completion modes\n        # - TabCompleteNext (default windows style - on each key press the next option is displayed)\n        # - Complete (works like bash)\n        # - MenuComplete (works like zsh)\n        # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function <mode>\n\n        # CompletionResult Arguments:\n        # 1) CompletionText text to be used as the auto completion result\n        # 2) ListItemText   text to be displayed in the suggestion list\n        # 3) ResultType     type of completion result\n        # 4) ToolTip        text for the tooltip with details about the object\n\n        switch ($Mode) {\n\n            # bash like\n            \"Complete\" {\n\n                if ($Values.Length -eq 1) {\n                    __%[1]s_debug \"Only one completion left\"\n\n                    # insert space after value\n                    $CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space\n                    if ($ExecutionContext.SessionState.LanguageMode -eq \"FullLanguage\"){\n                        [System.Management.Automation.CompletionResult]::new($CompletionText, \"$($comp.Name)\", 'ParameterValue', \"$($comp.Description)\")\n                    } else {\n                        $CompletionText\n                    }\n\n                } else {\n                    # Add the proper number of spaces to align the descriptions\n                    while($comp.Name.Length -lt $Longest) {\n                        $comp.Name = $comp.Name + \" \"\n                    }\n\n                    # Check for empty description and only add parentheses if needed\n                    if ($($comp.Description) -eq \" \" ) {\n                        $Description = \"\"\n                    } else {\n                        $Description = \"  ($($comp.Description))\"\n                    }\n\n                    $CompletionText = \"$($comp.Name)$Description\"\n                    if ($ExecutionContext.SessionState.LanguageMode -eq \"FullLanguage\"){\n                        [System.Management.Automation.CompletionResult]::new($CompletionText, \"$($comp.Name)$Description\", 'ParameterValue', \"$($comp.Description)\")\n                    } else {\n                        $CompletionText\n                    }\n                }\n             }\n\n            # zsh like\n            \"MenuComplete\" {\n                # insert space after value\n                # MenuComplete will automatically show the ToolTip of\n                # the highlighted value at the bottom of the suggestions.\n\n                $CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space\n                if ($ExecutionContext.SessionState.LanguageMode -eq \"FullLanguage\"){\n                    [System.Management.Automation.CompletionResult]::new($CompletionText, \"$($comp.Name)\", 'ParameterValue', \"$($comp.Description)\")\n                } else {\n                    $CompletionText\n                }\n            }\n\n            # TabCompleteNext and in case we get something unknown\n            Default {\n                # Like MenuComplete but we don't want to add a space here because\n                # the user need to press space anyway to get the completion.\n                # Description will not be shown because that's not possible with TabCompleteNext\n\n                $CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars)\n                if ($ExecutionContext.SessionState.LanguageMode -eq \"FullLanguage\"){\n                    [System.Management.Automation.CompletionResult]::new($CompletionText, \"$($comp.Name)\", 'ParameterValue', \"$($comp.Description)\")\n                } else {\n                    $CompletionText\n                }\n            }\n        }\n\n    }\n}\n\nRegister-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock ${__%[2]sCompleterBlock}\n`, name, nameForVar, compCmd,\n\t\tShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,\n\t\tShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name)))\n}\n\nfunc (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error {\n\tbuf := new(bytes.Buffer)\n\tgenPowerShellComp(buf, c.Name(), includeDesc)\n\t_, err := buf.WriteTo(w)\n\treturn err\n}\n\nfunc (c *Command) genPowerShellCompletionFile(filename string, includeDesc bool) error {\n\toutFile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer outFile.Close()\n\n\treturn c.genPowerShellCompletion(outFile, includeDesc)\n}\n\n// GenPowerShellCompletionFile generates powershell completion file without descriptions.\nfunc (c *Command) GenPowerShellCompletionFile(filename string) error {\n\treturn c.genPowerShellCompletionFile(filename, false)\n}\n\n// GenPowerShellCompletion generates powershell completion file without descriptions\n// and writes it to the passed writer.\nfunc (c *Command) GenPowerShellCompletion(w io.Writer) error {\n\treturn c.genPowerShellCompletion(w, false)\n}\n\n// GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions.\nfunc (c *Command) GenPowerShellCompletionFileWithDesc(filename string) error {\n\treturn c.genPowerShellCompletionFile(filename, true)\n}\n\n// GenPowerShellCompletionWithDesc generates powershell completion file with descriptions\n// and writes it to the passed writer.\nfunc (c *Command) GenPowerShellCompletionWithDesc(w io.Writer) error {\n\treturn c.genPowerShellCompletion(w, true)\n}\n"
  },
  {
    "path": "powershell_completions_test.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestPwshCompletionNoActiveHelp(t *testing.T) {\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, c.GenPowerShellCompletion(buf))\n\toutput := buf.String()\n\n\t// check that active help is being disabled\n\tactiveHelpVar := activeHelpEnvVar(c.Name())\n\tcheck(t, output, fmt.Sprintf(\"${env:%s}=0\", activeHelpVar))\n}\n"
  },
  {
    "path": "shell_completions.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"github.com/spf13/pflag\"\n)\n\n// MarkFlagRequired instructs the various shell completion implementations to\n// prioritize the named flag when performing completion,\n// and causes your command to report an error if invoked without the flag.\nfunc (c *Command) MarkFlagRequired(name string) error {\n\treturn MarkFlagRequired(c.Flags(), name)\n}\n\n// MarkPersistentFlagRequired instructs the various shell completion implementations to\n// prioritize the named persistent flag when performing completion,\n// and causes your command to report an error if invoked without the flag.\nfunc (c *Command) MarkPersistentFlagRequired(name string) error {\n\treturn MarkFlagRequired(c.PersistentFlags(), name)\n}\n\n// MarkFlagRequired instructs the various shell completion implementations to\n// prioritize the named flag when performing completion,\n// and causes your command to report an error if invoked without the flag.\nfunc MarkFlagRequired(flags *pflag.FlagSet, name string) error {\n\treturn flags.SetAnnotation(name, BashCompOneRequiredFlag, []string{\"true\"})\n}\n\n// MarkFlagFilename instructs the various shell completion implementations to\n// limit completions for the named flag to the specified file extensions.\nfunc (c *Command) MarkFlagFilename(name string, extensions ...string) error {\n\treturn MarkFlagFilename(c.Flags(), name, extensions...)\n}\n\n// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists.\n// The bash completion script will call the bash function f for the flag.\n//\n// This will only work for bash completion.\n// It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows\n// to register a Go function which will work across all shells.\nfunc (c *Command) MarkFlagCustom(name string, f string) error {\n\treturn MarkFlagCustom(c.Flags(), name, f)\n}\n\n// MarkPersistentFlagFilename instructs the various shell completion\n// implementations to limit completions for the named persistent flag to the\n// specified file extensions.\nfunc (c *Command) MarkPersistentFlagFilename(name string, extensions ...string) error {\n\treturn MarkFlagFilename(c.PersistentFlags(), name, extensions...)\n}\n\n// MarkFlagFilename instructs the various shell completion implementations to\n// limit completions for the named flag to the specified file extensions.\nfunc MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error {\n\treturn flags.SetAnnotation(name, BashCompFilenameExt, extensions)\n}\n\n// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists.\n// The bash completion script will call the bash function f for the flag.\n//\n// This will only work for bash completion.\n// It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows\n// to register a Go function which will work across all shells.\nfunc MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error {\n\treturn flags.SetAnnotation(name, BashCompCustom, []string{f})\n}\n\n// MarkFlagDirname instructs the various shell completion implementations to\n// limit completions for the named flag to directory names.\nfunc (c *Command) MarkFlagDirname(name string) error {\n\treturn MarkFlagDirname(c.Flags(), name)\n}\n\n// MarkPersistentFlagDirname instructs the various shell completion\n// implementations to limit completions for the named persistent flag to\n// directory names.\nfunc (c *Command) MarkPersistentFlagDirname(name string) error {\n\treturn MarkFlagDirname(c.PersistentFlags(), name)\n}\n\n// MarkFlagDirname instructs the various shell completion implementations to\n// limit completions for the named flag to directory names.\nfunc MarkFlagDirname(flags *pflag.FlagSet, name string) error {\n\treturn flags.SetAnnotation(name, BashCompSubdirsInDir, []string{})\n}\n"
  },
  {
    "path": "site/content/active_help.md",
    "content": "# Active Help\n\nActive Help is a framework provided by Cobra which allows a program to define messages (hints, warnings, etc) that will be printed during program usage.  It aims to make it easier for your users to learn how to use your program.  If configured by the program, Active Help is printed when the user triggers shell completion.\n\nFor example,\n\n```console\n$ helm repo add [tab]\nYou must choose a name for the repo you are adding.\n\n$ bin/helm package [tab]\nPlease specify the path to the chart to package\n\n$ bin/helm package [tab][tab]\nbin/    internal/    scripts/    pkg/     testdata/\n```\n\n**Hint**: A good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions to guide the user in knowing what is expected by the program.\n\n## Supported shells\n\nActive Help is currently only supported for the following shells:\n- Bash (using [bash completion V2](completions/_index.md#bash-completion-v2) only). Note that bash 4.4 or higher is required for the prompt to appear when an Active Help message is printed.\n- Zsh\n\n## Adding Active Help messages\n\nAs Active Help uses the shell completion system, the implementation of Active Help messages is done by enhancing custom dynamic completions.  If you are not familiar with dynamic completions, please refer to [Shell Completions](completions/_index.md).\n\nAdding Active Help is done through the use of the `cobra.AppendActiveHelp(...)` function, where the program repeatedly adds Active Help messages to the list of completions.  Keep reading for details.\n\n### Active Help for nouns\n\nAdding Active Help when completing a noun is done within the `ValidArgsFunction(...)` of a command.  Please notice the use of `cobra.AppendActiveHelp(...)` in the following example:\n\n```go\ncmd := &cobra.Command{\n\tUse:   \"add [NAME] [URL]\",\n\tShort: \"add a chart repository\",\n\tArgs:  require.ExactArgs(2),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn addRepo(args)\n\t},\n\tValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {\n\t\tvar comps []cobra.Completion\n\t\tif len(args) == 0 {\n\t\t\tcomps = cobra.AppendActiveHelp(comps, \"You must choose a name for the repo you are adding\")\n\t\t} else if len(args) == 1 {\n\t\t\tcomps = cobra.AppendActiveHelp(comps, \"You must specify the URL for the repo you are adding\")\n\t\t} else {\n\t\t\tcomps = cobra.AppendActiveHelp(comps, \"This command does not take any more arguments\")\n\t\t}\n\t\treturn comps, cobra.ShellCompDirectiveNoFileComp\n\t},\n}\n```\n\nThe example above defines the completions (none, in this specific example) as well as the Active Help messages for the `helm repo add` command.  It yields the following behavior:\n\n```console\n$ helm repo add [tab]\nYou must choose a name for the repo you are adding\n\n$ helm repo add grafana [tab]\nYou must specify the URL for the repo you are adding\n\n$ helm repo add grafana https://grafana.github.io/helm-charts [tab]\nThis command does not take any more arguments\n```\n\n**Hint**: As can be seen in the above example, a good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions.\n\n### Active Help for flags\n\nProviding Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag.  For example:\n\n```go\n_ = cmd.RegisterFlagCompletionFunc(\"version\", func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {\n\t\tif len(args) != 2 {\n\t\t\treturn cobra.AppendActiveHelp(nil, \"You must first specify the chart to install before the --version flag can be completed\"), cobra.ShellCompDirectiveNoFileComp\n\t\t}\n\t\treturn compVersionFlag(args[1], toComplete)\n\t})\n```\nThe example above prints an Active Help message when not enough information was given by the user to complete the `--version` flag.\n\n```console\n$ bin/helm install myrelease --version 2.0.[tab]\nYou must first specify the chart to install before the --version flag can be completed\n\n$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab]\n2.0.1  2.0.2  2.0.3\n```\n\n## User control of Active Help\n\nYou may want to allow your users to disable Active Help or choose between different levels of Active Help.  It is entirely up to the program to define the type of configurability of Active Help that it wants to offer, if any.\nAllowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration.\n\nThe way to configure Active Help is to use the program's Active Help environment\nvariable.  That variable is named `<PROGRAM>_ACTIVE_HELP` where `<PROGRAM>` is the name of your \nprogram in uppercase with any non-ASCII-alphanumeric characters replaced by an `_`.  The variable should be set by the user to whatever\nActive Help configuration values are supported by the program.\n\nFor example, say `helm` has chosen to support three levels for Active Help: `on`, `off`, `local`.  Then a user\nwould set the desired behavior to `local` by doing `export HELM_ACTIVE_HELP=local` in their shell.\n\nFor simplicity, when in `cmd.ValidArgsFunction(...)` or a flag's completion function, the program should read the\nActive Help configuration using the `cobra.GetActiveHelpConfig(cmd)` function and select what Active Help messages\nshould or should not be added (instead of reading the environment variable directly).\n\nFor example:\n\n```go\nValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {\n\tactiveHelpLevel := cobra.GetActiveHelpConfig(cmd)\n\n\tvar comps []cobra.Completion\n\tif len(args) == 0 {\n\t\tif activeHelpLevel != \"off\"  {\n\t\t\tcomps = cobra.AppendActiveHelp(comps, \"You must choose a name for the repo you are adding\")\n\t\t}\n\t} else if len(args) == 1 {\n\t\tif activeHelpLevel != \"off\" {\n\t\t\tcomps = cobra.AppendActiveHelp(comps, \"You must specify the URL for the repo you are adding\")\n\t\t}\n\t} else {\n\t\tif activeHelpLevel == \"local\" {\n\t\t\tcomps = cobra.AppendActiveHelp(comps, \"This command does not take any more arguments\")\n\t\t}\n\t}\n\treturn comps, cobra.ShellCompDirectiveNoFileComp\n},\n```\n\n**Note 1**: If the `<PROGRAM>_ACTIVE_HELP` environment variable is set to the string \"0\", Cobra will automatically disable all Active Help output (even if some output was specified by the program using the `cobra.AppendActiveHelp(...)` function).  Using \"0\" can simplify your code in situations where you want to blindly disable Active Help without having to call `cobra.GetActiveHelpConfig(cmd)` explicitly.\n\n**Note 2**: If a user wants to disable Active Help for every single program based on Cobra, she can set the environment variable `COBRA_ACTIVE_HELP` to \"0\".  In this case `cobra.GetActiveHelpConfig(cmd)` will return \"0\" no matter what the variable `<PROGRAM>_ACTIVE_HELP` is set to.\n\n**Note 3**: If the user does not set `<PROGRAM>_ACTIVE_HELP` or `COBRA_ACTIVE_HELP` (which will be a common case), the default value for the Active Help configuration returned by `cobra.GetActiveHelpConfig(cmd)` will be the empty string. \n\n## Active Help with Cobra's default completion command\n\nCobra provides a default `completion` command for programs that wish to use it.\nWhen using the default `completion` command, Active Help is configurable in the same\nfashion as described above using environment variables.  You may wish to document this in more\ndetails for your users.\n\n## Debugging Active Help\n\nDebugging your Active Help code is done in the same way as debugging your dynamic completion code, which is with Cobra's hidden `__complete` command.  Please refer to [debugging shell completion](completions/_index.md#debugging) for details.\n\nWhen debugging with the `__complete` command, if you want to specify different Active Help configurations, you should use the active help environment variable.  That variable is named `<PROGRAM>_ACTIVE_HELP` where any non-ASCII-alphanumeric characters are replaced by an `_`.  For example, we can test deactivating some Active Help as shown below:\n\n```console\n$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h<ENTER>\nbitnami/haproxy\nbitnami/harbor\n_activeHelp_ WARNING: cannot re-use a name that is still in use\n:0\nCompletion ended with directive: ShellCompDirectiveDefault\n\n$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h<ENTER>\nbitnami/haproxy\nbitnami/harbor\n:0\nCompletion ended with directive: ShellCompDirectiveDefault\n```\n"
  },
  {
    "path": "site/content/completions/_index.md",
    "content": "# Generating shell completions\n\nCobra can generate shell completions for multiple shells.\nThe currently supported shells are:\n- Bash\n- Zsh\n- fish\n- PowerShell\n\nCobra will automatically provide your program with a fully functional `completion` command,\nsimilarly to how it provides the `help` command. If there are no other subcommands, the\ndefault `completion` command will be hidden, but still functional.\n\n## Creating your own completion command\n\nIf you do not wish to use the default `completion` command, you can choose to\nprovide your own, which will take precedence over the default one. (This also provides\nbackwards-compatibility with programs that already have their own `completion` command.)\n\nIf you are using the `cobra-cli` generator,\nwhich can be found at [spf13/cobra-cli](https://github.com/spf13/cobra-cli),\nyou can create a completion command by running\n\n```bash\ncobra-cli add completion\n```\nand then modifying the generated `cmd/completion.go` file to look something like this\n(writing the shell script to stdout allows the most flexible use):\n\n```go\nvar completionCmd = &cobra.Command{\n\tUse:   \"completion [bash|zsh|fish|powershell]\",\n\tShort: \"Generate completion script\",\n\tLong: fmt.Sprintf(`To load completions:\n\nBash:\n\n  $ source <(%[1]s completion bash)\n\n  # To load completions for each session, execute once:\n  # Linux:\n  $ %[1]s completion bash > /etc/bash_completion.d/%[1]s\n  # macOS:\n  $ %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s\n\nZsh:\n\n  # If shell completion is not already enabled in your environment,\n  # you will need to enable it.  You can execute the following once:\n\n  $ echo \"autoload -U compinit; compinit\" >> ~/.zshrc\n\n  # To load completions for each session, execute once:\n  $ %[1]s completion zsh > \"${fpath[1]}/_%[1]s\"\n\n  # You will need to start a new shell for this setup to take effect.\n\nfish:\n\n  $ %[1]s completion fish | source\n\n  # To load completions for each session, execute once:\n  $ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish\n\nPowerShell:\n\n  PS> %[1]s completion powershell | Out-String | Invoke-Expression\n\n  # To load completions for every new session, run:\n  PS> %[1]s completion powershell > %[1]s.ps1\n  # and source this file from your PowerShell profile.\n`,cmd.Root().Name()),\n\tDisableFlagsInUseLine: true,\n\tValidArgs:             []string{\"bash\", \"zsh\", \"fish\", \"powershell\"},\n\tArgs:                  cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tswitch args[0] {\n\t\tcase \"bash\":\n\t\t\tcmd.Root().GenBashCompletion(os.Stdout)\n\t\tcase \"zsh\":\n\t\t\tcmd.Root().GenZshCompletion(os.Stdout)\n\t\tcase \"fish\":\n\t\t\tcmd.Root().GenFishCompletion(os.Stdout, true)\n\t\tcase \"powershell\":\n\t\t\tcmd.Root().GenPowerShellCompletionWithDesc(os.Stdout)\n\t\t}\n\t},\n}\n```\n\n**Note:** The cobra generator may include messages printed to stdout, for example, if the config file is loaded; this will break the auto-completion script so must be removed.\n\n## Adapting the default completion command\n\nCobra provides a few options for the default `completion` command.  To configure such options you must set\nthe `CompletionOptions` field on the *root* command.\n\nTo tell Cobra *not* to provide the default `completion` command:\n```\nrootCmd.CompletionOptions.DisableDefaultCmd = true\n```\n\nTo tell Cobra to mark the default `completion` command as *hidden*:\n```\nrootCmd.CompletionOptions.HiddenDefaultCmd = true\n```\n\nTo tell Cobra *not* to provide the user with the `--no-descriptions` flag to the completion sub-commands:\n```\nrootCmd.CompletionOptions.DisableNoDescFlag = true\n```\n\nTo tell Cobra to completely disable descriptions for completions:\n```\nrootCmd.CompletionOptions.DisableDescriptions = true\n```\n\n# Customizing completions\n\nThe generated completion scripts will automatically handle completing commands and flags.  However, you can make your completions much more powerful by providing information to complete your program's nouns and flag values.\n\n## Completion of nouns\n\n### Static completion of nouns\n\nCobra allows you to provide a pre-defined list of completion choices for your nouns using the `ValidArgs` field.\nFor example, if you want `kubectl get [tab][tab]` to show a list of valid \"nouns\" you have to set them.\nSome simplified code from `kubectl get` looks like:\n\n```go\nvalidArgs = []string{ \"pod\", \"node\", \"service\", \"replicationcontroller\" }\n\ncmd := &cobra.Command{\n\tUse:     \"get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)\",\n\tShort:   \"Display one or many resources\",\n\tLong:    get_long,\n\tExample: get_example,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tcobra.CheckErr(RunGet(f, out, cmd, args))\n\t},\n\tValidArgs: validArgs,\n}\n```\n\nNotice we put the `ValidArgs` field on the `get` sub-command. Doing so will give results like:\n\n```bash\n$ kubectl get [tab][tab]\nnode   pod   replicationcontroller   service\n```\n\n#### Aliases for nouns\n\nIf your nouns have aliases, you can define them alongside `ValidArgs` using `ArgAliases`:\n\n```go\nargAliases = []string { \"pods\", \"nodes\", \"services\", \"svc\", \"replicationcontrollers\", \"rc\" }\n\ncmd := &cobra.Command{\n    ...\n\tValidArgs:  validArgs,\n\tArgAliases: argAliases\n}\n```\n\nThe aliases are shown to the user on tab completion only if no completions were found within sub-commands or `ValidArgs`.\n\n### Dynamic completion of nouns\n\nIn some cases it is not possible to provide a list of completions in advance.  Instead, the list of completions must be determined at execution-time. In a similar fashion as for static completions, you can use the `ValidArgsFunction` field to provide a Go function that Cobra will execute when it needs the list of completion choices for the nouns of a command.  Note that either `ValidArgs` or `ValidArgsFunction` can be used for a single cobra command, but not both.\nSimplified code from `helm status` looks like:\n\n```go\ncmd := &cobra.Command{\n\tUse:   \"status RELEASE_NAME\",\n\tShort: \"Display the status of the named release\",\n\tLong:  status_long,\n\tRunE: func(cmd *cobra.Command, args []string) {\n\t\tRunGet(args[0])\n\t},\n\tValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {\n\t\tif len(args) != 0 {\n\t\t\treturn nil, cobra.ShellCompDirectiveNoFileComp\n\t\t}\n\t\treturn getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp\n\t},\n}\n```\nWhere `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster.\nNotice we put the `ValidArgsFunction` on the `status` sub-command. Let's assume the Helm releases on the cluster are: `harbor`, `notary`, `rook` and `thanos` then this dynamic completion will give results like:\n\n```bash\n$ helm status [tab][tab]\nharbor notary rook thanos\n```\nYou may have noticed the use of `cobra.ShellCompDirective`.  These directives are bit fields allowing to control some shell completion behaviors for your particular completion.  You can combine them with the bit-or operator such as `cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp`\n```go\n// Indicates that the shell will perform its default behavior after completions\n// have been provided (this implies none of the other directives).\nShellCompDirectiveDefault\n\n// Indicates an error occurred and completions should be ignored.\nShellCompDirectiveError\n\n// Indicates that the shell should not add a space after the completion,\n// even if there is a single completion provided.\nShellCompDirectiveNoSpace\n\n// Indicates that the shell should not provide file completion even when\n// no completion is provided.\nShellCompDirectiveNoFileComp\n\n// Indicates that the returned completions should be used as file extension filters.\n// For example, to complete only files of the form *.json or *.yaml:\n//    return []cobra.Completion{\"yaml\", \"json\"}, cobra.ShellCompDirectiveFilterFileExt\n// For flags, using MarkFlagFilename() and MarkPersistentFlagFilename()\n// is a shortcut to using this directive explicitly.\n//\nShellCompDirectiveFilterFileExt\n\n// Indicates that only directory names should be provided in file completion.\n// For example:\n//    return nil, cobra.ShellCompDirectiveFilterDirs\n// For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly.\n//\n// To request directory names within another directory, the returned completions\n// should specify a single directory name within which to search. For example,\n// to complete directories within \"themes/\":\n//    return []cobra.Completion{\"themes\"}, cobra.ShellCompDirectiveFilterDirs\n//\nShellCompDirectiveFilterDirs\n\n// ShellCompDirectiveKeepOrder indicates that the shell should preserve the order\n// in which the completions are provided\nShellCompDirectiveKeepOrder\n```\n\n***Note***: When using the `ValidArgsFunction`, Cobra will call your registered function after having parsed all flags and arguments provided in the command-line.  You therefore don't need to do this parsing yourself.  For example, when a user calls `helm status --namespace my-rook-ns [tab][tab]`, Cobra will call your registered `ValidArgsFunction` after having parsed the `--namespace` flag, as it would have done when calling the `RunE` function.\n\n#### Debugging\n\nCobra achieves dynamic completion through the use of a hidden command called by the completion script.  To debug your Go completion code, you can call this hidden command directly:\n```bash\n$ helm __complete status har<ENTER>\nharbor\n:4\nCompletion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr\n```\n***Important:*** If the noun to complete is empty (when the user has not yet typed any letters of that noun), you must pass an empty parameter to the `__complete` command:\n```bash\n$ helm __complete status \"\"<ENTER>\nharbor\nnotary\nrook\nthanos\n:4\nCompletion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr\n```\nCalling the `__complete` command directly allows you to run the Go debugger to troubleshoot your code.  You can also add printouts to your code; Cobra provides the following functions to use for printouts in Go completion code:\n```go\n// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE\n// is set to a file path) and optionally prints to stderr.\ncobra.CompDebug(msg string, printToStdErr bool)\ncobra.CompDebugln(msg string, printToStdErr bool)\n\n// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE\n// is set to a file path) and to stderr.\ncobra.CompError(msg string)\ncobra.CompErrorln(msg string)\n```\n***Important:*** You should **not** leave traces that print directly to stdout in your completion code as they will be interpreted as completion choices by the completion script.  Instead, use the cobra-provided debugging traces functions mentioned above.\n\n## Completions for flags\n\n### Mark flags as required\n\nMost of the time completions will only show sub-commands. But if a flag is required to make a sub-command work, you probably want it to show up when the user types [tab][tab].  You can mark a flag as 'Required' like so:\n\n```go\ncmd.MarkFlagRequired(\"pod\")\ncmd.MarkFlagRequired(\"container\")\n```\n\nand you'll get something like\n\n```bash\n$ kubectl exec [tab][tab]\n-c            --container=  -p            --pod=\n```\n\n### Specify dynamic flag completion\n\nAs for nouns, Cobra provides a way of defining dynamic completion of flags.  To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function using the `command.RegisterFlagCompletionFunc()` function.\n\n```go\nflagName := \"output\"\ncmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {\n\treturn []cobra.Completion{\"json\", \"table\", \"yaml\"}, cobra.ShellCompDirectiveDefault\n})\n```\nNotice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated.  In our example this dynamic completion will give results like so:\n\n```bash\n$ helm status --output [tab][tab]\njson table yaml\n```\n\n#### Change the default ShellCompDirective\n\nWhen no completion function is registered for a leaf command or for a flag, Cobra will\nautomatically use `ShellCompDirectiveDefault`, which will invoke the shell's filename completion.\nThis implies that when file completion does not apply to a leaf command or to a flag (the command\nor flag does not operate on a filename), turning off file completion requires you to register a\ncompletion function for that command/flag.\nFor example:\n\n```go\ncmd.RegisterFlagCompletionFunc(\"flag-name\", cobra.NoFileCompletions)\n```\n\nIf you find that there are more situations where file completion should be turned off than\nwhen it is applicable, you can recursively change the default `ShellCompDirective` for a command\nand its subcommands to `ShellCompDirectiveNoFileComp`:\n\n```go\ncmd.CompletionOptions.SetDefaultShellCompDirective(ShellCompDirectiveNoFileComp)\n```\n\nIf doing so, keep in mind that you should instead register a completion function for leaf commands or\nflags where file completion is applicable. For example:\n\n```go\ncmd.RegisterFlagCompletionFunc(\"flag-name\", cobra.FixedCompletions(nil, ShellCompDirectiveDefault))\n```\n\nTo change the default directive for the entire program, set the DefaultShellCompDirective on the root command.\n\n#### Debugging\n\nYou can also easily debug your Go completion code for flags:\n```bash\n$ helm __complete status --output \"\"\njson\ntable\nyaml\n:4\nCompletion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr\n```\n***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script.  Instead, use the cobra-provided debugging traces functions mentioned further above.\n\n### Specify valid filename extensions for flags that take a filename\n\nTo limit completions of flag values to file names with certain extensions you can either use the different `MarkFlagFilename()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterFileExt`, like so:\n```go\nflagName := \"output\"\ncmd.MarkFlagFilename(flagName, \"yaml\", \"json\")\n```\nor\n```go\nflagName := \"output\"\ncmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {\n\treturn []cobra.Completion{\"yaml\", \"json\"}, cobra.ShellCompDirectiveFilterFileExt})\n```\n\n### Limit flag completions to directory names\n\nTo limit completions of flag values to directory names you can either use the `MarkFlagDirname()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs`, like so:\n```go\nflagName := \"output\"\ncmd.MarkFlagDirname(flagName)\n```\nor\n```go\nflagName := \"output\"\ncmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {\n\treturn nil, cobra.ShellCompDirectiveFilterDirs\n})\n```\nTo limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so:\n```go\nflagName := \"output\"\ncmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {\n\treturn []cobra.Completion{\"themes\"}, cobra.ShellCompDirectiveFilterDirs\n})\n```\n### Descriptions for completions\n\nCobra provides support for completion descriptions.  Such descriptions are supported for each shell\n(however, for bash, it is only available in the [completion V2 version](#bash-completion-v2)).\nFor commands and flags, Cobra will provide the descriptions automatically, based on usage information.\nFor example, using zsh:\n```\n$ helm s[tab]\nsearch  -- search for a keyword in charts\nshow    -- show information of a chart\nstatus  -- displays the status of the named release\n```\nwhile using fish:\n```\n$ helm s[tab]\nsearch  (search for a keyword in charts)  show  (show information of a chart)  status  (displays the status of the named release)\n```\n\nCobra allows you to add descriptions to your own completions.  Simply add the description text after each completion, following a `\\t` separator. Cobra provides the helper function `CompletionWithDesc(string, string)` to create a completion with a description. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`.  For example:\n```go\nValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {\n\treturn []cobra.Completion{\n\t\tcobra.CompletionWithDesc(\"harbor\", \"An image registry\"),\n\t\tcobra.CompletionWithDesc(\"thanos\", \"Long-term metrics\")\n\t\t}, cobra.ShellCompDirectiveNoFileComp\n}}\n```\nor\n```go\nValidArgs: []cobra.Completion{\n\tcobra.CompletionWithDesc(\"bash\", \"Completions for bash\"),\n\tcobra.CompletionWithDesc(\"zsh\", \"Completions for zsh\")\n\t}\n```\n\nIf you don't want to show descriptions in the completions, you can add `--no-descriptions` to the default `completion` command to disable them, like:\n\n```bash\n$ source <(helm completion bash)\n$ helm completion [tab][tab]\nbash        (generate autocompletion script for bash)        powershell  (generate autocompletion script for powershell)\nfish        (generate autocompletion script for fish)        zsh         (generate autocompletion script for zsh)\n\n$ source <(helm completion bash --no-descriptions)\n$ helm completion [tab][tab]\nbash        fish        powershell  zsh\n```\n\nSetting the `<PROGRAM>_COMPLETION_DESCRIPTIONS` environment variable (falling back to `COBRA_COMPLETION_DESCRIPTIONS` if empty or not set) to a [falsey value](https://pkg.go.dev/strconv#ParseBool) achieves the same. `<PROGRAM>` is the name of your program with all non-ASCII-alphanumeric characters replaced by `_`.\n\n## Bash completions\n\n### Dependencies\n\nThe bash completion script generated by Cobra requires the `bash_completion` package. You should update the help text of your completion command to show how to install the `bash_completion` package ([Kubectl docs](https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion))\n\n### Aliases\n\nYou can also configure `bash` aliases for your program and they will also support completions.\n\n```bash\nalias aliasname=origcommand\ncomplete -o default -F __start_origcommand aliasname\n\n# and now when you run `aliasname` completion will make\n# suggestions as it did for `origcommand`.\n\n$ aliasname <tab><tab>\ncompletion     firstcommand   secondcommand\n```\n### Bash legacy dynamic completions\n\nFor backward compatibility, Cobra still supports its bash legacy dynamic completion solution.\nPlease refer to [Bash Completions](bash.md) for details.\n\n### Bash completion V2\n\nCobra provides two versions for bash completion.  The original bash completion (which started it all!) can be used by calling\n`GenBashCompletion()` or `GenBashCompletionFile()`.\n\nA new V2 bash completion version is also available.  This version can be used by calling `GenBashCompletionV2()` or\n`GenBashCompletionFileV2()`.  The V2 version does **not** support the legacy dynamic completion\n(see [Bash Completions](bash.md)) but instead works only with the Go dynamic completion\nsolution described in this document.\nUnless your program already uses the legacy dynamic completion solution, it is recommended that you use the bash\ncompletion V2 solution which provides the following extra features:\n- Supports completion descriptions (like the other shells)\n- Small completion script of less than 300 lines (v1 generates scripts of thousands of lines; `kubectl` for example has a bash v1 completion script of over 13K lines)\n- Streamlined user experience thanks to a completion behavior aligned with the other shells\n\n`Bash` completion V2 supports descriptions for completions. When calling `GenBashCompletionV2()` or `GenBashCompletionFileV2()`\nyou must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra\nwill provide the description automatically based on usage information.  You can choose to make this option configurable by\nyour users.\n\n```\n# With descriptions\n$ helm s[tab][tab]\nsearch  (search for a keyword in charts)           status  (display the status of the named release)\nshow    (show information of a chart)\n\n# Without descriptions\n$ helm s[tab][tab]\nsearch  show  status\n```\n**Note**: Cobra's default `completion` command uses bash completion V2.  If for some reason you need to use bash completion V1, you will need to implement your own `completion` command.\n## Zsh completions\n\nCobra supports native zsh completion generated from the root `cobra.Command`.\nThe generated completion script should be put somewhere in your `$fpath` and be named\n`_<yourProgram>`.  You will need to start a new shell for the completions to become available.\n\nZsh supports descriptions for completions. Cobra will provide the description automatically,\nbased on usage information. Cobra provides a way to completely disable such descriptions by\nusing `GenZshCompletionNoDesc()` or `GenZshCompletionFileNoDesc()`. You can choose to make\nthis a configurable option to your users.\n```\n# With descriptions\n$ helm s[tab]\nsearch  -- search for a keyword in charts\nshow    -- show information of a chart\nstatus  -- displays the status of the named release\n\n# Without descriptions\n$ helm s[tab]\nsearch  show  status\n```\n*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`.\n\n### Limitations\n\n* Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `zsh` (including the use of the `BashCompCustom` flag annotation).\n  * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).\n* The function `MarkFlagCustom()` is not supported and will be ignored for `zsh`.\n  * You should instead use `RegisterFlagCompletionFunc()`.\n\n### Zsh completions standardization\n\nCobra 1.1 standardized its zsh completion support to align it with its other shell completions.  Although the API was kept backward-compatible, some small changes in behavior were introduced.\nPlease refer to [Zsh Completions](zsh.md) for details.\n\n## fish completions\n\nCobra supports native fish completions generated from the root `cobra.Command`.  You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information.  You can choose to make this option configurable by your users.\n```\n# With descriptions\n$ helm s[tab]\nsearch  (search for a keyword in charts)  show  (show information of a chart)  status  (displays the status of the named release)\n\n# Without descriptions\n$ helm s[tab]\nsearch  show  status\n```\n*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`.\n\n### Limitations\n\n* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `fish` (including the use of the `BashCompCustom` flag annotation).\n  * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).\n* The function `MarkFlagCustom()` is not supported and will be ignored for `fish`.\n  * You should instead use `RegisterFlagCompletionFunc()`.\n* The following flag completion annotations are not supported and will be ignored for `fish`:\n  * `BashCompFilenameExt` (filtering by file extension)\n  * `BashCompSubdirsInDir` (filtering by directory)\n* The functions corresponding to the above annotations are consequently not supported and will be ignored for `fish`:\n  * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension)\n  * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory)\n* Similarly, the following completion directives are not supported and will be ignored for `fish`:\n  * `ShellCompDirectiveFilterFileExt` (filtering by file extension)\n  * `ShellCompDirectiveFilterDirs` (filtering by directory)\n\n## PowerShell completions\n\nCobra supports native PowerShell completions generated from the root `cobra.Command`. You can use the `command.GenPowerShellCompletion()` or `command.GenPowerShellCompletionFile()` functions. To include descriptions use `command.GenPowerShellCompletionWithDesc()` and `command.GenPowerShellCompletionFileWithDesc()`. Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.\n\nThe script is designed to support all three PowerShell completion modes:\n\n* TabCompleteNext (default windows style - on each key press the next option is displayed)\n* Complete (works like bash)\n* MenuComplete (works like zsh)\n\nYou set the mode with `Set-PSReadLineKeyHandler -Key Tab -Function <mode>`. Descriptions are only displayed when using the `Complete` or `MenuComplete` mode.\n\nUsers need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles.\n\n```\n# With descriptions and Mode 'Complete'\n$ helm s[tab]\nsearch  (search for a keyword in charts)  show  (show information of a chart)  status  (displays the status of the named release)\n\n# With descriptions and Mode 'MenuComplete' The description of the current selected value will be displayed below the suggestions.\n$ helm s[tab]\nsearch    show     status\n\nsearch for a keyword in charts\n\n# Without descriptions\n$ helm s[tab]\nsearch  show  status\n```\n### Aliases\n\nYou can also configure `powershell` aliases for your program and they will also support completions.\n\n```\n$ sal aliasname origcommand\n$ Register-ArgumentCompleter -CommandName 'aliasname' -ScriptBlock $__origcommandCompleterBlock\n\n# and now when you run `aliasname` completion will make\n# suggestions as it did for `origcommand`.\n\n$ aliasname <tab>\ncompletion     firstcommand   secondcommand\n```\nThe name of the completer block variable is of the form `$__<programName>CompleterBlock` where every `-` and `:` in the program name have been replaced with `_`, to respect powershell naming syntax.\n\n### Limitations\n\n* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `powershell` (including the use of the `BashCompCustom` flag annotation).\n  * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).\n* The function `MarkFlagCustom()` is not supported and will be ignored for `powershell`.\n  * You should instead use `RegisterFlagCompletionFunc()`.\n* The following flag completion annotations are not supported and will be ignored for `powershell`:\n  * `BashCompFilenameExt` (filtering by file extension)\n  * `BashCompSubdirsInDir` (filtering by directory)\n* The functions corresponding to the above annotations are consequently not supported and will be ignored for `powershell`:\n  * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension)\n  * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory)\n* Similarly, the following completion directives are not supported and will be ignored for `powershell`:\n  * `ShellCompDirectiveFilterFileExt` (filtering by file extension)\n  * `ShellCompDirectiveFilterDirs` (filtering by directory)\n"
  },
  {
    "path": "site/content/completions/bash.md",
    "content": "# Generating Bash Completions For Your cobra.Command\n\nPlease refer to [Shell Completions](_index.md) for details.\n\n## Bash legacy dynamic completions\n\nFor backward compatibility, Cobra still supports its legacy dynamic completion solution (described below).  Unlike the `ValidArgsFunction` solution, the legacy solution will only work for Bash shell-completion and not for other shells. This legacy solution can be used along-side `ValidArgsFunction` and `RegisterFlagCompletionFunc()`, as long as both solutions are not used for the same command.  This provides a path to gradually migrate from the legacy solution to the new solution.\n\n**Note**: Cobra's default `completion` command uses bash completion V2.  If you are currently using Cobra's legacy dynamic completion solution, you should not use the default `completion` command but continue using your own.\n\nThe legacy solution allows you to inject bash functions into the bash completion script.  Those bash functions are responsible for providing the completion choices for your own completions.\n\nSome code that works in kubernetes:\n\n```bash\nconst (\n        bash_completion_func = `__kubectl_parse_get()\n{\n    local kubectl_output out\n    if kubectl_output=$(kubectl get --no-headers \"$1\" 2>/dev/null); then\n        out=($(echo \"${kubectl_output}\" | awk '{print $1}'))\n        COMPREPLY=( $( compgen -W \"${out[*]}\" -- \"$cur\" ) )\n    fi\n}\n\n__kubectl_get_resource()\n{\n    if [[ ${#nouns[@]} -eq 0 ]]; then\n        return 1\n    fi\n    __kubectl_parse_get ${nouns[${#nouns[@]} -1]}\n    if [[ $? -eq 0 ]]; then\n        return 0\n    fi\n}\n\n__kubectl_custom_func() {\n    case ${last_command} in\n        kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop)\n            __kubectl_get_resource\n            return\n            ;;\n        *)\n            ;;\n    esac\n}\n`)\n```\n\nAnd then I set that in my command definition:\n\n```go\ncmds := &cobra.Command{\n\tUse:   \"kubectl\",\n\tShort: \"kubectl controls the Kubernetes cluster manager\",\n\tLong: `kubectl controls the Kubernetes cluster manager.\n\nFind more information at https://github.com/GoogleCloudPlatform/kubernetes.`,\n\tRun: runHelp,\n\tBashCompletionFunction: bash_completion_func,\n}\n```\n\nThe `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__kubectl_custom_func()` (`__<command-use>_custom_func()`) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__kubectl_customc_func()` will run because the cobra.Command only understood \"kubectl\" and \"get.\" `__kubectl_custom_func()` will see that the cobra.Command is \"kubectl_get\" and will thus call another helper `__kubectl_get_resource()`.  `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`.  So it will call `__kubectl_parse_get pod`.  `__kubectl_parse_get` will actually call out to kubernetes and get any pods.  It will then set `COMPREPLY` to valid pods!\n\nSimilarly, for flags:\n\n```go\n\tannotation := make(map[string][]string)\n\tannotation[cobra.BashCompCustom] = []string{\"__kubectl_get_namespaces\"}\n\n\tflag := &pflag.Flag{\n\t\tName:        \"namespace\",\n\t\tUsage:       usage,\n\t\tAnnotations: annotation,\n\t}\n\tcmd.Flags().AddFlag(flag)\n```\n\nIn addition add the `__kubectl_get_namespaces` implementation in the `BashCompletionFunction`\nvalue, e.g.:\n\n```bash\n__kubectl_get_namespaces()\n{\n    local template\n    template=\"{{ range .items  }}{{ .metadata.name }} {{ end }}\"\n    local kubectl_out\n    if kubectl_out=$(kubectl get -o template --template=\"${template}\" namespace 2>/dev/null); then\n        COMPREPLY=( $( compgen -W \"${kubectl_out}[*]\" -- \"$cur\" ) )\n    fi\n}\n```\n"
  },
  {
    "path": "site/content/completions/fish.md",
    "content": "## Generating Fish Completions For Your cobra.Command\n\nPlease refer to [Shell Completions](_index.md) for details.\n\n"
  },
  {
    "path": "site/content/completions/powershell.md",
    "content": "# Generating PowerShell Completions For Your Own cobra.Command\n\nPlease refer to [Shell Completions](_index.md#powershell-completions) for details.\n"
  },
  {
    "path": "site/content/completions/zsh.md",
    "content": "## Generating Zsh Completion For Your cobra.Command\n\nPlease refer to [Shell Completions](_index.md) for details.\n\n## Zsh completions standardization\n\nCobra 1.1 standardized its zsh completion support to align it with its other shell completions.  Although the API was kept backwards-compatible, some small changes in behavior were introduced.\n\n### Deprecation summary\n\nSee further below for more details on these deprecations.\n\n* `cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` is no longer needed.  It is therefore **deprecated** and silently ignored.\n* `cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` is **deprecated** and silently ignored.\n  * Instead use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt`.\n* `cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored.\n  * Instead use `ValidArgsFunction`.\n\n### Behavioral changes\n\n**Noun completion**\n|Old behavior|New behavior|\n|---|---|\n|No file completion by default (opposite of bash)|File completion by default; use `ValidArgsFunction` with `ShellCompDirectiveNoFileComp` to turn off file completion on a per-argument basis|\n|Completion of flag names without the `-` prefix having been typed|Flag names are only completed if the user has typed the first `-`|\n`cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` used to turn on file completion on a per-argument position basis|File completion for all arguments by default; `cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored|\n|`cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` used to turn on file completion **with glob filtering** on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored; use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt` for file **extension** filtering (not full glob filtering)|\n|`cmd.MarkZshCompPositionalArgumentWords(pos, words[])` used to provide completion choices on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored; use `ValidArgsFunction` to achieve the same behavior|\n\n**Flag-value completion**\n\n|Old behavior|New behavior|\n|---|---|\n|No file completion by default (opposite of bash)|File completion by default; use `RegisterFlagCompletionFunc()` with `ShellCompDirectiveNoFileComp` to turn off file completion|\n|`cmd.MarkFlagFilename(flag, []string{})` and similar used to turn on file completion|File completion by default; `cmd.MarkFlagFilename(flag, []string{})` no longer needed in this context and silently ignored|\n|`cmd.MarkFlagFilename(flag, glob[])`  used to turn on file completion **with glob filtering** (syntax of `[]string{\"*.yaml\", \"*.yml\"}` incompatible with bash)|Will continue to work, however, support for bash syntax is added and should be used instead so as to work for all shells (`[]string{\"yaml\", \"yml\"}`)|\n|`cmd.MarkFlagDirname(flag)` only completes directories (zsh-specific)|Has been added for all shells|\n|Completion of a flag name does not repeat, unless flag is of type `*Array` or `*Slice` (not supported by bash)|Retained for `zsh` and added to `fish`|\n|Completion of a flag name does not provide the `=` form (unlike bash)|Retained for `zsh` and added to `fish`|\n\n**Improvements**\n\n* Custom completion support (`ValidArgsFunction` and `RegisterFlagCompletionFunc()`)\n* File completion by default if no other completions found\n* Handling of required flags\n* File extension filtering no longer mutually exclusive with bash usage\n* Completion of directory names *within* another directory\n* Support for `=` form of flags\n"
  },
  {
    "path": "site/content/docgen/_index.md",
    "content": "# Documentation generation\n\n- [Man page docs](man.md)\n- [Markdown docs](md.md)\n- [Rest docs](rest.md)\n- [Yaml docs](yaml.md)\n\n## Options\n### `DisableAutoGenTag`\n\nYou may set `cmd.DisableAutoGenTag = true`\nto _entirely_ remove the auto generated string \"Auto generated by spf13/cobra...\"\nfrom any documentation source.\n\n### `InitDefaultCompletionCmd`\n\nYou may call `cmd.InitDefaultCompletionCmd()` to document the default autocompletion command.\n"
  },
  {
    "path": "site/content/docgen/man.md",
    "content": "# Generating Man Pages For Your Own cobra.Command\n\nGenerating man pages from a cobra command is incredibly easy. An example is as follows:\n\n```go\npackage main\n\nimport (\n\t\"log\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/cobra/doc\"\n)\n\nfunc main() {\n\tcmd := &cobra.Command{\n\t\tUse:   \"test\",\n\t\tShort: \"my test program\",\n\t}\n\theader := &doc.GenManHeader{\n\t\tTitle: \"MINE\",\n\t\tSection: \"3\",\n\t}\n\terr := doc.GenManTree(cmd, header, \"/tmp\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n```\n\nThat will get you a man page `/tmp/test.3`\n"
  },
  {
    "path": "site/content/docgen/md.md",
    "content": "# Generating Markdown Docs For Your Own cobra.Command\n\nGenerating Markdown pages from a cobra command is incredibly easy. An example is as follows:\n\n```go\npackage main\n\nimport (\n\t\"log\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/cobra/doc\"\n)\n\nfunc main() {\n\tcmd := &cobra.Command{\n\t\tUse:   \"test\",\n\t\tShort: \"my test program\",\n\t}\n\terr := doc.GenMarkdownTree(cmd, \"/tmp\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n```\n\nThat will get you a Markdown document `/tmp/test.md`\n\n## Generate markdown docs for the entire command tree\n\nThis program can actually generate docs for the kubectl command in the kubernetes project\n\n```go\npackage main\n\nimport (\n\t\"log\"\n\t\"io\"\n\t\"os\"\n\n\t\"k8s.io/kubernetes/pkg/kubectl/cmd\"\n\tcmdutil \"k8s.io/kubernetes/pkg/kubectl/cmd/util\"\n\n\t\"github.com/spf13/cobra/doc\"\n)\n\nfunc main() {\n\tkubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, io.Discard, io.Discard)\n\terr := doc.GenMarkdownTree(kubectl, \"./\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n```\n\nThis will generate a whole series of files, one for each command in the tree, in the directory specified (in this case \"./\")\n\n## Generate markdown docs for a single command\n\nYou may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenMarkdown` instead of `GenMarkdownTree`\n\n```go\n\tout := new(bytes.Buffer)\n\terr := doc.GenMarkdown(cmd, out)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n```\n\nThis will write the markdown doc for ONLY \"cmd\" into the out, buffer.\n\n## Customize the output\n\nBoth `GenMarkdown` and `GenMarkdownTree` have alternate versions with callbacks to get some control of the output:\n\n```go\nfunc GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {\n\t//...\n}\n```\n\n```go\nfunc GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {\n\t//...\n}\n```\n\nThe `filePrepender` will prepend the return value given the full filepath to the rendered Markdown file. A common use case is to add front matter to use the generated documentation with [Hugo](https://gohugo.io/):\n\n```go\nconst fmTemplate = `---\ndate: %s\ntitle: \"%s\"\nslug: %s\nurl: %s\n---\n`\n\nfilePrepender := func(filename string) string {\n\tnow := time.Now().Format(time.RFC3339)\n\tname := filepath.Base(filename)\n\tbase := strings.TrimSuffix(name, path.Ext(name))\n\turl := \"/commands/\" + strings.ToLower(base) + \"/\"\n\treturn fmt.Sprintf(fmTemplate, now, strings.Replace(base, \"_\", \" \", -1), base, url)\n}\n```\n\nThe `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:\n\n```go\nlinkHandler := func(name string) string {\n\tbase := strings.TrimSuffix(name, path.Ext(name))\n\treturn \"/commands/\" + strings.ToLower(base) + \"/\"\n}\n```\n"
  },
  {
    "path": "site/content/docgen/rest.md",
    "content": "# Generating ReStructured Text Docs For Your Own cobra.Command\n\nGenerating ReST pages from a cobra command is incredibly easy. An example is as follows:\n\n```go\npackage main\n\nimport (\n\t\"log\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/cobra/doc\"\n)\n\nfunc main() {\n\tcmd := &cobra.Command{\n\t\tUse:   \"test\",\n\t\tShort: \"my test program\",\n\t}\n\terr := doc.GenReSTTree(cmd, \"/tmp\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n```\n\nThat will get you a ReST document `/tmp/test.rst`\n\n## Generate ReST docs for the entire command tree\n\nThis program can actually generate docs for the kubectl command in the kubernetes project\n\n```go\npackage main\n\nimport (\n\t\"log\"\n\t\"io\"\n\t\"os\"\n\n\t\"k8s.io/kubernetes/pkg/kubectl/cmd\"\n\tcmdutil \"k8s.io/kubernetes/pkg/kubectl/cmd/util\"\n\n\t\"github.com/spf13/cobra/doc\"\n)\n\nfunc main() {\n\tkubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, io.Discard, io.Discard)\n\terr := doc.GenReSTTree(kubectl, \"./\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n```\n\nThis will generate a whole series of files, one for each command in the tree, in the directory specified (in this case \"./\")\n\n## Generate ReST docs for a single command\n\nYou may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenReST` instead of `GenReSTTree`\n\n```go\n\tout := new(bytes.Buffer)\n\terr := doc.GenReST(cmd, out)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n```\n\nThis will write the ReST doc for ONLY \"cmd\" into the out, buffer.\n\n## Customize the output\n\nBoth `GenReST` and `GenReSTTree` have alternate versions with callbacks to get some control of the output:\n\n```go\nfunc GenReSTTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {\n\t//...\n}\n```\n\n```go\nfunc GenReSTCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string, string) string) error {\n\t//...\n}\n```\n\nThe `filePrepender` will prepend the return value given the full filepath to the rendered ReST file. A common use case is to add front matter to use the generated documentation with [Hugo](https://gohugo.io/):\n\n```go\nconst fmTemplate = `---\ndate: %s\ntitle: \"%s\"\nslug: %s\nurl: %s\n---\n`\nfilePrepender := func(filename string) string {\n\tnow := time.Now().Format(time.RFC3339)\n\tname := filepath.Base(filename)\n\tbase := strings.TrimSuffix(name, path.Ext(name))\n\turl := \"/commands/\" + strings.ToLower(base) + \"/\"\n\treturn fmt.Sprintf(fmTemplate, now, strings.Replace(base, \"_\", \" \", -1), base, url)\n}\n```\n\nThe `linkHandler` can be used to customize the rendered links to the commands, given a command name and reference. This is useful while converting rst to html or while generating documentation with tools like Sphinx where `:ref:` is used:\n\n```go\n// Sphinx cross-referencing format\nlinkHandler := func(name, ref string) string {\n    return fmt.Sprintf(\":ref:`%s <%s>`\", name, ref)\n}\n```\n"
  },
  {
    "path": "site/content/docgen/yaml.md",
    "content": "# Generating Yaml Docs For Your Own cobra.Command\n\nGenerating yaml files from a cobra command is incredibly easy. An example is as follows:\n\n```go\npackage main\n\nimport (\n\t\"log\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/cobra/doc\"\n)\n\nfunc main() {\n\tcmd := &cobra.Command{\n\t\tUse:   \"test\",\n\t\tShort: \"my test program\",\n\t}\n\terr := doc.GenYamlTree(cmd, \"/tmp\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n```\n\nThat will get you a Yaml document `/tmp/test.yaml`\n\n## Generate yaml docs for the entire command tree\n\nThis program can actually generate docs for the kubectl command in the kubernetes project\n\n```go\npackage main\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"k8s.io/kubernetes/pkg/kubectl/cmd\"\n\tcmdutil \"k8s.io/kubernetes/pkg/kubectl/cmd/util\"\n\n\t\"github.com/spf13/cobra/doc\"\n)\n\nfunc main() {\n\tkubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, io.Discard, io.Discard)\n\terr := doc.GenYamlTree(kubectl, \"./\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n```\n\nThis will generate a whole series of files, one for each command in the tree, in the directory specified (in this case \"./\")\n\n## Generate yaml docs for a single command\n\nYou may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenYaml` instead of `GenYamlTree`\n\n```go\n\tout := new(bytes.Buffer)\n\tdoc.GenYaml(cmd, out)\n```\n\nThis will write the yaml doc for ONLY \"cmd\" into the out, buffer.\n\n## Customize the output\n\nBoth `GenYaml` and `GenYamlTree` have alternate versions with callbacks to get some control of the output:\n\n```go\nfunc GenYamlTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {\n\t//...\n}\n```\n\n```go\nfunc GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {\n\t//...\n}\n```\n\nThe `filePrepender` will prepend the return value given the full filepath to the rendered Yaml file. A common use case is to add front matter to use the generated documentation with [Hugo](https://gohugo.io/):\n\n```go\nconst fmTemplate = `---\ndate: %s\ntitle: \"%s\"\nslug: %s\nurl: %s\n---\n`\n\nfilePrepender := func(filename string) string {\n\tnow := time.Now().Format(time.RFC3339)\n\tname := filepath.Base(filename)\n\tbase := strings.TrimSuffix(name, path.Ext(name))\n\turl := \"/commands/\" + strings.ToLower(base) + \"/\"\n\treturn fmt.Sprintf(fmTemplate, now, strings.Replace(base, \"_\", \" \", -1), base, url)\n}\n```\n\nThe `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:\n\n```go\nlinkHandler := func(name string) string {\n\tbase := strings.TrimSuffix(name, path.Ext(name))\n\treturn \"/commands/\" + strings.ToLower(base) + \"/\"\n}\n```\n"
  },
  {
    "path": "site/content/projects_using_cobra.md",
    "content": "## Projects using Cobra\n\n- [Allero](https://github.com/allero-io/allero)\n- [Arewefastyet](https://benchmark.vitess.io)\n- [Arduino CLI](https://github.com/arduino/arduino-cli)\n- [Azion](https://github.com/aziontech/azion)\n- [Bleve](https://blevesearch.com/)\n- [Cilium](https://cilium.io/)\n- [CloudQuery](https://github.com/cloudquery/cloudquery)\n- [CockroachDB](https://www.cockroachlabs.com/)\n- [Conduit](https://github.com/conduitio/conduit)\n- [Constellation](https://github.com/edgelesssys/constellation)\n- [Cosmos SDK](https://github.com/cosmos/cosmos-sdk)\n- [Datree](https://github.com/datreeio/datree)\n- [Delve](https://github.com/derekparker/delve)\n- [Docker (distribution)](https://github.com/docker/distribution)\n- [Encore](https://encore.dev)\n- [Etcd](https://etcd.io/)\n- [Gardener](https://github.com/gardener/gardenctl)\n- [Giant Swarm's gsctl](https://github.com/giantswarm/gsctl)\n- [Git Bump](https://github.com/erdaltsksn/git-bump)\n- [GitHub CLI](https://github.com/cli/cli)\n- [GitHub Labeler](https://github.com/erdaltsksn/gh-label)\n- [Golangci-lint](https://golangci-lint.run)\n- [GopherJS](https://github.com/gopherjs/gopherjs)\n- [GoReleaser](https://goreleaser.com)\n- [Helm](https://helm.sh)\n- [Hugo](https://gohugo.io)\n- [Incus](https://linuxcontainers.org/incus/)\n- [Infracost](https://github.com/infracost/infracost)\n- [Istio](https://istio.io)\n- [Kool](https://github.com/kool-dev/kool)\n- [Kubernetes](https://kubernetes.io/)\n- [Kubescape](https://github.com/kubescape/kubescape)\n- [KubeVirt](https://github.com/kubevirt/kubevirt)\n- [Linkerd](https://linkerd.io/)\n- [LXC](https://github.com/canonical/lxd)\n- [Mattermost-server](https://github.com/mattermost/mattermost-server)\n- [Mercure](https://mercure.rocks/)\n- [Meroxa CLI](https://github.com/meroxa/cli)\n- [Metal Stack CLI](https://github.com/metal-stack/metalctl)\n- [Moby (former Docker)](https://github.com/moby/moby)\n- [Moldy](https://github.com/Moldy-Community/moldy)\n- [Multi-gitter](https://github.com/lindell/multi-gitter)\n- [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack)\n- [nFPM](https://nfpm.goreleaser.com)\n- [Okteto](https://github.com/okteto/okteto)\n- [OpenShift](https://www.openshift.com/)\n- [Ory Hydra](https://github.com/ory/hydra)\n- [Ory Kratos](https://github.com/ory/kratos)\n- [Periscope](https://github.com/anishathalye/periscope)\n- [Pixie](https://github.com/pixie-io/pixie)\n- [Polygon Edge](https://github.com/0xPolygon/polygon-edge)\n- [Pouch](https://github.com/alibaba/pouch)\n- [ProjectAtomic (enterprise)](https://www.projectatomic.io/)\n- [Prototool](https://github.com/uber/prototool)\n- [Pulumi](https://www.pulumi.com)\n- [QRcp](https://github.com/claudiodangelis/qrcp)\n- [Random](https://github.com/erdaltsksn/random)\n- [Rclone](https://rclone.org/)\n- [Scaleway CLI](https://github.com/scaleway/scaleway-cli)\n- [Sia](https://github.com/SiaFoundation/siad)\n- [Skaffold](https://skaffold.dev/)\n- [Taikun](https://taikun.cloud/)\n- [Tendermint](https://github.com/tendermint/tendermint)\n- [Twitch CLI](https://github.com/twitchdev/twitch-cli)\n- [UpCloud CLI (`upctl`)](https://github.com/UpCloudLtd/upcloud-cli)\n- [Vitess](https://vitess.io)\n- VMware's [Tanzu Community Edition](https://github.com/vmware-tanzu/community-edition) & [Tanzu Framework](https://github.com/vmware-tanzu/tanzu-framework)\n- [Werf](https://werf.io/)\n- [Zarf](https://github.com/defenseunicorns/zarf)\n- [ZITADEL](https://github.com/zitadel/zitadel)\n"
  },
  {
    "path": "site/content/user_guide.md",
    "content": "# User Guide\n\nWhile you are welcome to provide your own organization, typically a Cobra-based\napplication will follow the following organizational structure:\n\n```console\n▾ appName/\n  ▾ cmd/\n      add.go\n      your.go\n      commands.go\n      here.go\n  main.go\n```\n\nIn a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.\n\n```go\npackage main\n\nimport \"{pathToYourApp}/cmd\"\n\nfunc main() {\n  cmd.Execute()\n}\n```\n\n## Using the Cobra Generator\n\nCobra-CLI is its own program that will create your application and add any commands you want.\nIt's the easiest way to incorporate Cobra into your application.\n\nFor complete details on using the Cobra generator, please refer to [The Cobra-CLI Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md)\n\n## Using the Cobra Library\n\nTo manually implement Cobra you need to create a bare main.go file and a rootCmd file.\nYou will optionally provide additional commands as you see fit.\n\n### Create rootCmd\n\nCobra doesn't require any special constructors. Simply create your commands.\n\nIdeally you place this in app/cmd/root.go:\n\n```go\nvar rootCmd = &cobra.Command{\n  Use:   \"hugo\",\n  Short: \"Hugo is a very fast static site generator\",\n  Long: `A Fast and Flexible Static Site Generator built with\n                love by spf13 and friends in Go.\n                Complete documentation is available at https://gohugo.io/documentation/`,\n  Run: func(cmd *cobra.Command, args []string) {\n    // Do Stuff Here\n  },\n}\n\nfunc Execute() {\n  if err := rootCmd.Execute(); err != nil {\n    fmt.Fprintln(os.Stderr, err)\n    os.Exit(1)\n  }\n}\n```\n\nYou will additionally define flags and handle configuration in your init() function.\n\nFor example cmd/root.go:\n\n```go\npackage cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/viper\"\n)\n\nvar (\n\t// Used for flags.\n\tcfgFile     string\n\tuserLicense string\n\n\trootCmd = &cobra.Command{\n\t\tUse:   \"cobra-cli\",\n\t\tShort: \"A generator for Cobra based Applications\",\n\t\tLong: `Cobra is a CLI library for Go that empowers applications.\nThis application is a tool to generate the needed files\nto quickly create a Cobra application.`,\n\t}\n)\n\n// Execute executes the root command.\nfunc Execute() error {\n\treturn rootCmd.Execute()\n}\n\nfunc init() {\n\tcobra.OnInitialize(initConfig)\n\n\trootCmd.PersistentFlags().StringVar(&cfgFile, \"config\", \"\", \"config file (default is $HOME/.cobra.yaml)\")\n\trootCmd.PersistentFlags().StringP(\"author\", \"a\", \"YOUR NAME\", \"author name for copyright attribution\")\n\trootCmd.PersistentFlags().StringVarP(&userLicense, \"license\", \"l\", \"\", \"name of license for the project\")\n\trootCmd.PersistentFlags().Bool(\"viper\", true, \"use Viper for configuration\")\n\tviper.BindPFlag(\"author\", rootCmd.PersistentFlags().Lookup(\"author\"))\n\tviper.BindPFlag(\"useViper\", rootCmd.PersistentFlags().Lookup(\"viper\"))\n\tviper.SetDefault(\"author\", \"NAME HERE <EMAIL ADDRESS>\")\n\tviper.SetDefault(\"license\", \"apache\")\n\n\trootCmd.AddCommand(addCmd)\n\trootCmd.AddCommand(initCmd)\n}\n\nfunc initConfig() {\n\tif cfgFile != \"\" {\n\t\t// Use config file from the flag.\n\t\tviper.SetConfigFile(cfgFile)\n\t} else {\n\t\t// Find home directory.\n\t\thome, err := os.UserHomeDir()\n\t\tcobra.CheckErr(err)\n\n\t\t// Search config in home directory with name \".cobra\" (without extension).\n\t\tviper.AddConfigPath(home)\n\t\tviper.SetConfigType(\"yaml\")\n\t\tviper.SetConfigName(\".cobra\")\n\t}\n\n\tviper.AutomaticEnv()\n\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Println(\"Using config file:\", viper.ConfigFileUsed())\n\t}\n}\n```\n\n### Create your main.go\n\nWith the root command you need to have your main function execute it.\nExecute should be run on the root for clarity, though it can be called on any command.\n\nIn a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra.\n\n```go\npackage main\n\nimport \"{pathToYourApp}/cmd\"\n\nfunc main() {\n  cmd.Execute()\n}\n```\n\n### Create additional commands\n\nAdditional commands can be defined and typically are each given their own file\ninside of the cmd/ directory.\n\nIf you wanted to create a version command you would create cmd/version.go and\npopulate it with the following:\n\n```go\npackage cmd\n\nimport (\n  \"fmt\"\n\n  \"github.com/spf13/cobra\"\n)\n\nfunc init() {\n  rootCmd.AddCommand(versionCmd)\n}\n\nvar versionCmd = &cobra.Command{\n  Use:   \"version\",\n  Short: \"Print the version number of Hugo\",\n  Long:  `All software has versions. This is Hugo's`,\n  Run: func(cmd *cobra.Command, args []string) {\n    fmt.Println(\"Hugo Static Site Generator v0.9 -- HEAD\")\n  },\n}\n```\n\n### Organizing subcommands\n\nA command may have subcommands which in turn may have other subcommands. This is achieved by using\n`AddCommand`. In some cases, especially in larger applications, each subcommand may be defined in\nits own go package.\n\nThe suggested approach is for the parent command to use `AddCommand` to add its most immediate\nsubcommands. For example, consider the following directory structure:\n\n```console\n├── cmd\n│   ├── root.go\n│   └── sub1\n│       ├── sub1.go\n│       └── sub2\n│           ├── leafA.go\n│           ├── leafB.go\n│           └── sub2.go\n└── main.go\n```\n\nIn this case:\n\n* The `init` function of `root.go` adds the command defined in `sub1.go` to the root command.\n* The `init` function of `sub1.go` adds the command defined in `sub2.go` to the sub1 command.\n* The `init` function of `sub2.go` adds the commands defined in `leafA.go` and `leafB.go` to the\n  sub2 command.\n\nThis approach ensures the subcommands are always included at compile time while avoiding cyclic\nreferences.\n\n### Returning and handling errors\n\nIf you wish to return an error to the caller of a command, `RunE` can be used.\n\n```go\npackage cmd\n\nimport (\n  \"fmt\"\n\n  \"github.com/spf13/cobra\"\n)\n\nfunc init() {\n  rootCmd.AddCommand(tryCmd)\n}\n\nvar tryCmd = &cobra.Command{\n  Use:   \"try\",\n  Short: \"Try and possibly fail at something\",\n  RunE: func(cmd *cobra.Command, args []string) error {\n    if err := someFunc(); err != nil {\n\treturn err\n    }\n    return nil\n  },\n}\n```\n\nThe error can then be caught at the execute function call.\n\n## Working with Flags\n\nFlags provide modifiers to control how the action command operates.\n\n### Assign flags to a command\n\nSince the flags are defined and used in different locations, we need to\ndefine a variable outside with the correct scope to assign the flag to\nwork with.\n\n```go\nvar Verbose bool\nvar Source string\n```\n\nThere are two different approaches to assign a flag.\n\n### Persistent Flags\n\nA flag can be 'persistent', meaning that this flag will be available to the\ncommand it's assigned to as well as every command under that command. For\nglobal flags, assign a flag as a persistent flag on the root.\n\n```go\nrootCmd.PersistentFlags().BoolVarP(&Verbose, \"verbose\", \"v\", false, \"verbose output\")\n```\n\n### Local Flags\n\nA flag can also be assigned locally, which will only apply to that specific command.\n\n```go\nlocalCmd.Flags().StringVarP(&Source, \"source\", \"s\", \"\", \"Source directory to read from\")\n```\n\n### Local Flag on Parent Commands\n\nBy default, Cobra only parses local flags on the target command, and any local flags on\nparent commands are ignored. By enabling `Command.TraverseChildren`, Cobra will\nparse local flags on each command before executing the target command.\n\n```go\ncommand := cobra.Command{\n  Use: \"print [OPTIONS] [COMMANDS]\",\n  TraverseChildren: true,\n}\n```\n\n### Bind Flags with Config\n\nYou can also bind your flags with [viper](https://github.com/spf13/viper):\n\n```go\nvar author string\n\nfunc init() {\n  rootCmd.PersistentFlags().StringVar(&author, \"author\", \"YOUR NAME\", \"Author name for copyright attribution\")\n  viper.BindPFlag(\"author\", rootCmd.PersistentFlags().Lookup(\"author\"))\n}\n```\n\nIn this example, the persistent flag `author` is bound with `viper`.\n**Note**: the variable `author` will not be set to the value from config,\nwhen the `--author` flag is provided by user.\n\nMore in [viper documentation](https://github.com/spf13/viper#working-with-flags).\n\n### Required flags\n\nFlags are optional by default. If instead you wish your command to report an error\nwhen a flag has not been set, mark it as required:\n\n```go\nrootCmd.Flags().StringVarP(&Region, \"region\", \"r\", \"\", \"AWS region (required)\")\nrootCmd.MarkFlagRequired(\"region\")\n```\n\nOr, for persistent flags:\n\n```go\nrootCmd.PersistentFlags().StringVarP(&Region, \"region\", \"r\", \"\", \"AWS region (required)\")\nrootCmd.MarkPersistentFlagRequired(\"region\")\n```\n\n### Flag Groups\n\nIf you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then\nCobra can enforce that requirement:\n\n```go\nrootCmd.Flags().StringVarP(&u, \"username\", \"u\", \"\", \"Username (required if password is set)\")\nrootCmd.Flags().StringVarP(&pw, \"password\", \"p\", \"\", \"Password (required if username is set)\")\nrootCmd.MarkFlagsRequiredTogether(\"username\", \"password\")\n```\n\nYou can also prevent different flags from being provided together if they represent mutually\nexclusive options such as specifying an output format as either `--json` or `--yaml` but never both:\n\n```go\nrootCmd.Flags().BoolVar(&ofJson, \"json\", false, \"Output in JSON\")\nrootCmd.Flags().BoolVar(&ofYaml, \"yaml\", false, \"Output in YAML\")\nrootCmd.MarkFlagsMutuallyExclusive(\"json\", \"yaml\")\n```\n\nIf you want to require at least one flag from a group to be present, you can use `MarkFlagsOneRequired`.\nThis can be combined with `MarkFlagsMutuallyExclusive` to enforce exactly one flag from a given group:\n\n```go\nrootCmd.Flags().BoolVar(&ofJson, \"json\", false, \"Output in JSON\")\nrootCmd.Flags().BoolVar(&ofYaml, \"yaml\", false, \"Output in YAML\")\nrootCmd.MarkFlagsOneRequired(\"json\", \"yaml\")\nrootCmd.MarkFlagsMutuallyExclusive(\"json\", \"yaml\")\n```\n\nIn these cases:\n  - both local and persistent flags can be used\n    - **NOTE:** the group is only enforced on commands where every flag is defined\n  - a flag may appear in multiple groups\n  - a group may contain any number of flags\n\n### Repeated Flags\n\nCobra supports two types of repeated flags, useful for implementing SSH-like verbose flags (`-v`, `-vv`, `-vvv`) or collecting multiple values.\n\n#### Count Flags\n\nFor implementing verbose-style flags where repeated usage increases a counter (like SSH's `-v`, `-vv`, `-vvv`):\n\n```go\nvar verbose int\n\nfunc init() {\n  // CountVarP allows the flag to be repeated to increment the counter\n  rootCmd.PersistentFlags().CountVarP(&verbose, \"verbose\", \"v\", \"verbose output (can be repeated: -v, -vv, -vvv)\")\n}\n```\n\nUsage examples:\n- `myapp -v` → verbose = 1 (info level)\n- `myapp -vv` or `myapp -v -v` → verbose = 2 (debug level)\n- `myapp -vvv` or `myapp -v -v -v` → verbose = 3 (trace level)\n\nThen in your command logic:\n```go\nRun: func(cmd *cobra.Command, args []string) {\n  switch verbose {\n  case 0:\n    // Default: no verbose output\n  case 1:\n    // Info level logging\n    log.SetLevel(log.InfoLevel)\n  case 2:\n    // Debug level logging\n    log.SetLevel(log.DebugLevel)\n  case 3:\n    // Trace level logging\n    log.SetLevel(log.TraceLevel)\n  default:\n    // Maximum verbosity\n    log.SetLevel(log.TraceLevel)\n  }\n},\n```\n\n#### Array/Slice Flags\n\nFor collecting multiple values of the same flag:\n\n```go\nvar inputFiles []string\n\nfunc init() {\n  // StringArrayVarP allows multiple values: --input file1.txt --input file2.txt\n  rootCmd.Flags().StringArrayVarP(&inputFiles, \"input\", \"i\", []string{}, \"input files (can be repeated)\")\n\n  // Alternative: StringSliceVarP for comma-separated values\n  // rootCmd.Flags().StringSliceVarP(&inputFiles, \"input\", \"i\", []string{}, \"input files (comma-separated or repeated)\")\n}\n```\n\nUsage examples:\n- `myapp --input file1.txt --input file2.txt`\n- `myapp -i file1.txt -i file2.txt`\n- With StringSlice: `myapp --input file1.txt,file2.txt,file3.txt`\n\n**Note**: Both `CountVar` and array flags leverage the underlying [pflag](https://github.com/spf13/pflag) library's support for repeated flags.\n\n## Positional and Custom Arguments\n\nValidation of positional arguments can be specified using the `Args` field of `Command`.\nThe following validators are built in:\n\n- Number of arguments:\n  - `NoArgs` - report an error if there are any positional args.\n  - `ArbitraryArgs` - accept any number of args.\n  - `MinimumNArgs(int)` - report an error if less than N positional args are provided.\n  - `MaximumNArgs(int)` - report an error if more than N positional args are provided.\n  - `ExactArgs(int)` - report an error if there are not exactly N positional args.\n  - `RangeArgs(min, max)` - report an error if the number of args is not between `min` and `max`.\n- Content of the arguments:\n  - `OnlyValidArgs` - report an error if there are any positional args not specified in the `ValidArgs` field of `Command`, which can optionally be set to a list of valid values for positional args.\n\nIf `Args` is undefined or `nil`, it defaults to `ArbitraryArgs`.\n\nMoreover, `MatchAll(pargs ...PositionalArgs)` enables combining existing checks with arbitrary other checks.\nFor instance, if you want to report an error if there are not exactly N positional args OR if there are any positional\nargs that are not in the `ValidArgs` field of `Command`, you can call `MatchAll` on `ExactArgs` and `OnlyValidArgs`, as\nshown below:\n\n```go\nvar cmd = &cobra.Command{\n  Short: \"hello\",\n  Args: cobra.MatchAll(cobra.ExactArgs(2), cobra.OnlyValidArgs),\n  Run: func(cmd *cobra.Command, args []string) {\n    fmt.Println(\"Hello, World!\")\n  },\n}\n```\n\nIt is possible to set any custom validator that satisfies `func(cmd *cobra.Command, args []string) error`.\nFor example:\n\n```go\nvar cmd = &cobra.Command{\n  Short: \"hello\",\n  Args: func(cmd *cobra.Command, args []string) error {\n    // Optionally run one of the validators provided by cobra\n    if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {\n        return err\n    }\n    // Run the custom validation logic\n    if myapp.IsValidColor(args[0]) {\n      return nil\n    }\n    return fmt.Errorf(\"invalid color specified: %s\", args[0])\n  },\n  Run: func(cmd *cobra.Command, args []string) {\n    fmt.Println(\"Hello, World!\")\n  },\n}\n```\n\n## Example\n\nIn the example below, we have defined three commands. Two are at the top level\nand one (cmdTimes) is a child of one of the top commands. In this case the root\nis not executable, meaning that a subcommand is required. This is accomplished\nby not providing a 'Run' for the 'rootCmd'.\n\nWe have only defined one flag for a single command.\n\nMore documentation about flags is available at https://github.com/spf13/pflag.\n\n```go\npackage main\n\nimport (\n  \"fmt\"\n  \"strings\"\n\n  \"github.com/spf13/cobra\"\n)\n\nfunc main() {\n  var echoTimes int\n\n  var cmdPrint = &cobra.Command{\n    Use:   \"print [string to print]\",\n    Short: \"Print anything to the screen\",\n    Long: `print is for printing anything back to the screen.\nFor many years people have printed back to the screen.`,\n    Args: cobra.MinimumNArgs(1),\n    Run: func(cmd *cobra.Command, args []string) {\n      fmt.Println(\"Print: \" + strings.Join(args, \" \"))\n    },\n  }\n\n  var cmdEcho = &cobra.Command{\n    Use:   \"echo [string to echo]\",\n    Short: \"Echo anything to the screen\",\n    Long: `echo is for echoing anything back.\nEcho works a lot like print, except it has a child command.`,\n    Args: cobra.MinimumNArgs(1),\n    Run: func(cmd *cobra.Command, args []string) {\n      fmt.Println(\"Echo: \" + strings.Join(args, \" \"))\n    },\n  }\n\n  var cmdTimes = &cobra.Command{\n    Use:   \"times [string to echo]\",\n    Short: \"Echo anything to the screen more times\",\n    Long: `echo things multiple times back to the user by providing\na count and a string.`,\n    Args: cobra.MinimumNArgs(1),\n    Run: func(cmd *cobra.Command, args []string) {\n      for i := 0; i < echoTimes; i++ {\n        fmt.Println(\"Echo: \" + strings.Join(args, \" \"))\n      }\n    },\n  }\n\n  cmdTimes.Flags().IntVarP(&echoTimes, \"times\", \"t\", 1, \"times to echo the input\")\n\n  var rootCmd = &cobra.Command{Use: \"app\"}\n  rootCmd.AddCommand(cmdPrint, cmdEcho)\n  cmdEcho.AddCommand(cmdTimes)\n  rootCmd.Execute()\n}\n```\n\nFor a more complete example of a larger application, please checkout [Hugo](https://gohugo.io/).\n\n## Help Command\n\nCobra automatically adds a help command to your application when you have subcommands.\nThis will be called when a user runs 'app help'. Additionally, help will also\nsupport all other commands as input. Say, for instance, you have a command called\n'create' without any additional configuration; Cobra will work when 'app help\ncreate' is called.  Every command will automatically have the '--help' flag added.\n\n### Example\n\nThe following output is automatically generated by Cobra. Nothing beyond the\ncommand and flag definitions are needed.\n\n```console\n$ cobra-cli help\n\nCobra is a CLI library for Go that empowers applications.\nThis application is a tool to generate the needed files\nto quickly create a Cobra application.\n\nUsage:\n  cobra-cli [command]\n\nAvailable Commands:\n  add         Add a command to a Cobra Application\n  completion  Generate the autocompletion script for the specified shell\n  help        Help about any command\n  init        Initialize a Cobra Application\n\nFlags:\n  -a, --author string    author name for copyright attribution (default \"YOUR NAME\")\n      --config string    config file (default is $HOME/.cobra.yaml)\n  -h, --help             help for cobra-cli\n  -l, --license string   name of license for the project\n      --viper            use Viper for configuration\n\nUse \"cobra-cli [command] --help\" for more information about a command.\n```\n\nHelp is just a command like any other. There is no special logic or behavior\naround it. In fact, you can provide your own if you want.\n\n### Grouping commands in help\n\nCobra supports grouping of available commands in the help output.  To group commands, each group must be explicitly\ndefined using `AddGroup()` on the parent command.  Then a subcommand can be added to a group using the `GroupID` element\nof that subcommand. The groups will appear in the help output in the same order as they are defined using different\ncalls to `AddGroup()`.  If you use the generated `help` or `completion` commands, you can set their group ids using\n`SetHelpCommandGroupId()` and `SetCompletionCommandGroupId()` on the root command, respectively.\n\n### Defining your own help\n\nYou can provide your own Help command or your own template for the default command to use\nwith the following functions:\n\n```go\ncmd.SetHelpCommand(cmd *Command)\ncmd.SetHelpFunc(f func(*Command, []string))\ncmd.SetHelpTemplate(s string)\n```\n\nThe latter two will also apply to any children commands.\n\nNote that templates specified with `SetHelpTemplate` are evaluated using\n`text/template` which can increase the size of the compiled executable.\n\n## Usage Message\n\nWhen the user provides an invalid flag or invalid command, Cobra responds by\nshowing the user the 'usage'.\n\n### Example\nYou may recognize this from the help above. That's because the default help\nembeds the usage as part of its output.\n\n```console\n$ cobra-cli --invalid\nError: unknown flag: --invalid\nUsage:\n  cobra-cli [command]\n\nAvailable Commands:\n  add         Add a command to a Cobra Application\n  completion  Generate the autocompletion script for the specified shell\n  help        Help about any command\n  init        Initialize a Cobra Application\n\nFlags:\n  -a, --author string    author name for copyright attribution (default \"YOUR NAME\")\n      --config string    config file (default is $HOME/.cobra.yaml)\n  -h, --help             help for cobra-cli\n  -l, --license string   name of license for the project\n      --viper            use Viper for configuration\n\nUse \"cobra [command] --help\" for more information about a command.\n```\n\n### Defining your own usage\n\nYou can provide your own usage function or template for Cobra to use.\nLike help, the function and template are overridable through public methods:\n\n```go\ncmd.SetUsageFunc(f func(*Command) error)\ncmd.SetUsageTemplate(s string)\n```\n\nNote that templates specified with `SetUsageTemplate` are evaluated using\n`text/template` which can increase the size of the compiled executable.\n\n## Version Flag\n\nCobra adds a top-level '--version' flag if the Version field is set on the root command.\nRunning an application with the '--version' flag will print the version to stdout using\nthe version template. The template can be customized using the\n`cmd.SetVersionTemplate(s string)` function.\n\nNote that templates specified with `SetVersionTemplate` are evaluated using\n`text/template` which can increase the size of the compiled executable.\n\n## Error Message Prefix\n\nCobra prints an error message when receiving a non-nil error value.\nThe default error message is `Error: <error contents>`.\nThe Prefix, `Error:` can be customized using the `cmd.SetErrPrefix(s string)` function.\n\n## PreRun and PostRun Hooks\n\nIt is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`.  The `Persistent*Run` functions will be inherited by children if they do not declare their own.  The `*PreRun` and `*PostRun` functions will only be executed if the `Run` function of the current command has been declared.  These functions are run in the following order:\n\n- `PersistentPreRun`\n- `PreRun`\n- `Run`\n- `PostRun`\n- `PersistentPostRun`\n\nAn example of two commands which use all of these features is below.  When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`:\n\n```go\npackage main\n\nimport (\n  \"fmt\"\n\n  \"github.com/spf13/cobra\"\n)\n\nfunc main() {\n\n  var rootCmd = &cobra.Command{\n    Use:   \"root [sub]\",\n    Short: \"My root command\",\n    PersistentPreRun: func(cmd *cobra.Command, args []string) {\n      fmt.Printf(\"Inside rootCmd PersistentPreRun with args: %v\\n\", args)\n    },\n    PreRun: func(cmd *cobra.Command, args []string) {\n      fmt.Printf(\"Inside rootCmd PreRun with args: %v\\n\", args)\n    },\n    Run: func(cmd *cobra.Command, args []string) {\n      fmt.Printf(\"Inside rootCmd Run with args: %v\\n\", args)\n    },\n    PostRun: func(cmd *cobra.Command, args []string) {\n      fmt.Printf(\"Inside rootCmd PostRun with args: %v\\n\", args)\n    },\n    PersistentPostRun: func(cmd *cobra.Command, args []string) {\n      fmt.Printf(\"Inside rootCmd PersistentPostRun with args: %v\\n\", args)\n    },\n  }\n\n  var subCmd = &cobra.Command{\n    Use:   \"sub [no options!]\",\n    Short: \"My subcommand\",\n    PreRun: func(cmd *cobra.Command, args []string) {\n      fmt.Printf(\"Inside subCmd PreRun with args: %v\\n\", args)\n    },\n    Run: func(cmd *cobra.Command, args []string) {\n      fmt.Printf(\"Inside subCmd Run with args: %v\\n\", args)\n    },\n    PostRun: func(cmd *cobra.Command, args []string) {\n      fmt.Printf(\"Inside subCmd PostRun with args: %v\\n\", args)\n    },\n    PersistentPostRun: func(cmd *cobra.Command, args []string) {\n      fmt.Printf(\"Inside subCmd PersistentPostRun with args: %v\\n\", args)\n    },\n  }\n\n  rootCmd.AddCommand(subCmd)\n\n  rootCmd.SetArgs([]string{\"\"})\n  rootCmd.Execute()\n  fmt.Println()\n  rootCmd.SetArgs([]string{\"sub\", \"arg1\", \"arg2\"})\n  rootCmd.Execute()\n}\n```\n\nOutput:\n```\nInside rootCmd PersistentPreRun with args: []\nInside rootCmd PreRun with args: []\nInside rootCmd Run with args: []\nInside rootCmd PostRun with args: []\nInside rootCmd PersistentPostRun with args: []\n\nInside rootCmd PersistentPreRun with args: [arg1 arg2]\nInside subCmd PreRun with args: [arg1 arg2]\nInside subCmd Run with args: [arg1 arg2]\nInside subCmd PostRun with args: [arg1 arg2]\nInside subCmd PersistentPostRun with args: [arg1 arg2]\n```\n\nBy default, only the first persistent hook found in the command chain is executed.\nThat is why in the above output, the `rootCmd PersistentPostRun` was not called for a child command.\nSet `EnableTraverseRunHooks` global variable to `true` if you want to execute all parents' persistent hooks.\n\n## Suggestions when \"unknown command\" happens\n\nCobra will print automatic suggestions when \"unknown command\" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example:\n\n```console\n$ hugo srever\nError: unknown command \"srever\" for \"hugo\"\n\nDid you mean this?\n        server\n\nRun 'hugo --help' for usage.\n```\n\nSuggestions are automatically generated based on existing subcommands and use an implementation of [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.\n\nIf you need to disable suggestions or tweak the string distance in your command, use:\n\n```go\ncommand.DisableSuggestions = true\n```\n\nor\n\n```go\ncommand.SuggestionsMinimumDistance = 1\n```\n\nYou can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but make sense in your set of commands but for which\nyou don't want aliases. Example:\n\n```console\n$ kubectl remove\nError: unknown command \"remove\" for \"kubectl\"\n\nDid you mean this?\n        delete\n\nRun 'kubectl help' for usage.\n```\n\n## Generating documentation for your command\n\nCobra can generate documentation based on subcommands, flags, etc.\nRead more about it in the [docs generation documentation](docgen/_index.md).\n\n## Generating shell completions\n\nCobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell.\nIf you add more information to your commands, these completions can be amazingly powerful and flexible.\nRead more about it in [Shell Completions](completions/_index.md).\n\n## Providing Active Help\n\nCobra makes use of the shell-completion system to define a framework allowing you to provide Active Help to your users.\nActive Help are messages (hints, warnings, etc) printed as the program is being used.\nRead more about it in [Active Help](active_help.md).\n\n## Creating a plugin\n\nWhen creating a plugin for tools like *kubectl*, the executable is named\n`kubectl-myplugin`, but it is used as `kubectl myplugin`. To fix help\nmessages and completions, annotate the root command with the\n`cobra.CommandDisplayNameAnnotation` annotation.\n\n### Example kubectl plugin\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nfunc main() {\n\trootCmd := &cobra.Command{\n\t\tUse: \"kubectl-myplugin\",\n\t\tAnnotations: map[string]string{\n\t\t\tcobra.CommandDisplayNameAnnotation: \"kubectl myplugin\",\n\t\t},\n\t}\n\tsubCmd := &cobra.Command{\n\t\tUse: \"subcmd\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tfmt.Println(\"kubectl myplugin subcmd\")\n\t\t},\n\t}\n\trootCmd.AddCommand(subCmd)\n\trootCmd.Execute()\n}\n```\n\nExample run as a kubectl plugin:\n\n```console\n$ kubectl myplugin\nUsage:\n  kubectl myplugin [command]\n\nAvailable Commands:\n  completion  Generate the autocompletion script for the specified shell\n  help        Help about any command\n  subcmd\n\nFlags:\n  -h, --help   help for kubectl myplugin\n\nUse \"kubectl myplugin [command] --help\" for more information about a command.\n```\n"
  },
  {
    "path": "zsh_completions.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n)\n\n// GenZshCompletionFile generates zsh completion file including descriptions.\nfunc (c *Command) GenZshCompletionFile(filename string) error {\n\treturn c.genZshCompletionFile(filename, true)\n}\n\n// GenZshCompletion generates zsh completion file including descriptions\n// and writes it to the passed writer.\nfunc (c *Command) GenZshCompletion(w io.Writer) error {\n\treturn c.genZshCompletion(w, true)\n}\n\n// GenZshCompletionFileNoDesc generates zsh completion file without descriptions.\nfunc (c *Command) GenZshCompletionFileNoDesc(filename string) error {\n\treturn c.genZshCompletionFile(filename, false)\n}\n\n// GenZshCompletionNoDesc generates zsh completion file without descriptions\n// and writes it to the passed writer.\nfunc (c *Command) GenZshCompletionNoDesc(w io.Writer) error {\n\treturn c.genZshCompletion(w, false)\n}\n\n// MarkZshCompPositionalArgumentFile only worked for zsh and its behavior was\n// not consistent with Bash completion. It has therefore been disabled.\n// Instead, when no other completion is specified, file completion is done by\n// default for every argument. One can disable file completion on a per-argument\n// basis by using ValidArgsFunction and ShellCompDirectiveNoFileComp.\n// To achieve file extension filtering, one can use ValidArgsFunction and\n// ShellCompDirectiveFilterFileExt.\n//\n// Deprecated\nfunc (c *Command) MarkZshCompPositionalArgumentFile(argPosition int, patterns ...string) error {\n\treturn nil\n}\n\n// MarkZshCompPositionalArgumentWords only worked for zsh. It has therefore\n// been disabled.\n// To achieve the same behavior across all shells, one can use\n// ValidArgs (for the first argument only) or ValidArgsFunction for\n// any argument (can include the first one also).\n//\n// Deprecated\nfunc (c *Command) MarkZshCompPositionalArgumentWords(argPosition int, words ...string) error {\n\treturn nil\n}\n\nfunc (c *Command) genZshCompletionFile(filename string, includeDesc bool) error {\n\toutFile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer outFile.Close()\n\n\treturn c.genZshCompletion(outFile, includeDesc)\n}\n\nfunc (c *Command) genZshCompletion(w io.Writer, includeDesc bool) error {\n\tbuf := new(bytes.Buffer)\n\tgenZshComp(buf, c.Name(), includeDesc)\n\t_, err := buf.WriteTo(w)\n\treturn err\n}\n\nfunc genZshComp(buf io.StringWriter, name string, includeDesc bool) {\n\tcompCmd := ShellCompRequestCmd\n\tif !includeDesc {\n\t\tcompCmd = ShellCompNoDescRequestCmd\n\t}\n\tWriteStringAndCheck(buf, fmt.Sprintf(`#compdef %[1]s\ncompdef _%[1]s %[1]s\n\n# zsh completion for %-36[1]s -*- shell-script -*-\n\n__%[1]s_debug()\n{\n    local file=\"$BASH_COMP_DEBUG_FILE\"\n    if [[ -n ${file} ]]; then\n        echo \"$*\" >> \"${file}\"\n    fi\n}\n\n_%[1]s()\n{\n    local shellCompDirectiveError=%[3]d\n    local shellCompDirectiveNoSpace=%[4]d\n    local shellCompDirectiveNoFileComp=%[5]d\n    local shellCompDirectiveFilterFileExt=%[6]d\n    local shellCompDirectiveFilterDirs=%[7]d\n    local shellCompDirectiveKeepOrder=%[8]d\n\n    local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace keepOrder\n    local -a completions\n\n    __%[1]s_debug \"\\n========= starting completion logic ==========\"\n    __%[1]s_debug \"CURRENT: ${CURRENT}, words[*]: ${words[*]}\"\n\n    # The user could have moved the cursor backwards on the command-line.\n    # We need to trigger completion from the $CURRENT location, so we need\n    # to truncate the command-line ($words) up to the $CURRENT location.\n    # (We cannot use $CURSOR as its value does not work when a command is an alias.)\n    words=(\"${=words[1,CURRENT]}\")\n    __%[1]s_debug \"Truncated words[*]: ${words[*]},\"\n\n    lastParam=${words[-1]}\n    lastChar=${lastParam[-1]}\n    __%[1]s_debug \"lastParam: ${lastParam}, lastChar: ${lastChar}\"\n\n    # For zsh, when completing a flag with an = (e.g., %[1]s -n=<TAB>)\n    # completions must be prefixed with the flag\n    setopt local_options BASH_REMATCH\n    if [[ \"${lastParam}\" =~ '-.*=' ]]; then\n        # We are dealing with a flag with an =\n        flagPrefix=\"-P ${BASH_REMATCH}\"\n    fi\n\n    # Prepare the command to obtain completions\n    requestComp=\"${words[1]} %[2]s ${words[2,-1]}\"\n    if [ \"${lastChar}\" = \"\" ]; then\n        # If the last parameter is complete (there is a space following it)\n        # We add an extra empty parameter so we can indicate this to the go completion code.\n        __%[1]s_debug \"Adding extra empty parameter\"\n        requestComp=\"${requestComp} \\\"\\\"\"\n    fi\n\n    __%[1]s_debug \"About to call: eval ${requestComp}\"\n\n    # Use eval to handle any environment variables and such\n    out=$(eval ${requestComp} 2>/dev/null)\n    __%[1]s_debug \"completion output: ${out}\"\n\n    # Extract the directive integer following a : from the last line\n    local lastLine\n    while IFS='\\n' read -r line; do\n        lastLine=${line}\n    done < <(printf \"%%s\\n\" \"${out[@]}\")\n    __%[1]s_debug \"last line: ${lastLine}\"\n\n    if [ \"${lastLine[1]}\" = : ]; then\n        directive=${lastLine[2,-1]}\n        # Remove the directive including the : and the newline\n        local suffix\n        (( suffix=${#lastLine}+2))\n        out=${out[1,-$suffix]}\n    else\n        # There is no directive specified.  Leave $out as is.\n        __%[1]s_debug \"No directive found.  Setting do default\"\n        directive=0\n    fi\n\n    __%[1]s_debug \"directive: ${directive}\"\n    __%[1]s_debug \"completions: ${out}\"\n    __%[1]s_debug \"flagPrefix: ${flagPrefix}\"\n\n    if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then\n        __%[1]s_debug \"Completion received error. Ignoring completions.\"\n        return\n    fi\n\n    local activeHelpMarker=\"%[9]s\"\n    local endIndex=${#activeHelpMarker}\n    local startIndex=$((${#activeHelpMarker}+1))\n    local hasActiveHelp=0\n    while IFS='\\n' read -r comp; do\n        # Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker)\n        if [ \"${comp[1,$endIndex]}\" = \"$activeHelpMarker\" ];then\n            __%[1]s_debug \"ActiveHelp found: $comp\"\n            comp=\"${comp[$startIndex,-1]}\"\n            if [ -n \"$comp\" ]; then\n                compadd -x \"${comp}\"\n                __%[1]s_debug \"ActiveHelp will need delimiter\"\n                hasActiveHelp=1\n            fi\n\n            continue\n        fi\n\n        if [ -n \"$comp\" ]; then\n            # If requested, completions are returned with a description.\n            # The description is preceded by a TAB character.\n            # For zsh's _describe, we need to use a : instead of a TAB.\n            # We first need to escape any : as part of the completion itself.\n            comp=${comp//:/\\\\:}\n\n            local tab=\"$(printf '\\t')\"\n            comp=${comp//$tab/:}\n\n            __%[1]s_debug \"Adding completion: ${comp}\"\n            completions+=${comp}\n            lastComp=$comp\n        fi\n    done < <(printf \"%%s\\n\" \"${out[@]}\")\n\n    # Add a delimiter after the activeHelp statements, but only if:\n    # - there are completions following the activeHelp statements, or\n    # - file completion will be performed (so there will be choices after the activeHelp)\n    if [ $hasActiveHelp -eq 1 ]; then\n        if [ ${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then\n            __%[1]s_debug \"Adding activeHelp delimiter\"\n            compadd -x \"--\"\n            hasActiveHelp=0\n        fi\n    fi\n\n    if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then\n        __%[1]s_debug \"Activating nospace.\"\n        noSpace=\"-S ''\"\n    fi\n\n    if [ $((directive & shellCompDirectiveKeepOrder)) -ne 0 ]; then\n        __%[1]s_debug \"Activating keep order.\"\n        keepOrder=\"-V\"\n    fi\n\n    if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then\n        # File extension filtering\n        local filteringCmd\n        filteringCmd='_files'\n        for filter in ${completions[@]}; do\n            if [ ${filter[1]} != '*' ]; then\n                # zsh requires a glob pattern to do file filtering\n                filter=\"\\*.$filter\"\n            fi\n            filteringCmd+=\" -g $filter\"\n        done\n        filteringCmd+=\" ${flagPrefix}\"\n\n        __%[1]s_debug \"File filtering command: $filteringCmd\"\n        _arguments '*:filename:'\"$filteringCmd\"\n    elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then\n        # File completion for directories only\n        local subdir\n        subdir=\"${completions[1]}\"\n        if [ -n \"$subdir\" ]; then\n            __%[1]s_debug \"Listing directories in $subdir\"\n            pushd \"${subdir}\" >/dev/null 2>&1\n        else\n            __%[1]s_debug \"Listing directories in .\"\n        fi\n\n        local result\n        _arguments '*:dirname:_files -/'\" ${flagPrefix}\"\n        result=$?\n        if [ -n \"$subdir\" ]; then\n            popd >/dev/null 2>&1\n        fi\n        return $result\n    else\n        __%[1]s_debug \"Calling _describe\"\n        if eval _describe $keepOrder \"completions\" completions $flagPrefix $noSpace; then\n            __%[1]s_debug \"_describe found some completions\"\n\n            # Return the success of having called _describe\n            return 0\n        else\n            __%[1]s_debug \"_describe did not find completions.\"\n            __%[1]s_debug \"Checking if we should do file completion.\"\n            if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then\n                __%[1]s_debug \"deactivating file completion\"\n\n                # We must return an error code here to let zsh know that there were no\n                # completions found by _describe; this is what will trigger other\n                # matching algorithms to attempt to find completions.\n                # For example zsh can match letters in the middle of words.\n                return 1\n            else\n                # Perform file completion\n                __%[1]s_debug \"Activating file completion\"\n\n                # We must return the result of this command, so it must be the\n                # last command, or else we must store its result to return it.\n                _arguments '*:filename:_files'\" ${flagPrefix}\"\n            fi\n        fi\n    fi\n}\n\n# don't run the completion function when being source-ed or eval-ed\nif [ \"$funcstack[1]\" = \"_%[1]s\" ]; then\n    _%[1]s\nfi\n`, name, compCmd,\n\t\tShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,\n\t\tShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder,\n\t\tactiveHelpMarker))\n}\n"
  },
  {
    "path": "zsh_completions_test.go",
    "content": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage cobra\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestZshCompletionWithActiveHelp(t *testing.T) {\n\tc := &Command{Use: \"c\", Run: emptyRun}\n\n\tbuf := new(bytes.Buffer)\n\tassertNoErr(t, c.GenZshCompletion(buf))\n\toutput := buf.String()\n\n\t// check that active help is not being disabled\n\tactiveHelpVar := activeHelpEnvVar(c.Name())\n\tcheckOmit(t, output, fmt.Sprintf(\"%s=0\", activeHelpVar))\n}\n"
  }
]