Full Code of spf13/cobra for AI

main 61968e893eee cached
65 files
612.2 KB
167.0k tokens
654 symbols
1 requests
Download .txt
Showing preview only (637K chars total). Download the full file or copy to clipboard to get everything.
Repository: spf13/cobra
Branch: main
Commit: 61968e893eee
Files: 65
Total size: 612.2 KB

Directory structure:
gitextract_201ev488/

├── .github/
│   ├── dependabot.yml
│   ├── labeler.yml
│   └── workflows/
│       ├── labeler.yml
│       └── test.yml
├── .gitignore
├── .golangci.yml
├── .mailmap
├── CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE.txt
├── MAINTAINERS
├── Makefile
├── README.md
├── SECURITY.md
├── active_help.go
├── active_help_test.go
├── args.go
├── args_test.go
├── bash_completions.go
├── bash_completionsV2.go
├── bash_completionsV2_test.go
├── bash_completions_test.go
├── cobra.go
├── cobra_test.go
├── command.go
├── command_notwin.go
├── command_test.go
├── command_win.go
├── completions.go
├── completions_test.go
├── doc/
│   ├── cmd_test.go
│   ├── man_docs.go
│   ├── man_docs_test.go
│   ├── man_examples_test.go
│   ├── md_docs.go
│   ├── md_docs_test.go
│   ├── rest_docs.go
│   ├── rest_docs_test.go
│   ├── util.go
│   ├── yaml_docs.go
│   └── yaml_docs_test.go
├── fish_completions.go
├── fish_completions_test.go
├── flag_groups.go
├── flag_groups_test.go
├── go.mod
├── go.sum
├── powershell_completions.go
├── powershell_completions_test.go
├── shell_completions.go
├── site/
│   └── content/
│       ├── active_help.md
│       ├── completions/
│       │   ├── _index.md
│       │   ├── bash.md
│       │   ├── fish.md
│       │   ├── powershell.md
│       │   └── zsh.md
│       ├── docgen/
│       │   ├── _index.md
│       │   ├── man.md
│       │   ├── md.md
│       │   ├── rest.md
│       │   └── yaml.md
│       ├── projects_using_cobra.md
│       └── user_guide.md
├── zsh_completions.go
└── zsh_completions_test.go

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/dependabot.yml
================================================
version: 2
updates:
- package-ecosystem: gomod
  directory: /
  schedule:
    interval: weekly
  open-pull-requests-limit: 99
- package-ecosystem: github-actions
  directory: /
  schedule:
    interval: weekly
  open-pull-requests-limit: 99


================================================
FILE: .github/labeler.yml
================================================
# changes to documentation generation
"area/docs-generation": 
- changed-files:
  - any-glob-to-any-file: 'doc/**'

# changes to the core cobra command
"area/cobra-command":
- changed-files:
  - any-glob-to-any-file: ['./cobra.go', './cobra_test.go', './*command*.go']

# changes made to command flags/args
"area/flags":
- changed-files:
  - any-glob-to-any-file: './args*.go'

# changes to Github workflows
"area/github":
- changed-files:
  - any-glob-to-any-file: '.github/**'

# changes to shell completions
"area/shell-completion":
- changed-files:
  - any-glob-to-any-file: './*completions*'


================================================
FILE: .github/workflows/labeler.yml
================================================
name: "Pull Request Labeler"
on:
- pull_request_target

permissions:
  contents: read

jobs:
  triage:
    permissions:
      contents: read  # for actions/labeler to determine modified files
      pull-requests: write  # for actions/labeler to add labels to PRs
    runs-on: ubuntu-latest
    steps:
    - uses: actions/labeler@v5
      with:
        repo-token: "${{ github.token }}"



================================================
FILE: .github/workflows/test.yml
================================================
name: Test

on:
  push:
  pull_request:
  workflow_dispatch:

env:
  GO111MODULE: on

permissions:
  contents: read

jobs:


  lic-headers:
    runs-on: ubuntu-latest
    steps:

      - uses: actions/checkout@v4

      - run: >-
          docker run
          -v $(pwd):/wrk -w /wrk
          ghcr.io/google/addlicense
          -c 'The Cobra Authors'
          -y '2013-2023'
          -l apache
          -ignore '.github/**'
          -check
          .


  golangci-lint:
    permissions:
      contents: read  # for actions/checkout to fetch code
      pull-requests: read  # for golangci/golangci-lint-action to fetch pull requests
    runs-on: ubuntu-latest
    steps:

      - uses: actions/checkout@v4

      - uses: actions/setup-go@v6
        with:
          go-version: '^1.22'
          check-latest: true
          cache: true

      - uses: golangci/golangci-lint-action@v8.0.0
        with:
          version: latest
          args: --verbose


  test-unix:
    strategy:
      fail-fast: false
      matrix:
        platform:
        - ubuntu
        - macOS
        go:
        - 17
        - 18
        - 19
        - 20
        - 21
        - 22
        - 23
        - 24
    name: '${{ matrix.platform }} | 1.${{ matrix.go }}.x'
    runs-on: ${{ matrix.platform }}-latest
    steps:

    - uses: actions/checkout@v4

    - uses: actions/setup-go@v6
      with:
        go-version: 1.${{ matrix.go }}.x
        cache: true

    - run: |
        export GOBIN=$HOME/go/bin
        go install github.com/kyoh86/richgo@latest
        go install github.com/mitchellh/gox@latest

    - run: RICHGO_FORCE_COLOR=1 PATH=$HOME/go/bin/:$PATH make richtest


  test-win:
    name: MINGW64
    defaults:
      run:
        shell: msys2 {0}
    runs-on: windows-latest
    steps:

    - shell: bash
      run: git config --global core.autocrlf input

    - uses: msys2/setup-msys2@v2
      with:
        msystem: MINGW64
        update: true
        install: >
          git
          make
          unzip
          mingw-w64-x86_64-go

    - uses: actions/checkout@v4

    - uses: actions/cache@v4
      with:
        path: ~/go/pkg/mod
        key: ${{ runner.os }}-${{ matrix.go }}-${{ hashFiles('**/go.sum') }}
        restore-keys: ${{ runner.os }}-${{ matrix.go }}-

    - run: |
        export GOBIN=$HOME/go/bin
        go install github.com/kyoh86/richgo@latest
        go install github.com/mitchellh/gox@latest

    - run: RICHGO_FORCE_COLOR=1 PATH=$HOME/go/bin:$PATH make richtest


================================================
FILE: .gitignore
================================================
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so

# Folders
_obj
_test

# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out

*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*

_testmain.go

# Vim files https://github.com/github/gitignore/blob/master/Global/Vim.gitignore
# swap
[._]*.s[a-w][a-z]
[._]s[a-w][a-z]
# session
Session.vim
# temporary
.netrwhist
*~
# auto-generated tag files
tags

*.exe
cobra.test
bin

.idea/
*.iml


================================================
FILE: .golangci.yml
================================================
# Copyright 2013-2023 The Cobra Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

version: "2"

run:
  timeout: 5m

formatters:
  enable:
    - gofmt
    - goimports

linters:
  default: none
  enable:
    #- bodyclose
    #- depguard
    #- dogsled
    #- dupl
    - errcheck
    #- exhaustive
    #- funlen
    #- gochecknoinits
    - goconst
    - gocritic
    #- gocyclo
    #- goprintffuncname
    - gosec
    - govet
    - ineffassign
    #- lll
    - misspell
    #- mnd
    #- nakedret
    #- noctx
    - nolintlint
    #- rowserrcheck
    - staticcheck
    - unconvert
    #- unparam
    - unused
    #- whitespace
  exclusions:
    presets:
      - common-false-positives
      - legacy
      - std-error-handling
  settings:
    govet:
      # Disable buildtag check to allow dual build tag syntax (both //go:build and // +build).
      # This is necessary for Go 1.15 compatibility since //go:build was introduced in Go 1.17.
      # This can be removed once Cobra requires Go 1.17 or higher.
      disable:
        - buildtag


================================================
FILE: .mailmap
================================================
Steve Francia <steve.francia@gmail.com>
Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Fabiano Franz <ffranz@redhat.com>                   <contact@fabianofranz.com>


================================================
FILE: CONDUCT.md
================================================
## Cobra User Contract

### Versioning
Cobra 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.

### Backward Compatibility
We 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.

### Deprecation
Deprecation 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.

### CVE
Maintainers 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.

### Communication
Cobra 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.

### Breaking Changes
Breaking changes are generally allowed in the master branch, as this is the branch used to develop the next release of Cobra.

There 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.

Breaking 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.

Examples of breaking changes include:
- Removing or renaming exported constant, variable, type, or function.
- Updating the version of critical libraries such as `spf13/pflag`, `spf13/viper` etc...
  - Some version updates may be acceptable for picking up bug fixes, but maintainers must exercise caution when reviewing.

There 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.

### CI Testing
Maintainers will ensure the Cobra test suite utilizes the current supported versions of Golang.

### Disclaimer
Changes to this document and the contents therein are at the discretion of the maintainers.
None of the contents of this document are legally binding in any way to the maintainers or the users.


================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to Cobra

Thank you so much for contributing to Cobra. We appreciate your time and help.
Here are some guidelines to help you get started.

## Code of Conduct

Be kind and respectful to the members of the community. Take time to educate
others who are seeking help. Harassment of any kind will not be tolerated.

## Questions

If you have questions regarding Cobra, feel free to ask it in the community
[#cobra Slack channel][cobra-slack]

## Filing a bug or feature

1. Before filing an issue, please check the existing issues to see if a
   similar one was already opened. If there is one already opened, feel free
   to comment on it.
1. If you believe you've found a bug, please provide detailed steps of
   reproduction, the version of Cobra and anything else you believe will be
   useful to help troubleshoot it (e.g. OS environment, environment variables,
   etc...). Also state the current behavior vs. the expected behavior.
1. If you'd like to see a feature or an enhancement please open an issue with
   a clear title and description of what the feature is and why it would be
   beneficial to the project and its users.

## Submitting changes

1. CLA: Upon submitting a Pull Request (PR), contributors will be prompted to
   sign a CLA. Please sign the CLA :slightly_smiling_face:
1. Tests: If you are submitting code, please ensure you have adequate tests
   for the feature. Tests can be run via `go test ./...` or `make test`.
1. Since this is golang project, ensure the new code is properly formatted to
   ensure code consistency. Run `make all`.

### Quick steps to contribute

1. Fork the project.
1. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`)
1. Create your feature branch (`git checkout -b my-new-feature`)
1. Make changes and run tests (`make test`)
1. Add them to staging (`git add .`)
1. Commit your changes (`git commit -m 'Add some feature'`)
1. Push to the branch (`git push origin my-new-feature`)
1. Create new pull request

<!-- Links -->
[cobra-slack]: https://gophers.slack.com/archives/CD3LP1199


================================================
FILE: LICENSE.txt
================================================
                                Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.


================================================
FILE: MAINTAINERS
================================================
maintainers:
- spf13
- johnSchnake
- jpmcb
- marckhouzam
inactive:
- anthonyfok
- bep
- bogem
- broady
- eparis
- jharshman
- wfernandes


================================================
FILE: Makefile
================================================
BIN="./bin"
SRC=$(shell find . -name "*.go")

ifeq (, $(shell which golangci-lint))
$(warning "could not find golangci-lint in $(PATH), run: curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh")
endif

.PHONY: fmt lint test install_deps clean

default: all

all: fmt test

fmt:
	$(info ******************** checking formatting ********************)
	@test -z $(shell gofmt -l $(SRC)) || (gofmt -d $(SRC); exit 1)

lint:
	$(info ******************** running lint tools ********************)
	golangci-lint run -v

test: install_deps
	$(info ******************** running tests ********************)
	go test -v ./...

richtest: install_deps
	$(info ******************** running tests with kyoh86/richgo ********************)
	richgo test -v ./...

install_deps:
	$(info ******************** downloading dependencies ********************)
	go get -v ./...

clean:
	rm -rf $(BIN)


================================================
FILE: README.md
================================================
<div align="center">
<a href="https://cobra.dev">
<img width="512" height="535" alt="cobra-logo" src="https://github.com/user-attachments/assets/c8bf9aad-b5ae-41d3-8899-d83baec10af8" />
</a>
</div>

Cobra is a library for creating powerful modern CLI applications.

<a href="https://cobra.dev">Visit Cobra.dev for extensive documentation</a> 


Cobra is used in many Go projects such as [Kubernetes](https://kubernetes.io/),
[Hugo](https://gohugo.io), and [GitHub CLI](https://github.com/cli/cli) to
name a few. [This list](site/content/projects_using_cobra.md) contains a more extensive list of projects using Cobra.

[![](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)
[![Go Reference](https://pkg.go.dev/badge/github.com/spf13/cobra.svg)](https://pkg.go.dev/github.com/spf13/cobra)
[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra)
[![Slack](https://img.shields.io/badge/Slack-cobra-brightgreen)](https://gophers.slack.com/archives/CD3LP1199)
<hr>
<div align="center" markdown="1">
   <sup>Supported by:</sup>
   <br>
   <br>
   <a href="https://www.warp.dev/cobra">
      <img alt="Warp sponsorship" width="400" src="https://github.com/user-attachments/assets/ab8dd143-b0fd-4904-bdc5-dd7ecac94eae">
   </a>

### [Warp, the AI terminal for devs](https://www.warp.dev/cobra)
[Try Cobra in Warp today](https://www.warp.dev/cobra)<br>

</div>
<hr>

# Overview

Cobra is a library providing a simple interface to create powerful modern CLI
interfaces similar to git & go tools.

Cobra provides:
* Easy subcommand-based CLIs: `app server`, `app fetch`, etc.
* Fully POSIX-compliant flags (including short & long versions)
* Nested subcommands
* Global, local and cascading flags
* Intelligent suggestions (`app srver`... did you mean `app server`?)
* Automatic help generation for commands and flags
* Grouping help for subcommands
* Automatic help flag recognition of `-h`, `--help`, etc.
* Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell)
* Automatically generated man pages for your application
* Command aliases so you can change things without breaking them
* The flexibility to define your own help, usage, etc.
* Optional seamless integration with [viper](https://github.com/spf13/viper) for 12-factor apps

# Concepts

Cobra is built on a structure of commands, arguments & flags.

**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions.

The best applications read like sentences when used, and as a result, users
intuitively know how to interact with them.

The pattern to follow is
`APPNAME VERB NOUN --ADJECTIVE`
    or
`APPNAME COMMAND ARG --FLAG`.

A few good real world examples may better illustrate this point.

In the following example, 'server' is a command, and 'port' is a flag:

    hugo server --port=1313

In this command we are telling Git to clone the url bare.

    git clone URL --bare

## Commands

Command is the central point of the application. Each interaction that
the application supports will be contained in a Command. A command can
have children commands and optionally run an action.

In the example above, 'server' is the command.

[More about cobra.Command](https://pkg.go.dev/github.com/spf13/cobra#Command)

## Flags

A flag is a way to modify the behavior of a command. Cobra supports
fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/).
A Cobra command can define flags that persist through to children commands
and flags that are only available to that command.

In the example above, 'port' is the flag.

Flag functionality is provided by the [pflag
library](https://github.com/spf13/pflag), a fork of the flag standard library
which maintains the same interface while adding POSIX compliance.

# Installing
Using Cobra is easy. First, use `go get` to install the latest version
of the library.

```
go get -u github.com/spf13/cobra@latest
```

Next, include Cobra in your application:

```go
import "github.com/spf13/cobra"
```

# Usage
`cobra-cli` is a command line program to generate cobra applications and command files.
It will bootstrap your application scaffolding to rapidly
develop a Cobra-based application. It is the easiest way to incorporate Cobra into your application.

It can be installed by running:

```
go install github.com/spf13/cobra-cli@latest
```

For complete details on using the Cobra-CLI generator, please read [The Cobra Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md)

For complete details on using the Cobra library, please read [The Cobra User Guide](site/content/user_guide.md).

# License

Cobra is released under the Apache 2.0 license. See [LICENSE.txt](LICENSE.txt)


================================================
FILE: SECURITY.md
================================================
# Security Policy

## Reporting a Vulnerability

The `cobra` maintainers take security issues seriously and
we appreciate your efforts to _**responsibly**_ disclose your findings.
We will make every effort to swiftly respond and address concerns.

To report a security vulnerability:

1. **DO NOT** create a public GitHub issue for the vulnerability!
2. **DO NOT** create a public GitHub Pull Request with a fix for the vulnerability!
3. Send an email to `cobra-security@googlegroups.com`.
4. Include the following details in your report:
   - Description of the vulnerability
   - Steps to reproduce
   - Potential impact of the vulnerability (to your downstream project, to the Go ecosystem, etc.)
   - Any potential mitigations you've already identified
5. Allow up to 7 days for an initial response.
   You should receive an acknowledgment of your report and an estimated timeline for a fix.
6. (Optional) If you have a fix and would like to contribute your patch, please work
   directly with the maintainers via `cobra-security@googlegroups.com` to
   coordinate pushing the patch to GitHub, cutting a new release, and disclosing the change.

## Response Process

When a security vulnerability report is received, the `cobra` maintainers will:

1. Confirm receipt of the vulnerability report within 7 days.
2. Assess the report to determine if it constitutes a security vulnerability.
3. If confirmed, assign the vulnerability a severity level and create a timeline for addressing it.
4. Develop and test a fix.
5. Patch the vulnerability and make a new GitHub release: the maintainers will coordinate disclosure with the reporter.
6. Create a new GitHub Security Advisory to inform the broader Go ecosystem

## Disclosure Policy

The `cobra` maintainers follow a coordinated disclosure process:

1. Security vulnerabilities will be addressed as quickly as possible.
2. A CVE (Common Vulnerabilities and Exposures) identifier will be requested for significant vulnerabilities
   that are within `cobra` itself.
3. Once a fix is ready, the maintainers will:
   - Release a new version containing the fix.
   - Update the security advisory with details about the vulnerability.
   - Credit the reporter (unless they wish to remain anonymous).
   - Credit the fixer (unless they wish to remain anonymous, this may be the same as the reporter).
   - Announce the vulnerability through appropriate channels
     (GitHub Security Advisory, mailing lists, GitHub Releases, etc.)

## Supported Versions

Security fixes will typically only be released for the most recent major release.

## Upstream Security Issues

`cobra` generally will not accept vulnerability reports that originate in upstream
dependencies. I.e., if there is a problem in Go code that `cobra` depends on,
it is best to engage that project's maintainers and owners.

This security policy primarily pertains only to `cobra` itself but if you believe you've
identified a problem that originates in an upstream dependency and is being widely
distributed by `cobra`, please follow the disclosure procedure above: the `cobra`
maintainers will work with you to determine the severity and ecosystem impact.

## Security Updates and CVEs

Information about known security vulnerabilities and CVEs affecting `cobra` will
be published as GitHub Security Advisories at
https://github.com/spf13/cobra/security/advisories.

All users are encouraged to watch the repository and upgrade promptly when
security releases are published.

## `cobra` Security Best Practices for Users

When using `cobra` in your CLIs, the `cobra` maintainers recommend the following:

1. Always use the latest version of `cobra`.
2. [Use Go modules](https://go.dev/blog/using-go-modules) for dependency management.
3. Always use the latest possible version of Go.

## Security Best Practices for Contributors

When contributing to `cobra`:

1. Be mindful of security implications when adding new features or modifying existing ones.
2. Be aware of `cobra`'s extremely large reach: it is used in nearly every Go CLI
   (like Kubernetes, Docker, Prometheus, etc. etc.)
3. Write tests that explicitly cover edge cases and potential issues.
4. If you discover a security issue while working on `cobra`, please report it
   following the process above rather than opening a public pull request or issue that
   addresses the vulnerability.
5. 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),
   [sign your commits with a GPG or SSH key](https://docs.github.com/en/authentication/managing-commit-signature-verification/about-commit-signature-verification),
   etc.

## Acknowledgments

The `cobra` maintainers would like to thank all security researchers and
community members who help keep cobra, its users, and the entire Go ecosystem secure through responsible disclosures!!

---

*This security policy is inspired by the [Open Web Application Security Project (OWASP)](https://owasp.org/) guidelines and security best practices.*


================================================
FILE: active_help.go
================================================
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cobra

import (
	"fmt"
	"os"
)

const (
	activeHelpMarker = "_activeHelp_ "
	// The below values should not be changed: programs will be using them explicitly
	// in their user documentation, and users will be using them explicitly.
	activeHelpEnvVarSuffix  = "ACTIVE_HELP"
	activeHelpGlobalEnvVar  = configEnvVarGlobalPrefix + "_" + activeHelpEnvVarSuffix
	activeHelpGlobalDisable = "0"
)

// AppendActiveHelp adds the specified string to the specified array to be used as ActiveHelp.
// Such strings will be processed by the completion script and will be shown as ActiveHelp
// to the user.
// The array parameter should be the array that will contain the completions.
// This function can be called multiple times before and/or after completions are added to
// the array.  Each time this function is called with the same array, the new
// ActiveHelp line will be shown below the previous ones when completion is triggered.
func AppendActiveHelp(compArray []Completion, activeHelpStr string) []Completion {
	return append(compArray, fmt.Sprintf("%s%s", activeHelpMarker, activeHelpStr))
}

// GetActiveHelpConfig returns the value of the ActiveHelp environment variable
// <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the root command in upper
// case, with all non-ASCII-alphanumeric characters replaced by `_`.
// It will always return "0" if the global environment variable COBRA_ACTIVE_HELP
// is set to "0".
func GetActiveHelpConfig(cmd *Command) string {
	activeHelpCfg := os.Getenv(activeHelpGlobalEnvVar)
	if activeHelpCfg != activeHelpGlobalDisable {
		activeHelpCfg = os.Getenv(activeHelpEnvVar(cmd.Root().Name()))
	}
	return activeHelpCfg
}

// activeHelpEnvVar returns the name of the program-specific ActiveHelp environment
// variable.  It has the format <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the name of the
// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`.
func activeHelpEnvVar(name string) string {
	return configEnvVar(name, activeHelpEnvVarSuffix)
}


================================================
FILE: active_help_test.go
================================================
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cobra

import (
	"fmt"
	"os"
	"strings"
	"testing"
)

const (
	activeHelpMessage  = "This is an activeHelp message"
	activeHelpMessage2 = "This is the rest of the activeHelp message"
)

func TestActiveHelpAlone(t *testing.T) {
	rootCmd := &Command{
		Use: "root",
		Run: emptyRun,
	}

	activeHelpFunc := func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
		comps := AppendActiveHelp(nil, activeHelpMessage)
		return comps, ShellCompDirectiveDefault
	}

	// Test that activeHelp can be added to a root command
	rootCmd.ValidArgsFunction = activeHelpFunc

	output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}

	expected := strings.Join([]string{
		fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),
		":0",
		"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")

	if output != expected {
		t.Errorf("expected: %q, got: %q", expected, output)
	}

	rootCmd.ValidArgsFunction = nil

	// Test that activeHelp can be added to a child command
	childCmd := &Command{
		Use:   "thechild",
		Short: "The child command",
		Run:   emptyRun,
	}
	rootCmd.AddCommand(childCmd)

	childCmd.ValidArgsFunction = activeHelpFunc

	output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}

	expected = strings.Join([]string{
		fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),
		":0",
		"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")

	if output != expected {
		t.Errorf("expected: %q, got: %q", expected, output)
	}
}

func TestActiveHelpWithComps(t *testing.T) {
	rootCmd := &Command{
		Use: "root",
		Run: emptyRun,
	}

	childCmd := &Command{
		Use:   "thechild",
		Short: "The child command",
		Run:   emptyRun,
	}
	rootCmd.AddCommand(childCmd)

	// Test that activeHelp can be added following other completions
	childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
		comps := []string{"first", "second"}
		comps = AppendActiveHelp(comps, activeHelpMessage)
		return comps, ShellCompDirectiveDefault
	}

	output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}

	expected := strings.Join([]string{
		"first",
		"second",
		fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),
		":0",
		"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")

	if output != expected {
		t.Errorf("expected: %q, got: %q", expected, output)
	}

	// Test that activeHelp can be added preceding other completions
	childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
		var comps []string
		comps = AppendActiveHelp(comps, activeHelpMessage)
		comps = append(comps, []string{"first", "second"}...)
		return comps, ShellCompDirectiveDefault
	}

	output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}

	expected = strings.Join([]string{
		fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),
		"first",
		"second",
		":0",
		"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")

	if output != expected {
		t.Errorf("expected: %q, got: %q", expected, output)
	}

	// Test that activeHelp can be added interleaved with other completions
	childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
		comps := []string{"first"}
		comps = AppendActiveHelp(comps, activeHelpMessage)
		comps = append(comps, "second")
		return comps, ShellCompDirectiveDefault
	}

	output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}

	expected = strings.Join([]string{
		"first",
		fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),
		"second",
		":0",
		"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")

	if output != expected {
		t.Errorf("expected: %q, got: %q", expected, output)
	}
}

func TestMultiActiveHelp(t *testing.T) {
	rootCmd := &Command{
		Use: "root",
		Run: emptyRun,
	}

	childCmd := &Command{
		Use:   "thechild",
		Short: "The child command",
		Run:   emptyRun,
	}
	rootCmd.AddCommand(childCmd)

	// Test that multiple activeHelp message can be added
	childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
		comps := AppendActiveHelp(nil, activeHelpMessage)
		comps = AppendActiveHelp(comps, activeHelpMessage2)
		return comps, ShellCompDirectiveNoFileComp
	}

	output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}

	expected := strings.Join([]string{
		fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),
		fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage2),
		":4",
		"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")

	if output != expected {
		t.Errorf("expected: %q, got: %q", expected, output)
	}

	// Test that multiple activeHelp messages can be used along with completions
	childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
		comps := []string{"first"}
		comps = AppendActiveHelp(comps, activeHelpMessage)
		comps = append(comps, "second")
		comps = AppendActiveHelp(comps, activeHelpMessage2)
		return comps, ShellCompDirectiveNoFileComp
	}

	output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}

	expected = strings.Join([]string{
		"first",
		fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),
		"second",
		fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage2),
		":4",
		"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")

	if output != expected {
		t.Errorf("expected: %q, got: %q", expected, output)
	}
}

func TestActiveHelpForFlag(t *testing.T) {
	rootCmd := &Command{
		Use: "root",
		Run: emptyRun,
	}
	flagname := "flag"
	rootCmd.Flags().String(flagname, "", "A flag")

	// Test that multiple activeHelp message can be added
	_ = rootCmd.RegisterFlagCompletionFunc(flagname, func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
		comps := []string{"first"}
		comps = AppendActiveHelp(comps, activeHelpMessage)
		comps = append(comps, "second")
		comps = AppendActiveHelp(comps, activeHelpMessage2)
		return comps, ShellCompDirectiveNoFileComp
	})

	output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--flag", "")
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}

	expected := strings.Join([]string{
		"first",
		fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage),
		"second",
		fmt.Sprintf("%s%s", activeHelpMarker, activeHelpMessage2),
		":4",
		"Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")

	if output != expected {
		t.Errorf("expected: %q, got: %q", expected, output)
	}
}

func TestConfigActiveHelp(t *testing.T) {
	rootCmd := &Command{
		Use: "root",
		Run: emptyRun,
	}

	childCmd := &Command{
		Use:   "thechild",
		Short: "The child command",
		Run:   emptyRun,
	}
	rootCmd.AddCommand(childCmd)

	activeHelpCfg := "someconfig,anotherconfig"
	// Set the variable that the user would be setting
	os.Setenv(activeHelpEnvVar(rootCmd.Name()), activeHelpCfg)

	childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
		receivedActiveHelpCfg := GetActiveHelpConfig(cmd)
		if receivedActiveHelpCfg != activeHelpCfg {
			t.Errorf("expected activeHelpConfig: %q, but got: %q", activeHelpCfg, receivedActiveHelpCfg)
		}
		return nil, ShellCompDirectiveDefault
	}

	_, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}

	// Test active help config for a flag
	activeHelpCfg = "a config for a flag"
	// Set the variable that the completions scripts will be setting
	os.Setenv(activeHelpEnvVar(rootCmd.Name()), activeHelpCfg)

	flagname := "flag"
	childCmd.Flags().String(flagname, "", "A flag")

	// Test that multiple activeHelp message can be added
	_ = childCmd.RegisterFlagCompletionFunc(flagname, func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
		receivedActiveHelpCfg := GetActiveHelpConfig(cmd)
		if receivedActiveHelpCfg != activeHelpCfg {
			t.Errorf("expected activeHelpConfig: %q, but got: %q", activeHelpCfg, receivedActiveHelpCfg)
		}
		return nil, ShellCompDirectiveDefault
	})

	_, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "--flag", "")
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}
}

func TestDisableActiveHelp(t *testing.T) {
	rootCmd := &Command{
		Use: "root",
		Run: emptyRun,
	}

	childCmd := &Command{
		Use:   "thechild",
		Short: "The child command",
		Run:   emptyRun,
	}
	rootCmd.AddCommand(childCmd)

	// Test the disabling of activeHelp using the specific program
	// environment variable that the completions scripts will be setting.
	// Make sure the disabling value is "0" by hard-coding it in the tests;
	// this is for backwards-compatibility as programs will be using this value.
	os.Setenv(activeHelpEnvVar(rootCmd.Name()), "0")

	childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
		comps := []string{"first"}
		comps = AppendActiveHelp(comps, activeHelpMessage)
		return comps, ShellCompDirectiveDefault
	}

	output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}
	os.Unsetenv(activeHelpEnvVar(rootCmd.Name()))

	// Make sure there is no ActiveHelp in the output
	expected := strings.Join([]string{
		"first",
		":0",
		"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")

	if output != expected {
		t.Errorf("expected: %q, got: %q", expected, output)
	}

	// Now test the global disabling of ActiveHelp
	os.Setenv(activeHelpGlobalEnvVar, "0")
	// Set the specific variable, to make sure it is ignored when the global env
	// var is set properly
	os.Setenv(activeHelpEnvVar(rootCmd.Name()), "1")

	output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}

	// Make sure there is no ActiveHelp in the output
	expected = strings.Join([]string{
		"first",
		":0",
		"Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")

	if output != expected {
		t.Errorf("expected: %q, got: %q", expected, output)
	}

	// Make sure that if the global env variable is set to anything else than
	// the disable value it is ignored
	os.Setenv(activeHelpGlobalEnvVar, "on")
	// Set the specific variable, to make sure it is used (while ignoring the global env var)
	activeHelpCfg := "1"
	os.Setenv(activeHelpEnvVar(rootCmd.Name()), activeHelpCfg)

	childCmd.ValidArgsFunction = func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
		receivedActiveHelpCfg := GetActiveHelpConfig(cmd)
		if receivedActiveHelpCfg != activeHelpCfg {
			t.Errorf("expected activeHelpConfig: %q, but got: %q", activeHelpCfg, receivedActiveHelpCfg)
		}
		return nil, ShellCompDirectiveDefault
	}

	_, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "thechild", "")
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}
}


================================================
FILE: args.go
================================================
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cobra

import (
	"fmt"
	"strings"
)

type PositionalArgs func(cmd *Command, args []string) error

// legacyArgs validation has the following behaviour:
// - root commands with no subcommands can take arbitrary arguments
// - root commands with subcommands will do subcommand validity checking
// - subcommands will always accept arbitrary arguments
func legacyArgs(cmd *Command, args []string) error {
	// no subcommand, always take args
	if !cmd.HasSubCommands() {
		return nil
	}

	// root command with subcommands, do subcommand checking.
	if !cmd.HasParent() && len(args) > 0 {
		return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0]))
	}
	return nil
}

// NoArgs returns an error if any args are included.
func NoArgs(cmd *Command, args []string) error {
	if len(args) > 0 {
		return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath())
	}
	return nil
}

// OnlyValidArgs returns an error if there are any positional args that are not in
// the `ValidArgs` field of `Command`
func OnlyValidArgs(cmd *Command, args []string) error {
	if len(cmd.ValidArgs) > 0 {
		// Remove any description that may be included in ValidArgs.
		// A description is following a tab character.
		validArgs := make([]string, 0, len(cmd.ValidArgs))
		for _, v := range cmd.ValidArgs {
			validArgs = append(validArgs, strings.SplitN(v, "\t", 2)[0])
		}
		for _, v := range args {
			if !stringInSlice(v, validArgs) {
				return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0]))
			}
		}
	}
	return nil
}

// ArbitraryArgs never returns an error.
func ArbitraryArgs(cmd *Command, args []string) error {
	return nil
}

// MinimumNArgs returns an error if there is not at least N args.
func MinimumNArgs(n int) PositionalArgs {
	return func(cmd *Command, args []string) error {
		if len(args) < n {
			return fmt.Errorf("requires at least %d arg(s), only received %d", n, len(args))
		}
		return nil
	}
}

// MaximumNArgs returns an error if there are more than N args.
func MaximumNArgs(n int) PositionalArgs {
	return func(cmd *Command, args []string) error {
		if len(args) > n {
			return fmt.Errorf("accepts at most %d arg(s), received %d", n, len(args))
		}
		return nil
	}
}

// ExactArgs returns an error if there are not exactly n args.
func ExactArgs(n int) PositionalArgs {
	return func(cmd *Command, args []string) error {
		if len(args) != n {
			return fmt.Errorf("accepts %d arg(s), received %d", n, len(args))
		}
		return nil
	}
}

// RangeArgs returns an error if the number of args is not within the expected range.
func RangeArgs(min int, max int) PositionalArgs {
	return func(cmd *Command, args []string) error {
		if len(args) < min || len(args) > max {
			return fmt.Errorf("accepts between %d and %d arg(s), received %d", min, max, len(args))
		}
		return nil
	}
}

// MatchAll allows combining several PositionalArgs to work in concert.
func MatchAll(pargs ...PositionalArgs) PositionalArgs {
	return func(cmd *Command, args []string) error {
		for _, parg := range pargs {
			if err := parg(cmd, args); err != nil {
				return err
			}
		}
		return nil
	}
}

// ExactValidArgs returns an error if there are not exactly N positional args OR
// there are any positional args that are not in the `ValidArgs` field of `Command`
//
// Deprecated: use MatchAll(ExactArgs(n), OnlyValidArgs) instead
func ExactValidArgs(n int) PositionalArgs {
	return MatchAll(ExactArgs(n), OnlyValidArgs)
}


================================================
FILE: args_test.go
================================================
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cobra

import (
	"fmt"
	"strings"
	"testing"
)

func getCommand(args PositionalArgs, withValid bool) *Command {
	c := &Command{
		Use:  "c",
		Args: args,
		Run:  emptyRun,
	}
	if withValid {
		c.ValidArgs = []string{"one", "two", "three"}
	}
	return c
}

func expectSuccess(output string, err error, t *testing.T) {
	if output != "" {
		t.Errorf("Unexpected output: %v", output)
	}
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
}

func validOnlyWithInvalidArgs(err error, t *testing.T) {
	if err == nil {
		t.Fatal("Expected an error")
	}
	got := err.Error()
	expected := `invalid argument "a" for "c"`
	if got != expected {
		t.Errorf("Expected: %q, got: %q", expected, got)
	}
}

func noArgsWithArgs(err error, t *testing.T, arg string) {
	if err == nil {
		t.Fatal("Expected an error")
	}
	got := err.Error()
	expected := `unknown command "` + arg + `" for "c"`
	if got != expected {
		t.Errorf("Expected: %q, got: %q", expected, got)
	}
}

func minimumNArgsWithLessArgs(err error, t *testing.T) {
	if err == nil {
		t.Fatal("Expected an error")
	}
	got := err.Error()
	expected := "requires at least 2 arg(s), only received 1"
	if got != expected {
		t.Fatalf("Expected %q, got %q", expected, got)
	}
}

func maximumNArgsWithMoreArgs(err error, t *testing.T) {
	if err == nil {
		t.Fatal("Expected an error")
	}
	got := err.Error()
	expected := "accepts at most 2 arg(s), received 3"
	if got != expected {
		t.Fatalf("Expected %q, got %q", expected, got)
	}
}

func exactArgsWithInvalidCount(err error, t *testing.T) {
	if err == nil {
		t.Fatal("Expected an error")
	}
	got := err.Error()
	expected := "accepts 2 arg(s), received 3"
	if got != expected {
		t.Fatalf("Expected %q, got %q", expected, got)
	}
}

func rangeArgsWithInvalidCount(err error, t *testing.T) {
	if err == nil {
		t.Fatal("Expected an error")
	}
	got := err.Error()
	expected := "accepts between 2 and 4 arg(s), received 1"
	if got != expected {
		t.Fatalf("Expected %q, got %q", expected, got)
	}
}

// NoArgs

func TestNoArgs(t *testing.T) {
	c := getCommand(NoArgs, false)
	output, err := executeCommand(c)
	expectSuccess(output, err, t)
}

func TestNoArgs_WithArgs(t *testing.T) {
	c := getCommand(NoArgs, false)
	_, err := executeCommand(c, "one")
	noArgsWithArgs(err, t, "one")
}

func TestNoArgs_WithValid_WithArgs(t *testing.T) {
	c := getCommand(NoArgs, true)
	_, err := executeCommand(c, "one")
	noArgsWithArgs(err, t, "one")
}

func TestNoArgs_WithValid_WithInvalidArgs(t *testing.T) {
	c := getCommand(NoArgs, true)
	_, err := executeCommand(c, "a")
	noArgsWithArgs(err, t, "a")
}

func TestNoArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
	c := getCommand(MatchAll(OnlyValidArgs, NoArgs), true)
	_, err := executeCommand(c, "a")
	validOnlyWithInvalidArgs(err, t)
}

// OnlyValidArgs

func TestOnlyValidArgs(t *testing.T) {
	c := getCommand(OnlyValidArgs, true)
	output, err := executeCommand(c, "one", "two")
	expectSuccess(output, err, t)
}

func TestOnlyValidArgs_WithInvalidArgs(t *testing.T) {
	c := getCommand(OnlyValidArgs, true)
	_, err := executeCommand(c, "a")
	validOnlyWithInvalidArgs(err, t)
}

// ArbitraryArgs

func TestArbitraryArgs(t *testing.T) {
	c := getCommand(ArbitraryArgs, false)
	output, err := executeCommand(c, "a", "b")
	expectSuccess(output, err, t)
}

func TestArbitraryArgs_WithValid(t *testing.T) {
	c := getCommand(ArbitraryArgs, true)
	output, err := executeCommand(c, "one", "two")
	expectSuccess(output, err, t)
}

func TestArbitraryArgs_WithValid_WithInvalidArgs(t *testing.T) {
	c := getCommand(ArbitraryArgs, true)
	output, err := executeCommand(c, "a")
	expectSuccess(output, err, t)
}

func TestArbitraryArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
	c := getCommand(MatchAll(OnlyValidArgs, ArbitraryArgs), true)
	_, err := executeCommand(c, "a")
	validOnlyWithInvalidArgs(err, t)
}

// MinimumNArgs

func TestMinimumNArgs(t *testing.T) {
	c := getCommand(MinimumNArgs(2), false)
	output, err := executeCommand(c, "a", "b", "c")
	expectSuccess(output, err, t)
}

func TestMinimumNArgs_WithValid(t *testing.T) {
	c := getCommand(MinimumNArgs(2), true)
	output, err := executeCommand(c, "one", "three")
	expectSuccess(output, err, t)
}

func TestMinimumNArgs_WithValid__WithInvalidArgs(t *testing.T) {
	c := getCommand(MinimumNArgs(2), true)
	output, err := executeCommand(c, "a", "b")
	expectSuccess(output, err, t)
}

func TestMinimumNArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
	c := getCommand(MatchAll(OnlyValidArgs, MinimumNArgs(2)), true)
	_, err := executeCommand(c, "a", "b")
	validOnlyWithInvalidArgs(err, t)
}

func TestMinimumNArgs_WithLessArgs(t *testing.T) {
	c := getCommand(MinimumNArgs(2), false)
	_, err := executeCommand(c, "a")
	minimumNArgsWithLessArgs(err, t)
}

func TestMinimumNArgs_WithLessArgs_WithValid(t *testing.T) {
	c := getCommand(MinimumNArgs(2), true)
	_, err := executeCommand(c, "one")
	minimumNArgsWithLessArgs(err, t)
}

func TestMinimumNArgs_WithLessArgs_WithValid_WithInvalidArgs(t *testing.T) {
	c := getCommand(MinimumNArgs(2), true)
	_, err := executeCommand(c, "a")
	minimumNArgsWithLessArgs(err, t)
}

func TestMinimumNArgs_WithLessArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
	c := getCommand(MatchAll(OnlyValidArgs, MinimumNArgs(2)), true)
	_, err := executeCommand(c, "a")
	validOnlyWithInvalidArgs(err, t)
}

// MaximumNArgs

func TestMaximumNArgs(t *testing.T) {
	c := getCommand(MaximumNArgs(3), false)
	output, err := executeCommand(c, "a", "b")
	expectSuccess(output, err, t)
}

func TestMaximumNArgs_WithValid(t *testing.T) {
	c := getCommand(MaximumNArgs(2), true)
	output, err := executeCommand(c, "one", "three")
	expectSuccess(output, err, t)
}

func TestMaximumNArgs_WithValid_WithInvalidArgs(t *testing.T) {
	c := getCommand(MaximumNArgs(2), true)
	output, err := executeCommand(c, "a", "b")
	expectSuccess(output, err, t)
}

func TestMaximumNArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
	c := getCommand(MatchAll(OnlyValidArgs, MaximumNArgs(2)), true)
	_, err := executeCommand(c, "a", "b")
	validOnlyWithInvalidArgs(err, t)
}

func TestMaximumNArgs_WithMoreArgs(t *testing.T) {
	c := getCommand(MaximumNArgs(2), false)
	_, err := executeCommand(c, "a", "b", "c")
	maximumNArgsWithMoreArgs(err, t)
}

func TestMaximumNArgs_WithMoreArgs_WithValid(t *testing.T) {
	c := getCommand(MaximumNArgs(2), true)
	_, err := executeCommand(c, "one", "three", "two")
	maximumNArgsWithMoreArgs(err, t)
}

func TestMaximumNArgs_WithMoreArgs_WithValid_WithInvalidArgs(t *testing.T) {
	c := getCommand(MaximumNArgs(2), true)
	_, err := executeCommand(c, "a", "b", "c")
	maximumNArgsWithMoreArgs(err, t)
}

func TestMaximumNArgs_WithMoreArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
	c := getCommand(MatchAll(OnlyValidArgs, MaximumNArgs(2)), true)
	_, err := executeCommand(c, "a", "b", "c")
	validOnlyWithInvalidArgs(err, t)
}

// ExactArgs

func TestExactArgs(t *testing.T) {
	c := getCommand(ExactArgs(3), false)
	output, err := executeCommand(c, "a", "b", "c")
	expectSuccess(output, err, t)
}

func TestExactArgs_WithValid(t *testing.T) {
	c := getCommand(ExactArgs(3), true)
	output, err := executeCommand(c, "three", "one", "two")
	expectSuccess(output, err, t)
}

func TestExactArgs_WithValid_WithInvalidArgs(t *testing.T) {
	c := getCommand(ExactArgs(3), true)
	output, err := executeCommand(c, "three", "a", "two")
	expectSuccess(output, err, t)
}

func TestExactArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
	c := getCommand(MatchAll(OnlyValidArgs, ExactArgs(3)), true)
	_, err := executeCommand(c, "three", "a", "two")
	validOnlyWithInvalidArgs(err, t)
}

func TestExactArgs_WithInvalidCount(t *testing.T) {
	c := getCommand(ExactArgs(2), false)
	_, err := executeCommand(c, "a", "b", "c")
	exactArgsWithInvalidCount(err, t)
}

func TestExactArgs_WithInvalidCount_WithValid(t *testing.T) {
	c := getCommand(ExactArgs(2), true)
	_, err := executeCommand(c, "three", "one", "two")
	exactArgsWithInvalidCount(err, t)
}

func TestExactArgs_WithInvalidCount_WithValid_WithInvalidArgs(t *testing.T) {
	c := getCommand(ExactArgs(2), true)
	_, err := executeCommand(c, "three", "a", "two")
	exactArgsWithInvalidCount(err, t)
}

func TestExactArgs_WithInvalidCount_WithValidOnly_WithInvalidArgs(t *testing.T) {
	c := getCommand(MatchAll(OnlyValidArgs, ExactArgs(2)), true)
	_, err := executeCommand(c, "three", "a", "two")
	validOnlyWithInvalidArgs(err, t)
}

// RangeArgs

func TestRangeArgs(t *testing.T) {
	c := getCommand(RangeArgs(2, 4), false)
	output, err := executeCommand(c, "a", "b", "c")
	expectSuccess(output, err, t)
}

func TestRangeArgs_WithValid(t *testing.T) {
	c := getCommand(RangeArgs(2, 4), true)
	output, err := executeCommand(c, "three", "one", "two")
	expectSuccess(output, err, t)
}

func TestRangeArgs_WithValid_WithInvalidArgs(t *testing.T) {
	c := getCommand(RangeArgs(2, 4), true)
	output, err := executeCommand(c, "three", "a", "two")
	expectSuccess(output, err, t)
}

func TestRangeArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
	c := getCommand(MatchAll(OnlyValidArgs, RangeArgs(2, 4)), true)
	_, err := executeCommand(c, "three", "a", "two")
	validOnlyWithInvalidArgs(err, t)
}

func TestRangeArgs_WithInvalidCount(t *testing.T) {
	c := getCommand(RangeArgs(2, 4), false)
	_, err := executeCommand(c, "a")
	rangeArgsWithInvalidCount(err, t)
}

func TestRangeArgs_WithInvalidCount_WithValid(t *testing.T) {
	c := getCommand(RangeArgs(2, 4), true)
	_, err := executeCommand(c, "two")
	rangeArgsWithInvalidCount(err, t)
}

func TestRangeArgs_WithInvalidCount_WithValid_WithInvalidArgs(t *testing.T) {
	c := getCommand(RangeArgs(2, 4), true)
	_, err := executeCommand(c, "a")
	rangeArgsWithInvalidCount(err, t)
}

func TestRangeArgs_WithInvalidCount_WithValidOnly_WithInvalidArgs(t *testing.T) {
	c := getCommand(MatchAll(OnlyValidArgs, RangeArgs(2, 4)), true)
	_, err := executeCommand(c, "a")
	validOnlyWithInvalidArgs(err, t)
}

// Takes(No)Args

func TestRootTakesNoArgs(t *testing.T) {
	rootCmd := &Command{Use: "root", Run: emptyRun}
	childCmd := &Command{Use: "child", Run: emptyRun}
	rootCmd.AddCommand(childCmd)

	_, err := executeCommand(rootCmd, "illegal", "args")
	if err == nil {
		t.Fatal("Expected an error")
	}

	got := err.Error()
	expected := `unknown command "illegal" for "root"`
	if !strings.Contains(got, expected) {
		t.Errorf("expected %q, got %q", expected, got)
	}
}

func TestRootTakesArgs(t *testing.T) {
	rootCmd := &Command{Use: "root", Args: ArbitraryArgs, Run: emptyRun}
	childCmd := &Command{Use: "child", Run: emptyRun}
	rootCmd.AddCommand(childCmd)

	_, err := executeCommand(rootCmd, "legal", "args")
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}
}

func TestChildTakesNoArgs(t *testing.T) {
	rootCmd := &Command{Use: "root", Run: emptyRun}
	childCmd := &Command{Use: "child", Args: NoArgs, Run: emptyRun}
	rootCmd.AddCommand(childCmd)

	_, err := executeCommand(rootCmd, "child", "illegal", "args")
	if err == nil {
		t.Fatal("Expected an error")
	}

	got := err.Error()
	expected := `unknown command "illegal" for "root child"`
	if !strings.Contains(got, expected) {
		t.Errorf("expected %q, got %q", expected, got)
	}
}

func TestChildTakesArgs(t *testing.T) {
	rootCmd := &Command{Use: "root", Run: emptyRun}
	childCmd := &Command{Use: "child", Args: ArbitraryArgs, Run: emptyRun}
	rootCmd.AddCommand(childCmd)

	_, err := executeCommand(rootCmd, "child", "legal", "args")
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
}

func TestMatchAll(t *testing.T) {
	// Somewhat contrived example check that ensures there are exactly 3
	// arguments, and each argument is exactly 2 bytes long.
	pargs := MatchAll(
		ExactArgs(3),
		func(cmd *Command, args []string) error {
			for _, arg := range args {
				if len([]byte(arg)) != 2 {
					return fmt.Errorf("expected to be exactly 2 bytes long")
				}
			}
			return nil
		},
	)

	testCases := map[string]struct {
		args []string
		fail bool
	}{
		"happy path": {
			[]string{"aa", "bb", "cc"},
			false,
		},
		"incorrect number of args": {
			[]string{"aa", "bb", "cc", "dd"},
			true,
		},
		"incorrect number of bytes in one arg": {
			[]string{"aa", "bb", "abc"},
			true,
		},
	}

	rootCmd := &Command{Use: "root", Args: pargs, Run: emptyRun}

	for name, tc := range testCases {
		t.Run(name, func(t *testing.T) {
			_, err := executeCommand(rootCmd, tc.args...)
			if err != nil && !tc.fail {
				t.Errorf("unexpected: %v\n", err)
			}
			if err == nil && tc.fail {
				t.Errorf("expected error")
			}
		})
	}
}

// DEPRECATED

func TestExactValidArgs(t *testing.T) {
	c := getCommand(ExactValidArgs(3), true)
	output, err := executeCommand(c, "three", "one", "two")
	expectSuccess(output, err, t)
}

func TestExactValidArgs_WithInvalidCount(t *testing.T) {
	c := getCommand(ExactValidArgs(2), false)
	_, err := executeCommand(c, "three", "one", "two")
	exactArgsWithInvalidCount(err, t)
}

func TestExactValidArgs_WithInvalidCount_WithInvalidArgs(t *testing.T) {
	c := getCommand(ExactValidArgs(2), true)
	_, err := executeCommand(c, "three", "a", "two")
	exactArgsWithInvalidCount(err, t)
}

func TestExactValidArgs_WithInvalidArgs(t *testing.T) {
	c := getCommand(ExactValidArgs(2), true)
	_, err := executeCommand(c, "three", "a")
	validOnlyWithInvalidArgs(err, t)
}

// This test make sure we keep backwards-compatibility with respect
// to the legacyArgs() function.
// It makes sure the root command accepts arguments if it does not have
// sub-commands.
func TestLegacyArgsRootAcceptsArgs(t *testing.T) {
	rootCmd := &Command{Use: "root", Args: nil, Run: emptyRun}

	_, err := executeCommand(rootCmd, "somearg")
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
}

// This test make sure we keep backwards-compatibility with respect
// to the legacyArgs() function.
// It makes sure a sub-command accepts arguments and further sub-commands
func TestLegacyArgsSubcmdAcceptsArgs(t *testing.T) {
	rootCmd := &Command{Use: "root", Args: nil, Run: emptyRun}
	childCmd := &Command{Use: "child", Args: nil, Run: emptyRun}
	grandchildCmd := &Command{Use: "grandchild", Args: nil, Run: emptyRun}
	rootCmd.AddCommand(childCmd)
	childCmd.AddCommand(grandchildCmd)

	_, err := executeCommand(rootCmd, "child", "somearg")
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
}


================================================
FILE: bash_completions.go
================================================
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cobra

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"sort"
	"strings"

	"github.com/spf13/pflag"
)

// Annotations for Bash completion.
const (
	BashCompFilenameExt     = "cobra_annotation_bash_completion_filename_extensions"
	BashCompCustom          = "cobra_annotation_bash_completion_custom"
	BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"
	BashCompSubdirsInDir    = "cobra_annotation_bash_completion_subdirs_in_dir"
)

func writePreamble(buf io.StringWriter, name string) {
	WriteStringAndCheck(buf, fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name))
	WriteStringAndCheck(buf, fmt.Sprintf(`
__%[1]s_debug()
{
    if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then
        echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
    fi
}

# Homebrew on Macs have version 1.3 of bash-completion which doesn't include
# _init_completion. This is a very minimal version of that function.
__%[1]s_init_completion()
{
    COMPREPLY=()
    _get_comp_words_by_ref "$@" cur prev words cword
}

__%[1]s_index_of_word()
{
    local w word=$1
    shift
    index=0
    for w in "$@"; do
        [[ $w = "$word" ]] && return
        index=$((index+1))
    done
    index=-1
}

__%[1]s_contains_word()
{
    local w word=$1; shift
    for w in "$@"; do
        [[ $w = "$word" ]] && return
    done
    return 1
}

__%[1]s_handle_go_custom_completion()
{
    __%[1]s_debug "${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}"

    local shellCompDirectiveError=%[3]d
    local shellCompDirectiveNoSpace=%[4]d
    local shellCompDirectiveNoFileComp=%[5]d
    local shellCompDirectiveFilterFileExt=%[6]d
    local shellCompDirectiveFilterDirs=%[7]d

    local out requestComp lastParam lastChar comp directive args

    # Prepare the command to request completions for the program.
    # Calling ${words[0]} instead of directly %[1]s allows handling aliases
    args=("${words[@]:1}")
    # Disable ActiveHelp which is not supported for bash completion v1
    requestComp="%[8]s=0 ${words[0]} %[2]s ${args[*]}"

    lastParam=${words[$((${#words[@]}-1))]}
    lastChar=${lastParam:$((${#lastParam}-1)):1}
    __%[1]s_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}"

    if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then
        # If the last parameter is complete (there is a space following it)
        # We add an extra empty parameter so we can indicate this to the go method.
        __%[1]s_debug "${FUNCNAME[0]}: Adding extra empty parameter"
        requestComp="${requestComp} \"\""
    fi

    __%[1]s_debug "${FUNCNAME[0]}: calling ${requestComp}"
    # Use eval to handle any environment variables and such
    out=$(eval "${requestComp}" 2>/dev/null)

    # Extract the directive integer at the very end of the output following a colon (:)
    directive=${out##*:}
    # Remove the directive
    out=${out%%:*}
    if [ "${directive}" = "${out}" ]; then
        # There is not directive specified
        directive=0
    fi
    __%[1]s_debug "${FUNCNAME[0]}: the completion directive is: ${directive}"
    __%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out}"

    if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
        # Error code.  No completion.
        __%[1]s_debug "${FUNCNAME[0]}: received error from custom completion go code"
        return
    else
        if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then
            if [[ $(type -t compopt) = "builtin" ]]; then
                __%[1]s_debug "${FUNCNAME[0]}: activating no space"
                compopt -o nospace
            fi
        fi
        if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
            if [[ $(type -t compopt) = "builtin" ]]; then
                __%[1]s_debug "${FUNCNAME[0]}: activating no file completion"
                compopt +o default
            fi
        fi
    fi

    if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
        # File extension filtering
        local fullFilter filter filteringCmd
        # Do not use quotes around the $out variable or else newline
        # characters will be kept.
        for filter in ${out}; do
            fullFilter+="$filter|"
        done

        filteringCmd="_filedir $fullFilter"
        __%[1]s_debug "File filtering command: $filteringCmd"
        $filteringCmd
    elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
        # File completion for directories only
        local subdir
        # Use printf to strip any trailing newline
        subdir=$(printf "%%s" "${out}")
        if [ -n "$subdir" ]; then
            __%[1]s_debug "Listing directories in $subdir"
            __%[1]s_handle_subdirs_in_dir_flag "$subdir"
        else
            __%[1]s_debug "Listing directories in ."
            _filedir -d
        fi
    else
        while IFS='' read -r comp; do
            COMPREPLY+=("$comp")
        done < <(compgen -W "${out}" -- "$cur")
    fi
}

__%[1]s_handle_reply()
{
    __%[1]s_debug "${FUNCNAME[0]}"
    local comp
    case $cur in
        -*)
            if [[ $(type -t compopt) = "builtin" ]]; then
                compopt -o nospace
            fi
            local allflags
            if [ ${#must_have_one_flag[@]} -ne 0 ]; then
                allflags=("${must_have_one_flag[@]}")
            else
                allflags=("${flags[*]} ${two_word_flags[*]}")
            fi
            while IFS='' read -r comp; do
                COMPREPLY+=("$comp")
            done < <(compgen -W "${allflags[*]}" -- "$cur")
            if [[ $(type -t compopt) = "builtin" ]]; then
                [[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace
            fi

            # complete after --flag=abc
            if [[ $cur == *=* ]]; then
                if [[ $(type -t compopt) = "builtin" ]]; then
                    compopt +o nospace
                fi

                local index flag
                flag="${cur%%=*}"
                __%[1]s_index_of_word "${flag}" "${flags_with_completion[@]}"
                COMPREPLY=()
                if [[ ${index} -ge 0 ]]; then
                    PREFIX=""
                    cur="${cur#*=}"
                    ${flags_completion[${index}]}
                    if [ -n "${ZSH_VERSION:-}" ]; then
                        # zsh completion needs --flag= prefix
                        eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )"
                    fi
                fi
            fi

            if [[ -z "${flag_parsing_disabled}" ]]; then
                # If flag parsing is enabled, we have completed the flags and can return.
                # If flag parsing is disabled, we may not know all (or any) of the flags, so we fallthrough
                # to possibly call handle_go_custom_completion.
                return 0;
            fi
            ;;
    esac

    # check if we are handling a flag with special work handling
    local index
    __%[1]s_index_of_word "${prev}" "${flags_with_completion[@]}"
    if [[ ${index} -ge 0 ]]; then
        ${flags_completion[${index}]}
        return
    fi

    # we are parsing a flag and don't have a special handler, no completion
    if [[ ${cur} != "${words[cword]}" ]]; then
        return
    fi

    local completions
    completions=("${commands[@]}")
    if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then
        completions+=("${must_have_one_noun[@]}")
    elif [[ -n "${has_completion_function}" ]]; then
        # if a go completion function is provided, defer to that function
        __%[1]s_handle_go_custom_completion
    fi
    if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then
        completions+=("${must_have_one_flag[@]}")
    fi
    while IFS='' read -r comp; do
        COMPREPLY+=("$comp")
    done < <(compgen -W "${completions[*]}" -- "$cur")

    if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then
        while IFS='' read -r comp; do
            COMPREPLY+=("$comp")
        done < <(compgen -W "${noun_aliases[*]}" -- "$cur")
    fi

    if [[ ${#COMPREPLY[@]} -eq 0 ]]; then
        if declare -F __%[1]s_custom_func >/dev/null; then
            # try command name qualified custom func
            __%[1]s_custom_func
        else
            # otherwise fall back to unqualified for compatibility
            declare -F __custom_func >/dev/null && __custom_func
        fi
    fi

    # available in bash-completion >= 2, not always present on macOS
    if declare -F __ltrim_colon_completions >/dev/null; then
        __ltrim_colon_completions "$cur"
    fi

    # If there is only 1 completion and it is a flag with an = it will be completed
    # but we don't want a space after the =
    if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then
       compopt -o nospace
    fi
}

# The arguments should be in the form "ext1|ext2|extn"
__%[1]s_handle_filename_extension_flag()
{
    local ext="$1"
    _filedir "@(${ext})"
}

__%[1]s_handle_subdirs_in_dir_flag()
{
    local dir="$1"
    pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return
}

__%[1]s_handle_flag()
{
    __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"

    # if a command required a flag, and we found it, unset must_have_one_flag()
    local flagname=${words[c]}
    local flagvalue=""
    # if the word contained an =
    if [[ ${words[c]} == *"="* ]]; then
        flagvalue=${flagname#*=} # take in as flagvalue after the =
        flagname=${flagname%%=*} # strip everything after the =
        flagname="${flagname}=" # but put the = back
    fi
    __%[1]s_debug "${FUNCNAME[0]}: looking for ${flagname}"
    if __%[1]s_contains_word "${flagname}" "${must_have_one_flag[@]}"; then
        must_have_one_flag=()
    fi

    # if you set a flag which only applies to this command, don't show subcommands
    if __%[1]s_contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then
      commands=()
    fi

    # keep flag value with flagname as flaghash
    # flaghash variable is an associative array which is only supported in bash > 3.
    if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then
        if [ -n "${flagvalue}" ] ; then
            flaghash[${flagname}]=${flagvalue}
        elif [ -n "${words[ $((c+1)) ]}" ] ; then
            flaghash[${flagname}]=${words[ $((c+1)) ]}
        else
            flaghash[${flagname}]="true" # pad "true" for bool flag
        fi
    fi

    # skip the argument to a two word flag
    if [[ ${words[c]} != *"="* ]] && __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then
        __%[1]s_debug "${FUNCNAME[0]}: found a flag ${words[c]}, skip the next argument"
        c=$((c+1))
        # if we are looking for a flags value, don't show commands
        if [[ $c -eq $cword ]]; then
            commands=()
        fi
    fi

    c=$((c+1))

}

__%[1]s_handle_noun()
{
    __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"

    if __%[1]s_contains_word "${words[c]}" "${must_have_one_noun[@]}"; then
        must_have_one_noun=()
    elif __%[1]s_contains_word "${words[c]}" "${noun_aliases[@]}"; then
        must_have_one_noun=()
    fi

    nouns+=("${words[c]}")
    c=$((c+1))
}

__%[1]s_handle_command()
{
    __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"

    local next_command
    if [[ -n ${last_command} ]]; then
        next_command="_${last_command}_${words[c]//:/__}"
    else
        if [[ $c -eq 0 ]]; then
            next_command="_%[1]s_root_command"
        else
            next_command="_${words[c]//:/__}"
        fi
    fi
    c=$((c+1))
    __%[1]s_debug "${FUNCNAME[0]}: looking for ${next_command}"
    declare -F "$next_command" >/dev/null && $next_command
}

__%[1]s_handle_word()
{
    if [[ $c -ge $cword ]]; then
        __%[1]s_handle_reply
        return
    fi
    __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
    if [[ "${words[c]}" == -* ]]; then
        __%[1]s_handle_flag
    elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then
        __%[1]s_handle_command
    elif [[ $c -eq 0 ]]; then
        __%[1]s_handle_command
    elif __%[1]s_contains_word "${words[c]}" "${command_aliases[@]}"; then
        # aliashash variable is an associative array which is only supported in bash > 3.
        if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then
            words[c]=${aliashash[${words[c]}]}
            __%[1]s_handle_command
        else
            __%[1]s_handle_noun
        fi
    else
        __%[1]s_handle_noun
    fi
    __%[1]s_handle_word
}

`, name, ShellCompNoDescRequestCmd,
		ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
		ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name)))
}

func writePostscript(buf io.StringWriter, name string) {
	name = strings.ReplaceAll(name, ":", "__")
	WriteStringAndCheck(buf, fmt.Sprintf("__start_%s()\n", name))
	WriteStringAndCheck(buf, fmt.Sprintf(`{
    local cur prev words cword split
    declare -A flaghash 2>/dev/null || :
    declare -A aliashash 2>/dev/null || :
    if declare -F _init_completion >/dev/null 2>&1; then
        _init_completion -s || return
    else
        __%[1]s_init_completion -n "=" || return
    fi

    local c=0
    local flag_parsing_disabled=
    local flags=()
    local two_word_flags=()
    local local_nonpersistent_flags=()
    local flags_with_completion=()
    local flags_completion=()
    local commands=("%[1]s")
    local command_aliases=()
    local must_have_one_flag=()
    local must_have_one_noun=()
    local has_completion_function=""
    local last_command=""
    local nouns=()
    local noun_aliases=()

    __%[1]s_handle_word
}

`, name))
	WriteStringAndCheck(buf, fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then
    complete -o default -F __start_%s %s
else
    complete -o default -o nospace -F __start_%s %s
fi

`, name, name, name, name))
	WriteStringAndCheck(buf, "# ex: ts=4 sw=4 et filetype=sh\n")
}

func writeCommands(buf io.StringWriter, cmd *Command) {
	WriteStringAndCheck(buf, "    commands=()\n")
	for _, c := range cmd.Commands() {
		if !c.IsAvailableCommand() && c != cmd.helpCommand {
			continue
		}
		WriteStringAndCheck(buf, fmt.Sprintf("    commands+=(%q)\n", c.Name()))
		writeCmdAliases(buf, c)
	}
	WriteStringAndCheck(buf, "\n")
}

func writeFlagHandler(buf io.StringWriter, name string, annotations map[string][]string, cmd *Command) {
	for key, value := range annotations {
		switch key {
		case BashCompFilenameExt:
			WriteStringAndCheck(buf, fmt.Sprintf("    flags_with_completion+=(%q)\n", name))

			var ext string
			if len(value) > 0 {
				ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Root().Name()) + strings.Join(value, "|")
			} else {
				ext = "_filedir"
			}
			WriteStringAndCheck(buf, fmt.Sprintf("    flags_completion+=(%q)\n", ext))
		case BashCompCustom:
			WriteStringAndCheck(buf, fmt.Sprintf("    flags_with_completion+=(%q)\n", name))

			if len(value) > 0 {
				handlers := strings.Join(value, "; ")
				WriteStringAndCheck(buf, fmt.Sprintf("    flags_completion+=(%q)\n", handlers))
			} else {
				WriteStringAndCheck(buf, "    flags_completion+=(:)\n")
			}
		case BashCompSubdirsInDir:
			WriteStringAndCheck(buf, fmt.Sprintf("    flags_with_completion+=(%q)\n", name))

			var ext string
			if len(value) == 1 {
				ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Root().Name()) + value[0]
			} else {
				ext = "_filedir -d"
			}
			WriteStringAndCheck(buf, fmt.Sprintf("    flags_completion+=(%q)\n", ext))
		}
	}
}

const cbn = "\")\n"

func writeShortFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) {
	name := flag.Shorthand
	format := "    "
	if len(flag.NoOptDefVal) == 0 {
		format += "two_word_"
	}
	format += "flags+=(\"-%s" + cbn
	WriteStringAndCheck(buf, fmt.Sprintf(format, name))
	writeFlagHandler(buf, "-"+name, flag.Annotations, cmd)
}

func writeFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) {
	name := flag.Name
	format := "    flags+=(\"--%s"
	if len(flag.NoOptDefVal) == 0 {
		format += "="
	}
	format += cbn
	WriteStringAndCheck(buf, fmt.Sprintf(format, name))
	if len(flag.NoOptDefVal) == 0 {
		format = "    two_word_flags+=(\"--%s" + cbn
		WriteStringAndCheck(buf, fmt.Sprintf(format, name))
	}
	writeFlagHandler(buf, "--"+name, flag.Annotations, cmd)
}

func writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) {
	name := flag.Name
	format := "    local_nonpersistent_flags+=(\"--%[1]s" + cbn
	if len(flag.NoOptDefVal) == 0 {
		format += "    local_nonpersistent_flags+=(\"--%[1]s=" + cbn
	}
	WriteStringAndCheck(buf, fmt.Sprintf(format, name))
	if len(flag.Shorthand) > 0 {
		WriteStringAndCheck(buf, fmt.Sprintf("    local_nonpersistent_flags+=(\"-%s\")\n", flag.Shorthand))
	}
}

// prepareCustomAnnotationsForFlags setup annotations for go completions for registered flags
func prepareCustomAnnotationsForFlags(cmd *Command) {
	flagCompletionMutex.RLock()
	defer flagCompletionMutex.RUnlock()
	for flag := range flagCompletionFunctions {
		// Make sure the completion script calls the __*_go_custom_completion function for
		// every registered flag.  We need to do this here (and not when the flag was registered
		// for completion) so that we can know the root command name for the prefix
		// of __<prefix>_go_custom_completion
		if flag.Annotations == nil {
			flag.Annotations = map[string][]string{}
		}
		flag.Annotations[BashCompCustom] = []string{fmt.Sprintf("__%[1]s_handle_go_custom_completion", cmd.Root().Name())}
	}
}

func writeFlags(buf io.StringWriter, cmd *Command) {
	prepareCustomAnnotationsForFlags(cmd)
	WriteStringAndCheck(buf, `    flags=()
    two_word_flags=()
    local_nonpersistent_flags=()
    flags_with_completion=()
    flags_completion=()

`)

	if cmd.DisableFlagParsing {
		WriteStringAndCheck(buf, "    flag_parsing_disabled=1\n")
	}

	localNonPersistentFlags := cmd.LocalNonPersistentFlags()
	cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
		if nonCompletableFlag(flag) {
			return
		}
		writeFlag(buf, flag, cmd)
		if len(flag.Shorthand) > 0 {
			writeShortFlag(buf, flag, cmd)
		}
		// localNonPersistentFlags are used to stop the completion of subcommands when one is set
		// if TraverseChildren is true we should allow to complete subcommands
		if localNonPersistentFlags.Lookup(flag.Name) != nil && !cmd.Root().TraverseChildren {
			writeLocalNonPersistentFlag(buf, flag)
		}
	})
	cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
		if nonCompletableFlag(flag) {
			return
		}
		writeFlag(buf, flag, cmd)
		if len(flag.Shorthand) > 0 {
			writeShortFlag(buf, flag, cmd)
		}
	})

	WriteStringAndCheck(buf, "\n")
}

func writeRequiredFlag(buf io.StringWriter, cmd *Command) {
	WriteStringAndCheck(buf, "    must_have_one_flag=()\n")
	flags := cmd.NonInheritedFlags()
	flags.VisitAll(func(flag *pflag.Flag) {
		if nonCompletableFlag(flag) {
			return
		}
		if _, ok := flag.Annotations[BashCompOneRequiredFlag]; ok {
			format := "    must_have_one_flag+=(\"--%s"
			if flag.Value.Type() != "bool" {
				format += "="
			}
			format += cbn
			WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name))

			if len(flag.Shorthand) > 0 {
				WriteStringAndCheck(buf, fmt.Sprintf("    must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand))
			}
		}
	})
}

func writeRequiredNouns(buf io.StringWriter, cmd *Command) {
	WriteStringAndCheck(buf, "    must_have_one_noun=()\n")
	sort.Strings(cmd.ValidArgs)
	for _, value := range cmd.ValidArgs {
		// Remove any description that may be included following a tab character.
		// Descriptions are not supported by bash completion.
		value = strings.SplitN(value, "\t", 2)[0]
		WriteStringAndCheck(buf, fmt.Sprintf("    must_have_one_noun+=(%q)\n", value))
	}
	if cmd.ValidArgsFunction != nil {
		WriteStringAndCheck(buf, "    has_completion_function=1\n")
	}
}

func writeCmdAliases(buf io.StringWriter, cmd *Command) {
	if len(cmd.Aliases) == 0 {
		return
	}

	sort.Strings(cmd.Aliases)

	WriteStringAndCheck(buf, fmt.Sprint(`    if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then`, "\n"))
	for _, value := range cmd.Aliases {
		WriteStringAndCheck(buf, fmt.Sprintf("        command_aliases+=(%q)\n", value))
		WriteStringAndCheck(buf, fmt.Sprintf("        aliashash[%q]=%q\n", value, cmd.Name()))
	}
	WriteStringAndCheck(buf, `    fi`)
	WriteStringAndCheck(buf, "\n")
}
func writeArgAliases(buf io.StringWriter, cmd *Command) {
	WriteStringAndCheck(buf, "    noun_aliases=()\n")
	sort.Strings(cmd.ArgAliases)
	for _, value := range cmd.ArgAliases {
		WriteStringAndCheck(buf, fmt.Sprintf("    noun_aliases+=(%q)\n", value))
	}
}

func gen(buf io.StringWriter, cmd *Command) {
	for _, c := range cmd.Commands() {
		if !c.IsAvailableCommand() && c != cmd.helpCommand {
			continue
		}
		gen(buf, c)
	}
	commandName := cmd.CommandPath()
	commandName = strings.ReplaceAll(commandName, " ", "_")
	commandName = strings.ReplaceAll(commandName, ":", "__")

	if cmd.Root() == cmd {
		WriteStringAndCheck(buf, fmt.Sprintf("_%s_root_command()\n{\n", commandName))
	} else {
		WriteStringAndCheck(buf, fmt.Sprintf("_%s()\n{\n", commandName))
	}

	WriteStringAndCheck(buf, fmt.Sprintf("    last_command=%q\n", commandName))
	WriteStringAndCheck(buf, "\n")
	WriteStringAndCheck(buf, "    command_aliases=()\n")
	WriteStringAndCheck(buf, "\n")

	writeCommands(buf, cmd)
	writeFlags(buf, cmd)
	writeRequiredFlag(buf, cmd)
	writeRequiredNouns(buf, cmd)
	writeArgAliases(buf, cmd)
	WriteStringAndCheck(buf, "}\n\n")
}

// GenBashCompletion generates bash completion file and writes to the passed writer.
func (c *Command) GenBashCompletion(w io.Writer) error {
	buf := new(bytes.Buffer)
	writePreamble(buf, c.Name())
	if len(c.BashCompletionFunction) > 0 {
		buf.WriteString(c.BashCompletionFunction + "\n")
	}
	gen(buf, c)
	writePostscript(buf, c.Name())

	_, err := buf.WriteTo(w)
	return err
}

func nonCompletableFlag(flag *pflag.Flag) bool {
	return flag.Hidden || len(flag.Deprecated) > 0
}

// GenBashCompletionFile generates bash completion file.
func (c *Command) GenBashCompletionFile(filename string) error {
	outFile, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer outFile.Close()

	return c.GenBashCompletion(outFile)
}


================================================
FILE: bash_completionsV2.go
================================================
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cobra

import (
	"bytes"
	"fmt"
	"io"
	"os"
)

func (c *Command) genBashCompletion(w io.Writer, includeDesc bool) error {
	buf := new(bytes.Buffer)
	genBashComp(buf, c.Name(), includeDesc)
	_, err := buf.WriteTo(w)
	return err
}

func genBashComp(buf io.StringWriter, name string, includeDesc bool) {
	compCmd := ShellCompRequestCmd
	if !includeDesc {
		compCmd = ShellCompNoDescRequestCmd
	}

	WriteStringAndCheck(buf, fmt.Sprintf(`# bash completion V2 for %-36[1]s -*- shell-script -*-

__%[1]s_debug()
{
    if [[ -n ${BASH_COMP_DEBUG_FILE-} ]]; then
        echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
    fi
}

# Macs have bash3 for which the bash-completion package doesn't include
# _init_completion. This is a minimal version of that function.
__%[1]s_init_completion()
{
    COMPREPLY=()
    _get_comp_words_by_ref "$@" cur prev words cword
}

# This function calls the %[1]s program to obtain the completion
# results and the directive.  It fills the 'out' and 'directive' vars.
__%[1]s_get_completion_results() {
    local requestComp lastParam lastChar args

    # Prepare the command to request completions for the program.
    # Calling ${words[0]} instead of directly %[1]s allows handling aliases
    args=("${words[@]:1}")
    requestComp="${words[0]} %[2]s ${args[*]}"

    lastParam=${words[$((${#words[@]}-1))]}
    lastChar=${lastParam:$((${#lastParam}-1)):1}
    __%[1]s_debug "lastParam ${lastParam}, lastChar ${lastChar}"

    if [[ -z ${cur} && ${lastChar} != = ]]; then
        # If the last parameter is complete (there is a space following it)
        # We add an extra empty parameter so we can indicate this to the go method.
        __%[1]s_debug "Adding extra empty parameter"
        requestComp="${requestComp} ''"
    fi

    # When completing a flag with an = (e.g., %[1]s -n=<TAB>)
    # bash focuses on the part after the =, so we need to remove
    # the flag part from $cur
    if [[ ${cur} == -*=* ]]; then
        cur="${cur#*=}"
    fi

    __%[1]s_debug "Calling ${requestComp}"
    # Use eval to handle any environment variables and such
    out=$(eval "${requestComp}" 2>/dev/null)

    # Extract the directive integer at the very end of the output following a colon (:)
    directive=${out##*:}
    # Remove the directive
    out=${out%%:*}
    if [[ ${directive} == "${out}" ]]; then
        # There is not directive specified
        directive=0
    fi
    __%[1]s_debug "The completion directive is: ${directive}"
    __%[1]s_debug "The completions are: ${out}"
}

__%[1]s_process_completion_results() {
    local shellCompDirectiveError=%[3]d
    local shellCompDirectiveNoSpace=%[4]d
    local shellCompDirectiveNoFileComp=%[5]d
    local shellCompDirectiveFilterFileExt=%[6]d
    local shellCompDirectiveFilterDirs=%[7]d
    local shellCompDirectiveKeepOrder=%[8]d

    if (((directive & shellCompDirectiveError) != 0)); then
        # Error code.  No completion.
        __%[1]s_debug "Received error from custom completion go code"
        return
    else
        if (((directive & shellCompDirectiveNoSpace) != 0)); then
            if [[ $(type -t compopt) == builtin ]]; then
                __%[1]s_debug "Activating no space"
                compopt -o nospace
            else
                __%[1]s_debug "No space directive not supported in this version of bash"
            fi
        fi
        if (((directive & shellCompDirectiveKeepOrder) != 0)); then
            if [[ $(type -t compopt) == builtin ]]; then
                # no sort isn't supported for bash less than < 4.4
                if [[ ${BASH_VERSINFO[0]} -lt 4 || ( ${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -lt 4 ) ]]; then
                    __%[1]s_debug "No sort directive not supported in this version of bash"
                else
                    __%[1]s_debug "Activating keep order"
                    compopt -o nosort
                fi
            else
                __%[1]s_debug "No sort directive not supported in this version of bash"
            fi
        fi
        if (((directive & shellCompDirectiveNoFileComp) != 0)); then
            if [[ $(type -t compopt) == builtin ]]; then
                __%[1]s_debug "Activating no file completion"
                compopt +o default
            else
                __%[1]s_debug "No file completion directive not supported in this version of bash"
            fi
        fi
    fi

    # Separate activeHelp from normal completions
    local completions=()
    local activeHelp=()
    __%[1]s_extract_activeHelp

    if (((directive & shellCompDirectiveFilterFileExt) != 0)); then
        # File extension filtering
        local fullFilter="" filter filteringCmd

        # Do not use quotes around the $completions variable or else newline
        # characters will be kept.
        for filter in ${completions[*]}; do
            fullFilter+="$filter|"
        done

        filteringCmd="_filedir $fullFilter"
        __%[1]s_debug "File filtering command: $filteringCmd"
        $filteringCmd
    elif (((directive & shellCompDirectiveFilterDirs) != 0)); then
        # File completion for directories only

        local subdir
        subdir=${completions[0]}
        if [[ -n $subdir ]]; then
            __%[1]s_debug "Listing directories in $subdir"
            pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return
        else
            __%[1]s_debug "Listing directories in ."
            _filedir -d
        fi
    else
        __%[1]s_handle_completion_types
    fi

    __%[1]s_handle_special_char "$cur" :
    __%[1]s_handle_special_char "$cur" =

    # Print the activeHelp statements before we finish
    __%[1]s_handle_activeHelp
}

__%[1]s_handle_activeHelp() {
    # Print the activeHelp statements
    if ((${#activeHelp[*]} != 0)); then
        if [ -z $COMP_TYPE ]; then
            # Bash v3 does not set the COMP_TYPE variable.
            printf "\n";
            printf "%%s\n" "${activeHelp[@]}"
            printf "\n"
            __%[1]s_reprint_commandLine
            return
        fi

        # Only print ActiveHelp on the second TAB press
        if [ $COMP_TYPE -eq 63 ]; then
            printf "\n"
            printf "%%s\n" "${activeHelp[@]}"

            if ((${#COMPREPLY[*]} == 0)); then
                # When there are no completion choices from the program, file completion
                # may kick in if the program has not disabled it; in such a case, we want
                # to know if any files will match what the user typed, so that we know if
                # there will be completions presented, so that we know how to handle ActiveHelp.
                # To find out, we actually trigger the file completion ourselves;
                # the call to _filedir will fill COMPREPLY if files match.
                if (((directive & shellCompDirectiveNoFileComp) == 0)); then
                    __%[1]s_debug "Listing files"
                    _filedir
                fi
            fi

            if ((${#COMPREPLY[*]} != 0)); then
                # If there are completion choices to be shown, print a delimiter.
                # Re-printing the command-line will automatically be done
                # by the shell when it prints the completion choices.
                printf -- "--"
            else
                # When there are no completion choices at all, we need
                # to re-print the command-line since the shell will
                # not be doing it itself.
                __%[1]s_reprint_commandLine
            fi
        elif [ $COMP_TYPE -eq 37 ] || [ $COMP_TYPE -eq 42 ]; then
            # For completion type: menu-complete/menu-complete-backward and insert-completions
            # the completions are immediately inserted into the command-line, so we first
            # print the activeHelp message and reprint the command-line since the shell won't.
            printf "\n"
            printf "%%s\n" "${activeHelp[@]}"

            __%[1]s_reprint_commandLine
        fi
    fi
}

__%[1]s_reprint_commandLine() {
    # The prompt format is only available from bash 4.4.
    # We test if it is available before using it.
    if (x=${PS1@P}) 2> /dev/null; then
        printf "%%s" "${PS1@P}${COMP_LINE[@]}"
    else
        # Can't print the prompt.  Just print the
        # text the user had typed, it is workable enough.
        printf "%%s" "${COMP_LINE[@]}"
    fi
}

# Separate activeHelp lines from real completions.
# Fills the $activeHelp and $completions arrays.
__%[1]s_extract_activeHelp() {
    local activeHelpMarker="%[9]s"
    local endIndex=${#activeHelpMarker}

    while IFS='' read -r comp; do
        [[ -z $comp ]] && continue

        if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then
            comp=${comp:endIndex}
            __%[1]s_debug "ActiveHelp found: $comp"
            if [[ -n $comp ]]; then
                activeHelp+=("$comp")
            fi
        else
            # Not an activeHelp line but a normal completion
            completions+=("$comp")
        fi
    done <<<"${out}"
}

__%[1]s_handle_completion_types() {
    __%[1]s_debug "__%[1]s_handle_completion_types: COMP_TYPE is $COMP_TYPE"

    case $COMP_TYPE in
    37|42)
        # Type: menu-complete/menu-complete-backward and insert-completions
        # If the user requested inserting one completion at a time, or all
        # completions at once on the command-line we must remove the descriptions.
        # https://github.com/spf13/cobra/issues/1508

        # If there are no completions, we don't need to do anything
        (( ${#completions[@]} == 0 )) && return 0

        local tab=$'\t'

        # Strip any description and escape the completion to handled special characters
        IFS=$'\n' read -ra completions -d '' < <(printf "%%q\n" "${completions[@]%%%%$tab*}")

        # Only consider the completions that match
        IFS=$'\n' read -ra COMPREPLY -d '' < <(IFS=$'\n'; compgen -W "${completions[*]}" -- "${cur}")

        # compgen looses the escaping so we need to escape all completions again since they will
        # all be inserted on the command-line.
        IFS=$'\n' read -ra COMPREPLY -d '' < <(printf "%%q\n" "${COMPREPLY[@]}")
        ;;

    *)
        # Type: complete (normal completion)
        __%[1]s_handle_standard_completion_case
        ;;
    esac
}

__%[1]s_handle_standard_completion_case() {
    local tab=$'\t'

    # If there are no completions, we don't need to do anything
    (( ${#completions[@]} == 0 )) && return 0

    # Short circuit to optimize if we don't have descriptions
    if [[ "${completions[*]}" != *$tab* ]]; then
        # First, escape the completions to handle special characters
        IFS=$'\n' read -ra completions -d '' < <(printf "%%q\n" "${completions[@]}")
        # Only consider the completions that match what the user typed
        IFS=$'\n' read -ra COMPREPLY -d '' < <(IFS=$'\n'; compgen -W "${completions[*]}" -- "${cur}")

        # compgen looses the escaping so, if there is only a single completion, we need to
        # escape it again because it will be inserted on the command-line.  If there are multiple
        # completions, we don't want to escape them because they will be printed in a list
        # and we don't want to show escape characters in that list.
        if (( ${#COMPREPLY[@]} == 1 )); then
            COMPREPLY[0]=$(printf "%%q" "${COMPREPLY[0]}")
        fi
        return 0
    fi

    local longest=0
    local compline
    # Look for the longest completion so that we can format things nicely
    for compline in "${completions[@]}"; do
        [[ -z $compline ]] && continue

        # Before checking if the completion matches what the user typed,
        # we need to strip any description and escape the completion to handle special
        # characters because those escape characters are part of what the user typed.
        # Don't call "printf" in a sub-shell because it will be much slower
        # since we are in a loop.
        printf -v comp "%%q" "${compline%%%%$tab*}" &>/dev/null || comp=$(printf "%%q" "${compline%%%%$tab*}")

        # Only consider the completions that match
        [[ $comp == "$cur"* ]] || continue

        # The completions matches.  Add it to the list of full completions including
        # its description.  We don't escape the completion because it may get printed
        # in a list if there are more than one and we don't want show escape characters
        # in that list.
        COMPREPLY+=("$compline")

        # Strip any description before checking the length, and again, don't escape
        # the completion because this length is only used when printing the completions
        # in a list and we don't want show escape characters in that list.
        comp=${compline%%%%$tab*}
        if ((${#comp}>longest)); then
            longest=${#comp}
        fi
    done

    # If there is a single completion left, remove the description text and escape any special characters
    if ((${#COMPREPLY[*]} == 1)); then
        __%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}"
        COMPREPLY[0]=$(printf "%%q" "${COMPREPLY[0]%%%%$tab*}")
        __%[1]s_debug "Removed description from single completion, which is now: ${COMPREPLY[0]}"
    else
        # Format the descriptions
        __%[1]s_format_comp_descriptions $longest
    fi
}

__%[1]s_handle_special_char()
{
    local comp="$1"
    local char=$2
    if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then
        local word=${comp%%"${comp##*${char}}"}
        local idx=${#COMPREPLY[*]}
        while ((--idx >= 0)); do
            COMPREPLY[idx]=${COMPREPLY[idx]#"$word"}
        done
    fi
}

__%[1]s_format_comp_descriptions()
{
    local tab=$'\t'
    local comp desc maxdesclength
    local longest=$1

    local i ci
    for ci in ${!COMPREPLY[*]}; do
        comp=${COMPREPLY[ci]}
        # Properly format the description string which follows a tab character if there is one
        if [[ "$comp" == *$tab* ]]; then
            __%[1]s_debug "Original comp: $comp"
            desc=${comp#*$tab}
            comp=${comp%%%%$tab*}

            # $COLUMNS stores the current shell width.
            # Remove an extra 4 because we add 2 spaces and 2 parentheses.
            maxdesclength=$(( COLUMNS - longest - 4 ))

            # Make sure we can fit a description of at least 8 characters
            # if we are to align the descriptions.
            if ((maxdesclength > 8)); then
                # Add the proper number of spaces to align the descriptions
                for ((i = ${#comp} ; i < longest ; i++)); do
                    comp+=" "
                done
            else
                # Don't pad the descriptions so we can fit more text after the completion
                maxdesclength=$(( COLUMNS - ${#comp} - 4 ))
            fi

            # If there is enough space for any description text,
            # truncate the descriptions that are too long for the shell width
            if ((maxdesclength > 0)); then
                if ((${#desc} > maxdesclength)); then
                    desc=${desc:0:$(( maxdesclength - 1 ))}
                    desc+="…"
                fi
                comp+="  ($desc)"
            fi
            COMPREPLY[ci]=$comp
            __%[1]s_debug "Final comp: $comp"
        fi
    done
}

__start_%[1]s()
{
    local cur prev words cword split

    COMPREPLY=()

    # Call _init_completion from the bash-completion package
    # to prepare the arguments properly
    if declare -F _init_completion >/dev/null 2>&1; then
        _init_completion -n =: || return
    else
        __%[1]s_init_completion -n =: || return
    fi

    __%[1]s_debug
    __%[1]s_debug "========= starting completion logic =========="
    __%[1]s_debug "cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword"

    # The user could have moved the cursor backwards on the command-line.
    # We need to trigger completion from the $cword location, so we need
    # to truncate the command-line ($words) up to the $cword location.
    words=("${words[@]:0:$cword+1}")
    __%[1]s_debug "Truncated words[*]: ${words[*]},"

    local out directive
    __%[1]s_get_completion_results
    __%[1]s_process_completion_results
}

if [[ $(type -t compopt) = "builtin" ]]; then
    complete -o default -F __start_%[1]s %[1]s
else
    complete -o default -o nospace -F __start_%[1]s %[1]s
fi

# ex: ts=4 sw=4 et filetype=sh
`, name, compCmd,
		ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
		ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder,
		activeHelpMarker))
}

// GenBashCompletionFileV2 generates Bash completion version 2.
func (c *Command) GenBashCompletionFileV2(filename string, includeDesc bool) error {
	outFile, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer outFile.Close()

	return c.GenBashCompletionV2(outFile, includeDesc)
}

// GenBashCompletionV2 generates Bash completion file version 2
// and writes it to the passed writer.
func (c *Command) GenBashCompletionV2(w io.Writer, includeDesc bool) error {
	return c.genBashCompletion(w, includeDesc)
}


================================================
FILE: bash_completionsV2_test.go
================================================
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cobra

import (
	"bytes"
	"fmt"
	"testing"
)

func TestBashCompletionV2WithActiveHelp(t *testing.T) {
	c := &Command{Use: "c", Run: emptyRun}

	buf := new(bytes.Buffer)
	assertNoErr(t, c.GenBashCompletionV2(buf, true))
	output := buf.String()

	// check that active help is not being disabled
	activeHelpVar := activeHelpEnvVar(c.Name())
	checkOmit(t, output, fmt.Sprintf("%s=0", activeHelpVar))
}


================================================
FILE: bash_completions_test.go
================================================
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cobra

import (
	"bytes"
	"fmt"
	"os"
	"os/exec"
	"regexp"
	"strings"
	"testing"
)

func checkOmit(t *testing.T, found, unexpected string) {
	if strings.Contains(found, unexpected) {
		t.Errorf("Got: %q\nBut should not have!\n", unexpected)
	}
}

func check(t *testing.T, found, expected string) {
	if !strings.Contains(found, expected) {
		t.Errorf("Expecting to contain: \n %q\nGot:\n %q\n", expected, found)
	}
}

func checkNumOccurrences(t *testing.T, found, expected string, expectedOccurrences int) {
	numOccurrences := strings.Count(found, expected)
	if numOccurrences != expectedOccurrences {
		t.Errorf("Expecting to contain %d occurrences of: \n %q\nGot %d:\n %q\n", expectedOccurrences, expected, numOccurrences, found)
	}
}

func checkRegex(t *testing.T, found, pattern string) {
	matched, err := regexp.MatchString(pattern, found)
	if err != nil {
		t.Errorf("Error thrown performing MatchString: \n %s\n", err)
	}
	if !matched {
		t.Errorf("Expecting to match: \n %q\nGot:\n %q\n", pattern, found)
	}
}

func runShellCheck(s string) error {
	cmd := exec.Command("shellcheck", "-s", "bash", "-", "-e",
		"SC2034", // PREFIX appears unused. Verify it or export it.
	)
	cmd.Stderr = os.Stderr
	cmd.Stdout = os.Stdout

	stdin, err := cmd.StdinPipe()
	if err != nil {
		return err
	}
	go func() {
		_, err := stdin.Write([]byte(s))
		CheckErr(err)

		stdin.Close()
	}()

	return cmd.Run()
}

// World worst custom function, just keep telling you to enter hello!
const bashCompletionFunc = `__root_custom_func() {
	COMPREPLY=( "hello" )
}
`

func TestBashCompletions(t *testing.T) {
	rootCmd := &Command{
		Use:                    "root",
		ArgAliases:             []string{"pods", "nodes", "services", "replicationcontrollers", "po", "no", "svc", "rc"},
		ValidArgs:              []string{"pod", "node", "service", "replicationcontroller"},
		BashCompletionFunction: bashCompletionFunc,
		Run:                    emptyRun,
	}
	rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")
	assertNoErr(t, rootCmd.MarkFlagRequired("introot"))

	// Filename.
	rootCmd.Flags().String("filename", "", "Enter a filename")
	assertNoErr(t, rootCmd.MarkFlagFilename("filename", "json", "yaml", "yml"))

	// Persistent filename.
	rootCmd.PersistentFlags().String("persistent-filename", "", "Enter a filename")
	assertNoErr(t, rootCmd.MarkPersistentFlagFilename("persistent-filename"))
	assertNoErr(t, rootCmd.MarkPersistentFlagRequired("persistent-filename"))

	// Filename extensions.
	rootCmd.Flags().String("filename-ext", "", "Enter a filename (extension limited)")
	assertNoErr(t, rootCmd.MarkFlagFilename("filename-ext"))
	rootCmd.Flags().String("custom", "", "Enter a filename (extension limited)")
	assertNoErr(t, rootCmd.MarkFlagCustom("custom", "__complete_custom"))

	// Subdirectories in a given directory.
	rootCmd.Flags().String("theme", "", "theme to use (located in /themes/THEMENAME/)")
	assertNoErr(t, rootCmd.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"}))

	// For two word flags check
	rootCmd.Flags().StringP("two", "t", "", "this is two word flags")
	rootCmd.Flags().BoolP("two-w-default", "T", false, "this is not two word flags")

	echoCmd := &Command{
		Use:     "echo [string to echo]",
		Aliases: []string{"say"},
		Short:   "Echo anything to the screen",
		Long:    "an utterly useless command for testing.",
		Example: "Just run cobra-test echo",
		Run:     emptyRun,
	}

	echoCmd.Flags().String("filename", "", "Enter a filename")
	assertNoErr(t, echoCmd.MarkFlagFilename("filename", "json", "yaml", "yml"))
	echoCmd.Flags().String("config", "", "config to use (located in /config/PROFILE/)")
	assertNoErr(t, echoCmd.Flags().SetAnnotation("config", BashCompSubdirsInDir, []string{"config"}))

	printCmd := &Command{
		Use:   "print [string to print]",
		Args:  MinimumNArgs(1),
		Short: "Print anything to the screen",
		Long:  "an absolutely utterly useless command for testing.",
		Run:   emptyRun,
	}

	deprecatedCmd := &Command{
		Use:        "deprecated [can't do anything here]",
		Args:       NoArgs,
		Short:      "A command which is deprecated",
		Long:       "an absolutely utterly useless command for testing deprecation!.",
		Deprecated: "Please use echo instead",
		Run:        emptyRun,
	}

	colonCmd := &Command{
		Use: "cmd:colon",
		Run: emptyRun,
	}

	timesCmd := &Command{
		Use:        "times [# times] [string to echo]",
		SuggestFor: []string{"counts"},
		Args:       OnlyValidArgs,
		ValidArgs:  []string{"one", "two", "three", "four"},
		Short:      "Echo anything to the screen more times",
		Long:       "a slightly useless command for testing.",
		Run:        emptyRun,
	}

	echoCmd.AddCommand(timesCmd)
	rootCmd.AddCommand(echoCmd, printCmd, deprecatedCmd, colonCmd)

	buf := new(bytes.Buffer)
	assertNoErr(t, rootCmd.GenBashCompletion(buf))
	output := buf.String()

	check(t, output, "_root")
	check(t, output, "_root_echo")
	check(t, output, "_root_echo_times")
	check(t, output, "_root_print")
	check(t, output, "_root_cmd__colon")

	// check for required flags
	check(t, output, `must_have_one_flag+=("--introot=")`)
	check(t, output, `must_have_one_flag+=("--persistent-filename=")`)
	// check for custom completion function with both qualified and unqualified name
	checkNumOccurrences(t, output, `__custom_func`, 2)      // 1. check existence, 2. invoke
	checkNumOccurrences(t, output, `__root_custom_func`, 3) // 1. check existence, 2. invoke, 3. actual definition
	// check for custom completion function body
	check(t, output, `COMPREPLY=( "hello" )`)
	// check for required nouns
	check(t, output, `must_have_one_noun+=("pod")`)
	// check for noun aliases
	check(t, output, `noun_aliases+=("pods")`)
	check(t, output, `noun_aliases+=("rc")`)
	checkOmit(t, output, `must_have_one_noun+=("pods")`)
	// check for filename extension flags
	check(t, output, `flags_completion+=("_filedir")`)
	// check for filename extension flags
	check(t, output, `must_have_one_noun+=("three")`)
	// check for filename extension flags
	check(t, output, fmt.Sprintf(`flags_completion+=("__%s_handle_filename_extension_flag json|yaml|yml")`, rootCmd.Name()))
	// check for filename extension flags in a subcommand
	checkRegex(t, output, fmt.Sprintf(`_root_echo\(\)\n{[^}]*flags_completion\+=\("__%s_handle_filename_extension_flag json\|yaml\|yml"\)`, rootCmd.Name()))
	// check for custom flags
	check(t, output, `flags_completion+=("__complete_custom")`)
	// check for subdirs_in_dir flags
	check(t, output, fmt.Sprintf(`flags_completion+=("__%s_handle_subdirs_in_dir_flag themes")`, rootCmd.Name()))
	// check for subdirs_in_dir flags in a subcommand
	checkRegex(t, output, fmt.Sprintf(`_root_echo\(\)\n{[^}]*flags_completion\+=\("__%s_handle_subdirs_in_dir_flag config"\)`, rootCmd.Name()))

	// check two word flags
	check(t, output, `two_word_flags+=("--two")`)
	check(t, output, `two_word_flags+=("-t")`)
	checkOmit(t, output, `two_word_flags+=("--two-w-default")`)
	checkOmit(t, output, `two_word_flags+=("-T")`)

	// check local nonpersistent flag
	check(t, output, `local_nonpersistent_flags+=("--two")`)
	check(t, output, `local_nonpersistent_flags+=("--two=")`)
	check(t, output, `local_nonpersistent_flags+=("-t")`)
	check(t, output, `local_nonpersistent_flags+=("--two-w-default")`)
	check(t, output, `local_nonpersistent_flags+=("-T")`)

	checkOmit(t, output, deprecatedCmd.Name())

	// If available, run shellcheck against the script.
	if err := exec.Command("which", "shellcheck").Run(); err != nil {
		return
	}
	if err := runShellCheck(output); err != nil {
		t.Fatalf("shellcheck failed: %v", err)
	}
}

func TestBashCompletionHiddenFlag(t *testing.T) {
	c := &Command{Use: "c", Run: emptyRun}

	const flagName = "hiddenFlag"
	c.Flags().Bool(flagName, false, "")
	assertNoErr(t, c.Flags().MarkHidden(flagName))

	buf := new(bytes.Buffer)
	assertNoErr(t, c.GenBashCompletion(buf))
	output := buf.String()

	if strings.Contains(output, flagName) {
		t.Errorf("Expected completion to not include %q flag: Got %v", flagName, output)
	}
}

func TestBashCompletionDeprecatedFlag(t *testing.T) {
	c := &Command{Use: "c", Run: emptyRun}

	const flagName = "deprecated-flag"
	c.Flags().Bool(flagName, false, "")
	assertNoErr(t, c.Flags().MarkDeprecated(flagName, "use --not-deprecated instead"))

	buf := new(bytes.Buffer)
	assertNoErr(t, c.GenBashCompletion(buf))
	output := buf.String()

	if strings.Contains(output, flagName) {
		t.Errorf("expected completion to not include %q flag: Got %v", flagName, output)
	}
}

func TestBashCompletionTraverseChildren(t *testing.T) {
	c := &Command{Use: "c", Run: emptyRun, TraverseChildren: true}

	c.Flags().StringP("string-flag", "s", "", "string flag")
	c.Flags().BoolP("bool-flag", "b", false, "bool flag")

	buf := new(bytes.Buffer)
	assertNoErr(t, c.GenBashCompletion(buf))
	output := buf.String()

	// check that local nonpersistent flag are not set since we have TraverseChildren set to true
	checkOmit(t, output, `local_nonpersistent_flags+=("--string-flag")`)
	checkOmit(t, output, `local_nonpersistent_flags+=("--string-flag=")`)
	checkOmit(t, output, `local_nonpersistent_flags+=("-s")`)
	checkOmit(t, output, `local_nonpersistent_flags+=("--bool-flag")`)
	checkOmit(t, output, `local_nonpersistent_flags+=("-b")`)
}

func TestBashCompletionNoActiveHelp(t *testing.T) {
	c := &Command{Use: "c", Run: emptyRun}

	buf := new(bytes.Buffer)
	assertNoErr(t, c.GenBashCompletion(buf))
	output := buf.String()

	// check that active help is being disabled
	activeHelpVar := activeHelpEnvVar(c.Name())
	check(t, output, fmt.Sprintf("%s=0", activeHelpVar))
}


================================================
FILE: cobra.go
================================================
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Commands similar to git, go tools and other modern CLI tools
// inspired by go, go-Commander, gh and subcommand

package cobra

import (
	"fmt"
	"io"
	"os"
	"reflect"
	"strconv"
	"strings"
	"text/template"
	"time"
	"unicode"
)

var templateFuncs = template.FuncMap{
	"trim":                    strings.TrimSpace,
	"trimRightSpace":          trimRightSpace,
	"trimTrailingWhitespaces": trimRightSpace,
	"appendIfNotPresent":      appendIfNotPresent,
	"rpad":                    rpad,
	"gt":                      Gt,
	"eq":                      Eq,
}

var initializers []func()
var finalizers []func()

const (
	defaultPrefixMatching   = false
	defaultCommandSorting   = true
	defaultCaseInsensitive  = false
	defaultTraverseRunHooks = false
)

// EnablePrefixMatching allows setting automatic prefix matching. Automatic prefix matching can be a dangerous thing
// to automatically enable in CLI tools.
// Set this to true to enable it.
var EnablePrefixMatching = defaultPrefixMatching

// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default.
// To disable sorting, set it to false.
var EnableCommandSorting = defaultCommandSorting

// EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default)
var EnableCaseInsensitive = defaultCaseInsensitive

// EnableTraverseRunHooks executes persistent pre-run and post-run hooks from all parents.
// By default this is disabled, which means only the first run hook to be found is executed.
var EnableTraverseRunHooks = defaultTraverseRunHooks

// MousetrapHelpText enables an information splash screen on Windows
// if the CLI is started from explorer.exe.
// To disable the mousetrap, just set this variable to blank string ("").
// Works only on Microsoft Windows.
var MousetrapHelpText = `This is a command line tool.

You need to open cmd.exe and run it from there.
`

// MousetrapDisplayDuration controls how long the MousetrapHelpText message is displayed on Windows
// if the CLI is started from explorer.exe. Set to 0 to wait for the return key to be pressed.
// To disable the mousetrap, just set MousetrapHelpText to blank string ("").
// Works only on Microsoft Windows.
var MousetrapDisplayDuration = 5 * time.Second

// AddTemplateFunc adds a template function that's available to Usage and Help
// template generation.
func AddTemplateFunc(name string, tmplFunc interface{}) {
	templateFuncs[name] = tmplFunc
}

// AddTemplateFuncs adds multiple template functions that are available to Usage and
// Help template generation.
func AddTemplateFuncs(tmplFuncs template.FuncMap) {
	for k, v := range tmplFuncs {
		templateFuncs[k] = v
	}
}

// OnInitialize sets the passed functions to be run when each command's
// Execute method is called.
func OnInitialize(y ...func()) {
	initializers = append(initializers, y...)
}

// OnFinalize sets the passed functions to be run when each command's
// Execute method is terminated.
func OnFinalize(y ...func()) {
	finalizers = append(finalizers, y...)
}

// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.

// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as
// ints and then compared.
func Gt(a interface{}, b interface{}) bool {
	var left, right int64
	av := reflect.ValueOf(a)

	switch av.Kind() {
	case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
		left = int64(av.Len())
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		left = av.Int()
	case reflect.String:
		left, _ = strconv.ParseInt(av.String(), 10, 64)
	}

	bv := reflect.ValueOf(b)

	switch bv.Kind() {
	case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
		right = int64(bv.Len())
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		right = bv.Int()
	case reflect.String:
		right, _ = strconv.ParseInt(bv.String(), 10, 64)
	}

	return left > right
}

// FIXME Eq is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.

// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
func Eq(a interface{}, b interface{}) bool {
	av := reflect.ValueOf(a)
	bv := reflect.ValueOf(b)

	switch av.Kind() {
	case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
		panic("Eq called on unsupported type")
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return av.Int() == bv.Int()
	case reflect.String:
		return av.String() == bv.String()
	}
	return false
}

func trimRightSpace(s string) string {
	return strings.TrimRightFunc(s, unicode.IsSpace)
}

// FIXME appendIfNotPresent is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.

// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s.
func appendIfNotPresent(s, stringToAppend string) string {
	if strings.Contains(s, stringToAppend) {
		return s
	}
	return s + " " + stringToAppend
}

// rpad adds padding to the right of a string.
func rpad(s string, padding int) string {
	formattedString := fmt.Sprintf("%%-%ds", padding)
	return fmt.Sprintf(formattedString, s)
}

func tmpl(text string) *tmplFunc {
	return &tmplFunc{
		tmpl: text,
		fn: func(w io.Writer, data interface{}) error {
			t := template.New("top")
			t.Funcs(templateFuncs)
			template.Must(t.Parse(text))
			return t.Execute(w, data)
		},
	}
}

// ld compares two strings and returns the levenshtein distance between them.
func ld(s, t string, ignoreCase bool) int {
	if ignoreCase {
		s = strings.ToLower(s)
		t = strings.ToLower(t)
	}
	d := make([][]int, len(s)+1)
	for i := range d {
		d[i] = make([]int, len(t)+1)
		d[i][0] = i
	}
	for j := range d[0] {
		d[0][j] = j
	}
	for j := 1; j <= len(t); j++ {
		for i := 1; i <= len(s); i++ {
			if s[i-1] == t[j-1] {
				d[i][j] = d[i-1][j-1]
			} else {
				min := d[i-1][j]
				if d[i][j-1] < min {
					min = d[i][j-1]
				}
				if d[i-1][j-1] < min {
					min = d[i-1][j-1]
				}
				d[i][j] = min + 1
			}
		}

	}
	return d[len(s)][len(t)]
}

func stringInSlice(a string, list []string) bool {
	for _, b := range list {
		if b == a {
			return true
		}
	}
	return false
}

// CheckErr prints the msg with the prefix 'Error:' and exits with error code 1. If the msg is nil, it does nothing.
func CheckErr(msg interface{}) {
	if msg != nil {
		fmt.Fprintln(os.Stderr, "Error:", msg)
		os.Exit(1)
	}
}

// WriteStringAndCheck writes a string into a buffer, and checks if the error is not nil.
func WriteStringAndCheck(b io.StringWriter, s string) {
	_, err := b.WriteString(s)
	CheckErr(err)
}


================================================
FILE: cobra_test.go
================================================
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cobra

import (
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"testing"
	"text/template"
)

func assertNoErr(t *testing.T, e error) {
	if e != nil {
		t.Error(e)
	}
}

func TestAddTemplateFunctions(t *testing.T) {
	AddTemplateFunc("t", func() bool { return true })
	AddTemplateFuncs(template.FuncMap{
		"f": func() bool { return false },
		"h": func() string { return "Hello," },
		"w": func() string { return "world." }})

	c := &Command{}
	c.SetUsageTemplate(`{{if t}}{{h}}{{end}}{{if f}}{{h}}{{end}} {{w}}`)

	const expected = "Hello, world."
	if got := c.UsageString(); got != expected {
		t.Errorf("Expected UsageString: %v\nGot: %v", expected, got)
	}
}

func TestLevenshteinDistance(t *testing.T) {
	tests := []struct {
		name       string
		s          string
		t          string
		ignoreCase bool
		expected   int
	}{
		{
			name:       "Equal strings (case-sensitive)",
			s:          "hello",
			t:          "hello",
			ignoreCase: false,
			expected:   0,
		},
		{
			name:       "Equal strings (case-insensitive)",
			s:          "Hello",
			t:          "hello",
			ignoreCase: true,
			expected:   0,
		},
		{
			name:       "Different strings (case-sensitive)",
			s:          "kitten",
			t:          "sitting",
			ignoreCase: false,
			expected:   3,
		},
		{
			name:       "Different strings (case-insensitive)",
			s:          "Kitten",
			t:          "Sitting",
			ignoreCase: true,
			expected:   3,
		},
		{
			name:       "Empty strings",
			s:          "",
			t:          "",
			ignoreCase: false,
			expected:   0,
		},
		{
			name:       "One empty string",
			s:          "abc",
			t:          "",
			ignoreCase: false,
			expected:   3,
		},
		{
			name:       "Both empty strings",
			s:          "",
			t:          "",
			ignoreCase: true,
			expected:   0,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// Act
			got := ld(tt.s, tt.t, tt.ignoreCase)

			// Assert
			if got != tt.expected {
				t.Errorf("Expected ld: %v\nGot: %v", tt.expected, got)
			}
		})
	}
}

func TestStringInSlice(t *testing.T) {
	tests := []struct {
		name     string
		a        string
		list     []string
		expected bool
	}{
		{
			name:     "String in slice (case-sensitive)",
			a:        "apple",
			list:     []string{"orange", "banana", "apple", "grape"},
			expected: true,
		},
		{
			name:     "String not in slice (case-sensitive)",
			a:        "pear",
			list:     []string{"orange", "banana", "apple", "grape"},
			expected: false,
		},
		{
			name:     "String in slice (case-insensitive)",
			a:        "APPLE",
			list:     []string{"orange", "banana", "apple", "grape"},
			expected: false,
		},
		{
			name:     "Empty slice",
			a:        "apple",
			list:     []string{},
			expected: false,
		},
		{
			name:     "Empty string",
			a:        "",
			list:     []string{"orange", "banana", "apple", "grape"},
			expected: false,
		},
		{
			name:     "Empty strings match",
			a:        "",
			list:     []string{"orange", ""},
			expected: true,
		},
		{
			name:     "Empty string in empty slice",
			a:        "",
			list:     []string{},
			expected: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// Act
			got := stringInSlice(tt.a, tt.list)

			// Assert
			if got != tt.expected {
				t.Errorf("Expected stringInSlice: %v\nGot: %v", tt.expected, got)
			}
		})
	}
}

func TestRpad(t *testing.T) {
	tests := []struct {
		name        string
		inputString string
		padding     int
		expected    string
	}{
		{
			name:        "Padding required",
			inputString: "Hello",
			padding:     10,
			expected:    "Hello     ",
		},
		{
			name:        "No padding required",
			inputString: "World",
			padding:     5,
			expected:    "World",
		},
		{
			name:        "Empty string",
			inputString: "",
			padding:     8,
			expected:    "        ",
		},
		{
			name:        "Zero padding",
			inputString: "cobra",
			padding:     0,
			expected:    "cobra",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// Act
			got := rpad(tt.inputString, tt.padding)

			// Assert
			if got != tt.expected {
				t.Errorf("Expected rpad: %v\nGot: %v", tt.expected, got)
			}
		})
	}
}

// TestDeadcodeElimination checks that a simple program using cobra in its
// default configuration is linked taking full advantage of the linker's
// deadcode elimination step.
//
// If reflect.Value.MethodByName/reflect.Value.Method are reachable the
// linker will not always be able to prove that exported methods are
// unreachable, making deadcode elimination less effective. Using
// text/template and html/template makes reflect.Value.MethodByName
// reachable.
// Since cobra can use text/template templates this test checks that in its
// default configuration that code path can be proven to be unreachable by
// the linker.
//
// See also: https://github.com/spf13/cobra/pull/1956
func TestDeadcodeElimination(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("go tool nm fails on windows")
	}

	// check that a simple program using cobra in its default configuration is
	// linked with deadcode elimination enabled.
	const (
		dirname  = "test_deadcode"
		progname = "test_deadcode_elimination"
	)
	_ = os.Mkdir(dirname, 0770)
	defer os.RemoveAll(dirname)
	filename := filepath.Join(dirname, progname+".go")
	err := os.WriteFile(filename, []byte(`package main

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
	Version: "1.0",
	Use:     "example_program",
	Short:   "example_program - test fixture to check that deadcode elimination is allowed",
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("hello world")
	},
	Aliases: []string{"alias1", "alias2"},
	Example: "stringer --help",
}

func main() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Fprintf(os.Stderr, "Whoops. There was an error while executing your CLI '%s'", err)
		os.Exit(1)
	}
}
`), 0600)
	if err != nil {
		t.Fatalf("could not write test program: %v", err)
	}
	buf, err := exec.Command("go", "build", filename).CombinedOutput()
	if err != nil {
		t.Fatalf("could not compile test program: %s", string(buf))
	}
	defer os.Remove(progname)
	buf, err = exec.Command("go", "tool", "nm", progname).CombinedOutput()
	if err != nil {
		t.Fatalf("could not run go tool nm: %v", err)
	}
	if strings.Contains(string(buf), "MethodByName") {
		t.Error("compiled programs contains MethodByName symbol")
	}
}


================================================
FILE: command.go
================================================
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces.
// In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code.
package cobra

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"sort"
	"strings"

	flag "github.com/spf13/pflag"
)

const (
	FlagSetByCobraAnnotation     = "cobra_annotation_flag_set_by_cobra"
	CommandDisplayNameAnnotation = "cobra_annotation_command_display_name"

	helpFlagName    = "help"
	helpCommandName = "help"
)

// FParseErrWhitelist configures Flag parse errors to be ignored
type FParseErrWhitelist flag.ParseErrorsAllowlist

// Group Structure to manage groups for commands
type Group struct {
	ID    string
	Title string
}

// Command is just that, a command for your application.
// E.g.  'go run ...' - 'run' is the command. Cobra requires
// you to define the usage and description as part of your command
// definition to ensure usability.
type Command struct {
	// Use is the one-line usage message.
	// Recommended syntax is as follows:
	//   [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required.
	//   ... indicates that you can specify multiple values for the previous argument.
	//   |   indicates mutually exclusive information. You can use the argument to the left of the separator or the
	//       argument to the right of the separator. You cannot use both arguments in a single use of the command.
	//   { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are
	//       optional, they are enclosed in brackets ([ ]).
	// Example: add [-F file | -D dir]... [-f format] profile
	Use string

	// Aliases is an array of aliases that can be used instead of the first word in Use.
	Aliases []string

	// SuggestFor is an array of command names for which this command will be suggested -
	// similar to aliases but only suggests.
	SuggestFor []string

	// Short is the short description shown in the 'help' output.
	Short string

	// The group id under which this subcommand is grouped in the 'help' output of its parent.
	GroupID string

	// Long is the long message shown in the 'help <this-command>' output.
	Long string

	// Example is examples of how to use the command.
	Example string

	// ValidArgs is list of all valid non-flag arguments that are accepted in shell completions
	ValidArgs []Completion
	// ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion.
	// It is a dynamic version of using ValidArgs.
	// Only one of ValidArgs and ValidArgsFunction can be used for a command.
	ValidArgsFunction CompletionFunc

	// Expected arguments
	Args PositionalArgs

	// ArgAliases is List of aliases for ValidArgs.
	// These are not suggested to the user in the shell completion,
	// but accepted if entered manually.
	ArgAliases []string

	// BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator.
	// For portability with other shells, it is recommended to instead use ValidArgsFunction
	BashCompletionFunction string

	// Deprecated defines, if this command is deprecated and should print this string when used.
	Deprecated string

	// Annotations are key/value pairs that can be used by applications to identify or
	// group commands or set special options.
	Annotations map[string]string

	// Version defines the version for this command. If this value is non-empty and the command does not
	// define a "version" flag, a "version" boolean flag will be added to the command and, if specified,
	// will print content of the "Version" variable. A shorthand "v" flag will also be added if the
	// command does not define one.
	Version string

	// The *Run functions are executed in the following order:
	//   * PersistentPreRun()
	//   * PreRun()
	//   * Run()
	//   * PostRun()
	//   * PersistentPostRun()
	// All functions get the same args, the arguments after the command name.
	// The *PreRun and *PostRun functions will only be executed if the Run function of the current
	// command has been declared.
	//
	// PersistentPreRun: children of this command will inherit and execute.
	PersistentPreRun func(cmd *Command, args []string)
	// PersistentPreRunE: PersistentPreRun but returns an error.
	PersistentPreRunE func(cmd *Command, args []string) error
	// PreRun: children of this command will not inherit.
	PreRun func(cmd *Command, args []string)
	// PreRunE: PreRun but returns an error.
	PreRunE func(cmd *Command, args []string) error
	// Run: Typically the actual work function. Most commands will only implement this.
	Run func(cmd *Command, args []string)
	// RunE: Run but returns an error.
	RunE func(cmd *Command, args []string) error
	// PostRun: run after the Run command.
	PostRun func(cmd *Command, args []string)
	// PostRunE: PostRun but returns an error.
	PostRunE func(cmd *Command, args []string) error
	// PersistentPostRun: children of this command will inherit and execute after PostRun.
	PersistentPostRun func(cmd *Command, args []string)
	// PersistentPostRunE: PersistentPostRun but returns an error.
	PersistentPostRunE func(cmd *Command, args []string) error

	// groups for subcommands
	commandgroups []*Group

	// args is actual args parsed from flags.
	args []string
	// flagErrorBuf contains all error messages from pflag.
	flagErrorBuf *bytes.Buffer
	// flags is full set of flags.
	flags *flag.FlagSet
	// pflags contains persistent flags.
	pflags *flag.FlagSet
	// lflags contains local flags.
	// This field does not represent internal state, it's used as a cache to optimise LocalFlags function call
	lflags *flag.FlagSet
	// iflags contains inherited flags.
	// This field does not represent internal state, it's used as a cache to optimise InheritedFlags function call
	iflags *flag.FlagSet
	// parentsPflags is all persistent flags of cmd's parents.
	parentsPflags *flag.FlagSet
	// globNormFunc is the global normalization function
	// that we can use on every pflag set and children commands
	globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName

	// usageFunc is usage func defined by user.
	usageFunc func(*Command) error
	// usageTemplate is usage template defined by user.
	usageTemplate *tmplFunc
	// flagErrorFunc is func defined by user and it's called when the parsing of
	// flags returns an error.
	flagErrorFunc func(*Command, error) error
	// helpTemplate is help template defined by user.
	helpTemplate *tmplFunc
	// helpFunc is help func defined by user.
	helpFunc func(*Command, []string)
	// helpCommand is command with usage 'help'. If it's not defined by user,
	// cobra uses default help command.
	helpCommand *Command
	// helpCommandGroupID is the group id for the helpCommand
	helpCommandGroupID string

	// completionCommandGroupID is the group id for the completion command
	completionCommandGroupID string

	// versionTemplate is the version template defined by user.
	versionTemplate *tmplFunc

	// errPrefix is the error message prefix defined by user.
	errPrefix string

	// inReader is a reader defined by the user that replaces stdin
	inReader io.Reader
	// outWriter is a writer defined by the user that replaces stdout
	outWriter io.Writer
	// errWriter is a writer defined by the user that replaces stderr
	errWriter io.Writer

	// FParseErrWhitelist flag parse errors to be ignored
	FParseErrWhitelist FParseErrWhitelist

	// CompletionOptions is a set of options to control the handling of shell completion
	CompletionOptions CompletionOptions

	// commandsAreSorted defines, if command slice are sorted or not.
	commandsAreSorted bool
	// commandCalledAs is the name or alias value used to call this command.
	commandCalledAs struct {
		name   string
		called bool
	}

	ctx context.Context

	// commands is the list of commands supported by this program.
	commands []*Command
	// parent is a parent command for this command.
	parent *Command
	// Max lengths of commands' string lengths for use in padding.
	commandsMaxUseLen         int
	commandsMaxCommandPathLen int
	commandsMaxNameLen        int

	// TraverseChildren parses flags on all parents before executing child command.
	TraverseChildren bool

	// Hidden defines, if this command is hidden and should NOT show up in the list of available commands.
	Hidden bool

	// SilenceErrors is an option to quiet errors down stream.
	SilenceErrors bool

	// SilenceUsage is an option to silence usage when an error occurs.
	SilenceUsage bool

	// DisableFlagParsing disables the flag parsing.
	// If this is true all flags will be passed to the command as arguments.
	DisableFlagParsing bool

	// DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")
	// will be printed by generating docs for this command.
	DisableAutoGenTag bool

	// DisableFlagsInUseLine will disable the addition of [flags] to the usage
	// line of a command when printing help or generating docs
	DisableFlagsInUseLine bool

	// DisableSuggestions disables the suggestions based on Levenshtein distance
	// that go along with 'unknown command' messages.
	DisableSuggestions bool

	// SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.
	// Must be > 0.
	SuggestionsMinimumDistance int
}

// Context returns underlying command context. If command was executed
// with ExecuteContext or the context was set with SetContext, the
// previously set context will be returned. Otherwise, nil is returned.
//
// Notice that a call to Execute and ExecuteC will replace a nil context of
// a command with a context.Background, so a background context will be
// returned by Context after one of these functions has been called.
func (c *Command) Context() context.Context {
	return c.ctx
}

// SetContext sets context for the command. This context will be overwritten by
// Command.ExecuteContext or Command.ExecuteContextC.
func (c *Command) SetContext(ctx context.Context) {
	c.ctx = ctx
}

// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden
// particularly useful when testing.
func (c *Command) SetArgs(a []string) {
	c.args = a
}

// SetOutput sets the destination for usage and error messages.
// If output is nil, os.Stderr is used.
//
// Deprecated: Use SetOut and/or SetErr instead
func (c *Command) SetOutput(output io.Writer) {
	c.outWriter = output
	c.errWriter = output
}

// SetOut sets the destination for usage messages.
// If newOut is nil, os.Stdout is used.
func (c *Command) SetOut(newOut io.Writer) {
	c.outWriter = newOut
}

// SetErr sets the destination for error messages.
// If newErr is nil, os.Stderr is used.
func (c *Command) SetErr(newErr io.Writer) {
	c.errWriter = newErr
}

// SetIn sets the source for input data
// If newIn is nil, os.Stdin is used.
func (c *Command) SetIn(newIn io.Reader) {
	c.inReader = newIn
}

// SetUsageFunc sets usage function. Usage can be defined by application.
func (c *Command) SetUsageFunc(f func(*Command) error) {
	c.usageFunc = f
}

// SetUsageTemplate sets usage template. Can be defined by Application.
func (c *Command) SetUsageTemplate(s string) {
	if s == "" {
		c.usageTemplate = nil
		return
	}
	c.usageTemplate = tmpl(s)
}

// SetFlagErrorFunc sets a function to generate an error when flag parsing
// fails.
func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {
	c.flagErrorFunc = f
}

// SetHelpFunc sets help function. Can be defined by Application.
func (c *Command) SetHelpFunc(f func(*Command, []string)) {
	c.helpFunc = f
}

// SetHelpCommand sets help command.
func (c *Command) SetHelpCommand(cmd *Command) {
	c.helpCommand = cmd
}

// SetHelpCommandGroupID sets the group id of the help command.
func (c *Command) SetHelpCommandGroupID(groupID string) {
	if c.helpCommand != nil {
		c.helpCommand.GroupID = groupID
	}
	// helpCommandGroupID is used if no helpCommand is defined by the user
	c.helpCommandGroupID = groupID
}

// SetCompletionCommandGroupID sets the group id of the completion command.
func (c *Command) SetCompletionCommandGroupID(groupID string) {
	// completionCommandGroupID is used if no completion command is defined by the user
	c.Root().completionCommandGroupID = groupID
}

// SetHelpTemplate sets help template to be used. Application can use it to set custom template.
func (c *Command) SetHelpTemplate(s string) {
	if s == "" {
		c.helpTemplate = nil
		return
	}
	c.helpTemplate = tmpl(s)
}

// SetVersionTemplate sets version template to be used. Application can use it to set custom template.
func (c *Command) SetVersionTemplate(s string) {
	if s == "" {
		c.versionTemplate = nil
		return
	}
	c.versionTemplate = tmpl(s)
}

// SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix.
func (c *Command) SetErrPrefix(s string) {
	c.errPrefix = s
}

// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.
// The user should not have a cyclic dependency on commands.
func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {
	c.Flags().SetNormalizeFunc(n)
	c.PersistentFlags().SetNormalizeFunc(n)
	c.globNormFunc = n

	for _, command := range c.commands {
		command.SetGlobalNormalizationFunc(n)
	}
}

// OutOrStdout returns output to stdout.
func (c *Command) OutOrStdout() io.Writer {
	return c.getOut(os.Stdout)
}

// OutOrStderr returns output to stderr
func (c *Command) OutOrStderr() io.Writer {
	return c.getOut(os.Stderr)
}

// ErrOrStderr returns output to stderr
func (c *Command) ErrOrStderr() io.Writer {
	return c.getErr(os.Stderr)
}

// InOrStdin returns input to stdin
func (c *Command) InOrStdin() io.Reader {
	return c.getIn(os.Stdin)
}

func (c *Command) getOut(def io.Writer) io.Writer {
	if c.outWriter != nil {
		return c.outWriter
	}
	if c.HasParent() {
		return c.parent.getOut(def)
	}
	return def
}

func (c *Command) getErr(def io.Writer) io.Writer {
	if c.errWriter != nil {
		return c.errWriter
	}
	if c.HasParent() {
		return c.parent.getErr(def)
	}
	return def
}

func (c *Command) getIn(def io.Reader) io.Reader {
	if c.inReader != nil {
		return c.inReader
	}
	if c.HasParent() {
		return c.parent.getIn(def)
	}
	return def
}

// UsageFunc returns either the function set by SetUsageFunc for this command
// or a parent, or it returns a default usage function.
func (c *Command) UsageFunc() (f func(*Command) error) {
	if c.usageFunc != nil {
		return c.usageFunc
	}
	if c.HasParent() {
		return c.Parent().UsageFunc()
	}
	return func(c *Command) error {
		c.mergePersistentFlags()
		fn := c.getUsageTemplateFunc()
		err := fn(c.OutOrStderr(), c)
		if err != nil {
			c.PrintErrln(err)
		}
		return err
	}
}

// getUsageTemplateFunc returns the usage template function for the command
// going up the command tree if necessary.
func (c *Command) getUsageTemplateFunc() func(w io.Writer, data interface{}) error {
	if c.usageTemplate != nil {
		return c.usageTemplate.fn
	}

	if c.HasParent() {
		return c.parent.getUsageTemplateFunc()
	}
	return defaultUsageFunc
}

// Usage puts out the usage for the command.
// Used when a user provides invalid input.
// Can be defined by user by overriding UsageFunc.
func (c *Command) Usage() error {
	return c.UsageFunc()(c)
}

// HelpFunc returns either the function set by SetHelpFunc for this command
// or a parent, or it returns a function with default help behavior.
func (c *Command) HelpFunc() func(*Command, []string) {
	if c.helpFunc != nil {
		return c.helpFunc
	}
	if c.HasParent() {
		return c.Parent().HelpFunc()
	}
	return func(c *Command, a []string) {
		c.mergePersistentFlags()
		fn := c.getHelpTemplateFunc()
		// The help should be sent to stdout
		// See https://github.com/spf13/cobra/issues/1002
		err := fn(c.OutOrStdout(), c)
		if err != nil {
			c.PrintErrln(err)
		}
	}
}

// getHelpTemplateFunc returns the help template function for the command
// going up the command tree if necessary.
func (c *Command) getHelpTemplateFunc() func(w io.Writer, data interface{}) error {
	if c.helpTemplate != nil {
		return c.helpTemplate.fn
	}

	if c.HasParent() {
		return c.parent.getHelpTemplateFunc()
	}

	return defaultHelpFunc
}

// Help puts out the help for the command.
// Used when a user calls help [command].
// Can be defined by user by overriding HelpFunc.
func (c *Command) Help() error {
	c.HelpFunc()(c, []string{})
	return nil
}

// UsageString returns usage string.
func (c *Command) UsageString() string {
	// Storing normal writers
	tmpOutput := c.outWriter
	tmpErr := c.errWriter

	bb := new(bytes.Buffer)
	c.outWriter = bb
	c.errWriter = bb

	CheckErr(c.Usage())

	// Setting things back to normal
	c.outWriter = tmpOutput
	c.errWriter = tmpErr

	return bb.String()
}

// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this
// command or a parent, or it returns a function which returns the original
// error.
func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {
	if c.flagErrorFunc != nil {
		return c.flagErrorFunc
	}

	if c.HasParent() {
		return c.parent.FlagErrorFunc()
	}
	return func(c *Command, err error) error {
		return err
	}
}

const minUsagePadding = 25

// UsagePadding return padding for the usage.
func (c *Command) UsagePadding() int {
	if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {
		return minUsagePadding
	}
	return c.parent.commandsMaxUseLen
}

const minCommandPathPadding = 11

// CommandPathPadding return padding for the command path.
func (c *Command) CommandPathPadding() int {
	if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {
		return minCommandPathPadding
	}
	return c.parent.commandsMaxCommandPathLen
}

const minNamePadding = 11

// NamePadding returns padding for the name.
func (c *Command) NamePadding() int {
	if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {
		return minNamePadding
	}
	return c.parent.commandsMaxNameLen
}

// UsageTemplate returns usage template for the command.
// This function is kept for backwards-compatibility reasons.
func (c *Command) UsageTemplate() string {
	if c.usageTemplate != nil {
		return c.usageTemplate.tmpl
	}

	if c.HasParent() {
		return c.parent.UsageTemplate()
	}
	return defaultUsageTemplate
}

// HelpTemplate return help template for the command.
// This function is kept for backwards-compatibility reasons.
func (c *Command) HelpTemplate() string {
	if c.helpTemplate != nil {
		return c.helpTemplate.tmpl
	}

	if c.HasParent() {
		return c.parent.HelpTemplate()
	}
	return defaultHelpTemplate
}

// VersionTemplate return version template for the command.
// This function is kept for backwards-compatibility reasons.
func (c *Command) VersionTemplate() string {
	if c.versionTemplate != nil {
		return c.versionTemplate.tmpl
	}

	if c.HasParent() {
		return c.parent.VersionTemplate()
	}
	return defaultVersionTemplate
}

// getVersionTemplateFunc returns the version template function for the command
// going up the command tree if necessary.
func (c *Command) getVersionTemplateFunc() func(w io.Writer, data interface{}) error {
	if c.versionTemplate != nil {
		return c.versionTemplate.fn
	}

	if c.HasParent() {
		return c.parent.getVersionTemplateFunc()
	}
	return defaultVersionFunc
}

// ErrPrefix return error message prefix for the command
func (c *Command) ErrPrefix() string {
	if c.errPrefix != "" {
		return c.errPrefix
	}

	if c.HasParent() {
		return c.parent.ErrPrefix()
	}
	return "Error:"
}

func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {
	flag := fs.Lookup(name)
	if flag == nil {
		return false
	}
	return flag.NoOptDefVal != ""
}

func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {
	if len(name) == 0 {
		return false
	}

	flag := fs.ShorthandLookup(name[:1])
	if flag == nil {
		return false
	}
	return flag.NoOptDefVal != ""
}

func stripFlags(args []string, c *Command) []string {
	if len(args) == 0 {
		return args
	}
	c.mergePersistentFlags()

	commands := []string{}
	flags := c.Flags()

Loop:
	for len(args) > 0 {
		s := args[0]
		args = args[1:]
		switch {
		case s == "--":
			// "--" terminates the flags
			break Loop
		case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
			// If '--flag arg' then
			// delete arg from args.
			fallthrough // (do the same as below)
		case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):
			// If '-f arg' then
			// delete 'arg' from args or break the loop if len(args) <= 1.
			if len(args) <= 1 {
				break Loop
			} else {
				args = args[1:]
				continue
			}
		case s != "" && !strings.HasPrefix(s, "-"):
			commands = append(commands, s)
		}
	}

	return commands
}

// argsMinusFirstX removes only the first x from args.  Otherwise, commands that look like
// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).
// Special care needs to be taken not to remove a flag value.
func (c *Command) argsMinusFirstX(args []string, x string) []string {
	if len(args) == 0 {
		return args
	}
	c.mergePersistentFlags()
	flags := c.Flags()

Loop:
	for pos := 0; pos < len(args); pos++ {
		s := args[pos]
		switch {
		case s == "--":
			// -- means we have reached the end of the parseable args. Break out of the loop now.
			break Loop
		case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
			fallthrough
		case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):
			// This is a flag without a default value, and an equal sign is not used. Increment pos in order to skip
			// over the next arg, because that is the value of this flag.
			pos++
			continue
		case !strings.HasPrefix(s, "-"):
			// This is not a flag or a flag value. Check to see if it matches what we're looking for, and if so,
			// return the args, excluding the one at this position.
			if s == x {
				ret := make([]string, 0, len(args)-1)
				ret = append(ret, args[:pos]...)
				ret = append(ret, args[pos+1:]...)
				return ret
			}
		}
	}
	return args
}

func isFlagArg(arg string) bool {
	return ((len(arg) >= 3 && arg[0:2] == "--") ||
		(len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))
}

// Find the target command given the args and command tree
// Meant to be run on the highest node. Only searches down.
func (c *Command) Find(args []string) (*Command, []string, error) {
	var innerfind func(*Command, []string) (*Command, []string)

	innerfind = func(c *Command, innerArgs []string) (*Command, []string) {
		argsWOflags := stripFlags(innerArgs, c)
		if len(argsWOflags) == 0 {
			return c, innerArgs
		}
		nextSubCmd := argsWOflags[0]

		cmd := c.findNext(nextSubCmd)
		if cmd != nil {
			return innerfind(cmd, c.argsMinusFirstX(innerArgs, nextSubCmd))
		}
		return c, innerArgs
	}

	commandFound, a := innerfind(c, args)
	if commandFound.Args == nil {
		return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))
	}
	return commandFound, a, nil
}

func (c *Command) findSuggestions(arg string) string {
	if c.DisableSuggestions {
		return ""
	}
	if c.SuggestionsMinimumDistance <= 0 {
		c.SuggestionsMinimumDistance = 2
	}
	var sb strings.Builder
	if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {
		sb.WriteString("\n\nDid you mean this?\n")
		for _, s := range suggestions {
			_, _ = fmt.Fprintf(&sb, "\t%v\n", s)
		}
	}
	return sb.String()
}

func (c *Command) findNext(next string) *Command {
	matches := make([]*Command, 0)
	for _, cmd := range c.commands {
		if commandNameMatches(cmd.Name(), next) || cmd.HasAlias(next) {
			cmd.commandCalledAs.name = next
			return cmd
		}
		if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {
			matches = append(matches, cmd)
		}
	}

	if len(matches) == 1 {
		// Temporarily disable gosec G602, which produces a false positive.
		// See https://github.com/securego/gosec/issues/1005.
		return matches[0] // #nosec G602
	}

	return nil
}

// Traverse the command tree to find the command, and parse args for
// each parent.
func (c *Command) Traverse(args []string) (*Command, []string, error) {
	flags := []string{}
	inFlag := false

	for i, arg := range args {
		switch {
		// A long flag with a space separated value
		case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):
			// TODO: this isn't quite right, we should really check ahead for 'true' or 'false'
			inFlag = !hasNoOptDefVal(arg[2:], c.Flags())
			flags = append(flags, arg)
			continue
		// A short flag with a space separated value
		case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):
			inFlag = true
			flags = append(flags, arg)
			continue
		// The value for a flag
		case inFlag:
			inFlag = false
			flags = append(flags, arg)
			continue
		// A flag without a value, or with an `=` separated value
		case isFlagArg(arg):
			flags = append(flags, arg)
			continue
		}

		cmd := c.findNext(arg)
		if cmd == nil {
			return c, args, nil
		}

		if err := c.ParseFlags(flags); err != nil {
			return nil, args, err
		}
		return cmd.Traverse(args[i+1:])
	}
	return c, args, nil
}

// SuggestionsFor provides suggestions for the typedName.
func (c *Command) SuggestionsFor(typedName string) []string {
	suggestions := []string{}
	for _, cmd := range c.commands {
		if cmd.IsAvailableCommand() {
			levenshteinDistance := ld(typedName, cmd.Name(), true)
			suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance
			suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))
			if suggestByLevenshtein || suggestByPrefix {
				suggestions = append(suggestions, cmd.Name())
			}
			for _, explicitSuggestion := range cmd.SuggestFor {
				if strings.EqualFold(typedName, explicitSuggestion) {
					suggestions = append(suggestions, cmd.Name())
				}
			}
		}
	}
	return suggestions
}

// VisitParents visits all parents of the command and invokes fn on each parent.
func (c *Command) VisitParents(fn func(*Command)) {
	if c.HasParent() {
		fn(c.Parent())
		c.Parent().VisitParents(fn)
	}
}

// Root finds root command.
func (c *Command) Root() *Command {
	if c.HasParent() {
		return c.Parent().Root()
	}
	return c
}

// ArgsLenAtDash will return the length of c.Flags().Args at the moment
// when a -- was found during args parsing.
func (c *Command) ArgsLenAtDash() int {
	return c.Flags().ArgsLenAtDash()
}

func (c *Command) execute(a []string) (err error) {
	if c == nil {
		return fmt.Errorf("called Execute() on a nil Command")
	}

	if len(c.Deprecated) > 0 {
		c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)
	}

	// initialize help and version flag at the last point possible to allow for user
	// overriding
	c.InitDefaultHelpFlag()
	c.InitDefaultVersionFlag()

	err = c.ParseFlags(a)
	if err != nil {
		return c.FlagErrorFunc()(c, err)
	}

	// If help is called, regardless of other flags, return we want help.
	// Also say we need help if the command isn't runnable.
	helpVal, err := c.Flags().GetBool(helpFlagName)
	if err != nil {
		// should be impossible to get here as we always declare a help
		// flag in InitDefaultHelpFlag()
		c.Println("\"help\" flag declared as non-bool. Please correct your code")
		return err
	}

	if helpVal {
		return flag.ErrHelp
	}

	// for back-compat, only add version flag behavior if version is defined
	if c.Version != "" {
		versionVal, err := c.Flags().GetBool("version")
		if err != nil {
			c.Println("\"version\" flag declared as non-bool. Please correct your code")
			return err
		}
		if versionVal {
			fn := c.getVersionTemplateFunc()
			err := fn(c.OutOrStdout(), c)
			if err != nil {
				c.Println(err)
			}
			return err
		}
	}

	if !c.Runnable() {
		return flag.ErrHelp
	}

	c.preRun()

	defer c.postRun()

	argWoFlags := c.Flags().Args()
	if c.DisableFlagParsing {
		argWoFlags = a
	}

	if err := c.ValidateArgs(argWoFlags); err != nil {
		return err
	}

	parents := make([]*Command, 0, 5)
	for p := c; p != nil; p = p.Parent() {
		if EnableTraverseRunHooks {
			// When EnableTraverseRunHooks is set:
			// - Execute all persistent pre-runs from the root parent till this command.
			// - Execute all persistent post-runs from this command till the root parent.
			parents = append([]*Command{p}, parents...)
		} else {
			// Otherwise, execute only the first found persistent hook.
			parents = append(parents, p)
		}
	}
	for _, p := range parents {
		if p.PersistentPreRunE != nil {
			if err := p.PersistentPreRunE(c, argWoFlags); err != nil {
				return err
			}
			if !EnableTraverseRunHooks {
				break
			}
		} else if p.PersistentPreRun != nil {
			p.PersistentPreRun(c, argWoFlags)
			if !EnableTraverseRunHooks {
				break
			}
		}
	}
	if c.PreRunE != nil {
		if err := c.PreRunE(c, argWoFlags); err != nil {
			return err
		}
	} else if c.PreRun != nil {
		c.PreRun(c, argWoFlags)
	}

	if err := c.ValidateRequiredFlags(); err != nil {
		return err
	}
	if err := c.ValidateFlagGroups(); err != nil {
		return err
	}

	if c.RunE != nil {
		if err := c.RunE(c, argWoFlags); err != nil {
			return err
		}
	} else {
		c.Run(c, argWoFlags)
	}
	if c.PostRunE != nil {
		if err := c.PostRunE(c, argWoFlags); err != nil {
			return err
		}
	} else if c.PostRun != nil {
		c.PostRun(c, argWoFlags)
	}
	for p := c; p != nil; p = p.Parent() {
		if p.PersistentPostRunE != nil {
			if err := p.PersistentPostRunE(c, argWoFlags); err != nil {
				return err
			}
			if !EnableTraverseRunHooks {
				break
			}
		} else if p.PersistentPostRun != nil {
			p.PersistentPostRun(c, argWoFlags)
			if !EnableTraverseRunHooks {
				break
			}
		}
	}

	return nil
}

func (c *Command) preRun() {
	for _, x := range initializers {
		x()
	}
}

func (c *Command) postRun() {
	for _, x := range finalizers {
		x()
	}
}

// ExecuteContext is the same as Execute(), but sets the ctx on the command.
// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs
// functions.
func (c *Command) ExecuteContext(ctx context.Context) error {
	c.ctx = ctx
	return c.Execute()
}

// Execute uses the args (os.Args[1:] by default)
// and run through the command tree finding appropriate matches
// for commands and then corresponding flags.
func (c *Command) Execute() error {
	_, err := c.ExecuteC()
	return err
}

// ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command.
// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs
// functions.
func (c *Command) ExecuteContextC(ctx context.Context) (*Command, error) {
	c.ctx = ctx
	return c.ExecuteC()
}

// ExecuteC executes the command.
func (c *Command) ExecuteC() (cmd *Command, err error) {
	if c.ctx == nil {
		c.ctx = context.Background()
	}

	// Regardless of what command execute is called on, run on Root only
	if c.HasParent() {
		return c.Root().ExecuteC()
	}

	// windows hook
	if preExecHookFn != nil {
		preExecHookFn(c)
	}

	// initialize help at the last point to allow for user overriding
	c.InitDefaultHelpCmd()

	args := c.args

	// Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155
	if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {
		args = os.Args[1:]
	}

	// initialize the __complete command to be used for shell completion
	c.initCompleteCmd(args)

	// initialize the default completion command
	c.InitDefaultCompletionCmd(args...)

	// Now that all commands have been created, let's make sure all groups
	// are properly created also
	c.checkCommandGroups()

	var flags []string
	if c.TraverseChildren {
		cmd, flags, err = c.Traverse(args)
	} else {
		cmd, flags, err = c.Find(args)
	}
	if err != nil {
		// If found parse to a subcommand and then failed, talk about the subcommand
		if cmd != nil {
			c = cmd
		}
		if !c.SilenceErrors {
			c.PrintErrln(c.ErrPrefix(), err.Error())
			c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath())
		}
		return c, err
	}

	cmd.commandCalledAs.called = true
	if cmd.commandCalledAs.name == "" {
		cmd.commandCalledAs.name = cmd.Name()
	}

	// We have to pass global context to children command
	// if context is present on the parent command.
	if cmd.ctx == nil {
		cmd.ctx = c.ctx
	}

	err = cmd.execute(flags)
	if err != nil {
		// Always show help if requested, even if SilenceErrors is in
		// effect
		if errors.Is(err, flag.ErrHelp) {
			cmd.HelpFunc()(cmd, args)
			return cmd, nil
		}

		// If root command has SilenceErrors flagged,
		// all subcommands should respect it
		if !cmd.SilenceErrors && !c.SilenceErrors {
			c.PrintErrln(cmd.ErrPrefix(), err.Error())
		}

		// If root command has SilenceUsage flagged,
		// all subcommands should respect it
		if !cmd.SilenceUsage && !c.SilenceUsage {
			c.Println(cmd.UsageString())
		}
	}
	return cmd, err
}

func (c *Command) ValidateArgs(args []string) error {
	if c.Args == nil {
		return ArbitraryArgs(c, args)
	}
	return c.Args(c, args)
}

// ValidateRequiredFlags validates all required flags are present and returns an error otherwise
func (c *Command) ValidateRequiredFlags() error {
	if c.DisableFlagParsing {
		return nil
	}

	flags := c.Flags()
	missingFlagNames := []string{}
	flags.VisitAll(func(pflag *flag.Flag) {
		requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]
		if !found {
			return
		}
		if (requiredAnnotation[0] == "true") && !pflag.Changed {
			missingFlagNames = append(missingFlagNames, pflag.Name)
		}
	})

	if len(missingFlagNames) > 0 {
		return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`))
	}
	return nil
}

// checkCommandGroups checks if a command has been added to a group that does not exists.
// If so, we panic because it indicates a coding error that should be corrected.
func (c *Command) checkCommandGroups() {
	for _, sub := range c.commands {
		// if Group is not defined let the developer know right away
		if sub.GroupID != "" && !c.ContainsGroup(sub.GroupID) {
			panic(fmt.Sprintf("group id '%s' is not defined for subcommand '%s'", sub.GroupID, sub.CommandPath()))
		}

		sub.checkCommandGroups()
	}
}

// InitDefaultHelpFlag adds default help flag to c.
// It is called automatically by executing the c or by calling help and usage.
// If c already has help flag, it will do nothing.
func (c *Command) InitDefaultHelpFlag() {
	c.mergePersistentFlags()
	if c.Flags().Lookup(helpFlagName) == nil {
		usage := "help for "
		name := c.DisplayName()
		if name == "" {
			usage += "this command"
		} else {
			usage += name
		}
		c.Flags().BoolP(helpFlagName, "h", false, usage)
		_ = c.Flags().SetAnnotation(helpFlagName, FlagSetByCobraAnnotation, []string{"true"})
	}
}

// InitDefaultVersionFlag adds default version flag to c.
// It is called automatically by executing the c.
// If c already has a version flag, it will do nothing.
// If c.Version is empty, it will do nothing.
func (c *Command) InitDefaultVersionFlag() {
	if c.Version == "" {
		return
	}

	c.mergePersistentFlags()
	if c.Flags().Lookup("version") == nil {
		usage := "version for "
		if c.Name() == "" {
			usage += "this command"
		} else {
			usage += c.DisplayName()
		}
		if c.Flags().ShorthandLookup("v") == nil {
			c.Flags().BoolP("version", "v", false, usage)
		} else {
			c.Flags().Bool("version", false, usage)
		}
		_ = c.Flags().SetAnnotation("version", FlagSetByCobraAnnotation, []string{"true"})
	}
}

// InitDefaultHelpCmd adds default help command to c.
// It is called automatically by executing the c or by calling help and usage.
// If c already has help command or c has no subcommands, it will do nothing.
func (c *Command) InitDefaultHelpCmd() {
	if !c.HasSubCommands() {
		return
	}

	if c.helpCommand == nil {
		c.helpCommand = &Command{
			Use:   "help [command]",
			Short: "Help about any command",
			Long: `Help provides help for any command in the application.
Simply type ` + c.DisplayName() + ` help [path to command] for full details.`,
			ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) {
				var completions []Completion
				cmd, _, e := c.Root().Find(args)
				if e != nil {
					return nil, ShellCompDirectiveNoFileComp
				}
				if cmd == nil {
					// Root help command.
					cmd = c.Root()
				}
				for _, subCmd := range cmd.Commands() {
					if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand {
						if strings.HasPrefix(subCmd.Name(), toComplete) {
							completions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short))
						}
					}
				}
				return completions, ShellCompDirectiveNoFileComp
			},
			Run: func(c *Command, args []string) {
				cmd, _, e := c.Root().Find(args)
				if cmd == nil || e != nil {
					c.Printf("Unknown help topic %#q\n", args)
					CheckErr(c.Root().Usage())
				} else {
					// FLow the context down to be used in help text
					if cmd.ctx == nil {
						cmd.ctx = c.ctx
					}

					cmd.InitDefaultHelpFlag()    // make possible 'help' flag to be shown
					cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown
					CheckErr(cmd.Help())
				}
			},
			GroupID: c.helpCommandGroupID,
		}
	}
	c.RemoveCommand(c.helpCommand)
	c.AddCommand(c.helpCommand)
}

// ResetCommands delete parent, subcommand and help command from c.
func (c *Command) ResetCommands() {
	c.parent = nil
	c.commands = nil
	c.helpCommand = nil
	c.parentsPflags = nil
}

// Sorts commands by their names.
type commandSorterByName []*Command

func (c commandSorterByName) Len() int           { return len(c) }
func (c commandSorterByName) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }
func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }

// Commands returns a sorted slice of child commands.
func (c *Command) Commands() []*Command {
	// do not sort commands if it already sorted or sorting was disabled
	if EnableCommandSorting && !c.commandsAreSorted {
		sort.Sort(commandSorterByName(c.commands))
		c.commandsAreSorted = true
	}
	return c.commands
}

// AddCommand adds one or more commands to this parent command.
func (c *Command) AddCommand(cmds ...*Command) {
	for i, x := range cmds {
		if cmds[i] == c {
			panic("Command can't be a child of itself")
		}
		cmds[i].parent = c
		// update max lengths
		usageLen := len(x.Use)
		if usageLen > c.commandsMaxUseLen {
			c.commandsMaxUseLen = usageLen
		}
		commandPathLen := len(x.CommandPath())
		if commandPathLen > c.commandsMaxCommandPathLen {
			c.commandsMaxCommandPathLen = commandPathLen
		}
		nameLen := len(x.Name())
		if nameLen > c.commandsMaxNameLen {
			c.commandsMaxNameLen = nameLen
		}
		// If global normalization function exists, update all children
		if c.globNormFunc != nil {
			x.SetGlobalNormalizationFunc(c.globNormFunc)
		}
		c.commands = append(c.commands, x)
		c.commandsAreSorted = false
	}
}

// Groups returns a slice of child command groups.
func (c *Command) Groups() []*Group {
	return c.commandgroups
}

// AllChildCommandsHaveGroup returns if all subcommands are assigned to a group
func (c *Command) AllChildCommandsHaveGroup() bool {
	for _, sub := range c.commands {
		if (sub.IsAvailableCommand() || sub == c.helpCommand) && sub.GroupID == "" {
			return false
		}
	}
	return true
}

// ContainsGroup return if groupID exists in the list of command groups.
func (c *Command) ContainsGroup(groupID string) bool {
	for _, x := range c.commandgroups {
		if x.ID == groupID {
			return true
		}
	}
	return false
}

// AddGroup adds one or more command groups to this parent command.
func (c *Command) AddGroup(groups ...*Group) {
	c.commandgroups = append(c.commandgroups, groups...)
}

// RemoveCommand removes one or more commands from a parent command.
func (c *Command) RemoveCommand(cmds ...*Command) {
	commands := []*Command{}
main:
	for _, command := range c.commands {
		for _, cmd := range cmds {
			if command == cmd {
				command.parent = nil
				continue main
			}
		}
		commands = append(commands, command)
	}
	c.commands = commands
	// recompute all lengths
	c.commandsMaxUseLen = 0
	c.commandsMaxCommandPathLen = 0
	c.commandsMaxNameLen = 0
	for _, command := range c.commands {
		usageLen := len(command.Use)
		if usageLen > c.commandsMaxUseLen {
			c.commandsMaxUseLen = usageLen
		}
		commandPathLen := len(command.CommandPath())
		if commandPathLen > c.commandsMaxCommandPathLen {
			c.commandsMaxCommandPathLen = commandPathLen
		}
		nameLen := len(command.Name())
		if nameLen > c.commandsMaxNameLen {
			c.commandsMaxNameLen = nameLen
		}
	}
}

// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.
func (c *Command) Print(i ...interface{}) {
	fmt.Fprint(c.OutOrStderr(), i...)
}

// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.
func (c *Command) Println(i ...interface{}) {
	c.Print(fmt.Sprintln(i...))
}

// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.
func (c *Command) Printf(format string, i ...interface{}) {
	c.Print(fmt.Sprintf(format, i...))
}

// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.
func (c *Command) PrintErr(i ...interface{}) {
	fmt.Fprint(c.ErrOrStderr(), i...)
}

// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.
func (c *Command) PrintErrln(i ...interface{}) {
	c.PrintErr(fmt.Sprintln(i...))
}

// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.
func (c *Command) PrintErrf(format string, i ...interface{}) {
	c.PrintErr(fmt.Sprintf(format, i...))
}

// CommandPath returns the full path to this command.
func (c *Command) CommandPath() string {
	if c.HasParent() {
		return c.Parent().CommandPath() + " " + c.Name()
	}
	return c.DisplayName()
}

// DisplayName returns the name to display in help text. Returns command Name()
// If CommandDisplayNameAnnoation is not set
func (c *Command) DisplayName() string {
	if displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok {
		return displayName
	}
	return c.Name()
}

// UseLine puts out the full usage for a given command (including parents).
func (c *Command) UseLine() string {
	var useline string
	use := strings.Replace(c.Use, c.Name(), c.DisplayName(), 1)
	if c.HasParent() {
		useline = c.parent.CommandPath() + " " + use
	} else {
		useline = use
	}
	if c.DisableFlagsInUseLine {
		return useline
	}
	if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {
		useline += " [flags]"
	}
	return useline
}

// DebugFlags used to determine which flags have been assigned to which commands
// and which persist.
func (c *Command) DebugFlags() {
	c.Println("DebugFlags called on", c.Name())
	var debugflags func(*Command)

	debugflags = func(x *Command) {
		if x.HasFlags() || x.HasPersistentFlags() {
			c.Println(x.Name())
		}
		if x.HasFlags() {
			x.flags.VisitAll(func(f *flag.Flag) {
				if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {
					c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [LP]")
				} else {
					c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [L]")
				}
			})
		}
		if x.HasPersistentFlags() {
			x.pflags.VisitAll(func(f *flag.Flag) {
				if x.HasFlags() {
					if x.flags.Lookup(f.Name) == nil {
						c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [P]")
					}
				} else {
					c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [P]")
				}
			})
		}
		c.Println(x.flagErrorBuf)
		if x.HasSubCommands() {
			for _, y := range x.commands {
				debugflags(y)
			}
		}
	}

	debugflags(c)
}

// Name returns the command's name: the first word in the use line.
func (c *Command) Name() string {
	name := c.Use
	i := strings.Index(name, " ")
	if i >= 0 {
		name = name[:i]
	}
	return name
}

// HasAlias determines if a given string is an alias of the command.
func (c *Command) HasAlias(s string) bool {
	for _, a := range c.Aliases {
		if commandNameMatches(a, s) {
			return true
		}
	}
	return false
}

// CalledAs returns the command name or alias that was used to invoke
// this command or an empty string if the command has not been called.
func (c *Command) CalledAs() string {
	if c.commandCalledAs.called {
		return c.commandCalledAs.name
	}
	return ""
}

// hasNameOrAliasPrefix returns true if the Name or any of aliases start
// with prefix
func (c *Command) hasNameOrAliasPrefix(prefix string) bool {
	if strings.HasPrefix(c.Name(), prefix) {
		c.commandCalledAs.name = c.Name()
		return true
	}
	for _, alias := range c.Aliases {
		if strings.HasPrefix(alias, prefix) {
			c.commandCalledAs.name = alias
			return true
		}
	}
	return false
}

// NameAndAliases returns a list of the command name and all aliases
func (c *Command) NameAndAliases() string {
	return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")
}

// HasExample determines if the command has example.
func (c *Command) HasExample() bool {
	return len(c.Example) > 0
}

// Runnable determines if the command is itself runnable.
func (c *Command) Runnable() bool {
	return c.Run != nil || c.RunE != nil
}

// HasSubCommands determines if the command has children commands.
func (c *Command) HasSubCommands() bool {
	return len(c.commands) > 0
}

// IsAvailableCommand determines if a command is available as a non-help command
// (this includes all non deprecated/hidden commands).
func (c *Command) IsAvailableCommand() bool {
	if len(c.Deprecated) != 0 || c.Hidden {
		return false
	}

	if c.HasParent() && c.Parent().helpCommand == c {
		return false
	}

	if c.Runnable() || c.HasAvailableSubCommands() {
		return true
	}

	return false
}

// IsAdditionalHelpTopicCommand determines if a command is an additional
// help topic command; additional help topic command is determined by the
// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that
// are runnable/hidden/deprecated.
// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.
func (c *Command) IsAdditionalHelpTopicCommand() bool {
	// if a command is runnable, deprecated, or hidden it is not a 'help' command
	if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {
		return false
	}

	// if any non-help sub commands are found, the command is not a 'help' command
	for _, sub := range c.commands {
		if !sub.IsAdditionalHelpTopicCommand() {
			return false
		}
	}

	// the command either has no sub commands, or no non-help sub commands
	return true
}

// HasHelpSubCommands determines if a command has any available 'help' sub commands
// that need to be shown in the usage/help default template under 'additional help
// topics'.
func (c *Command) HasHelpSubCommands() bool {
	// return true on the first found available 'help' sub command
	for _, sub := range c.commands {
		if sub.IsAdditionalHelpTopicCommand() {
			return true
		}
	}

	// the command either has no sub commands, or no available 'help' sub commands
	return false
}

// HasAvailableSubCommands determines if a command has available sub commands that
// need to be shown in the usage/help default template under 'available commands'.
func (c *Command) HasAvailableSubCommands() bool {
	// return true on the first found available (non deprecated/help/hidden)
	// sub command
	for _, sub := range c.commands {
		if sub.IsAvailableCommand() {
			return true
		}
	}

	// the command either has no sub commands, or no available (non deprecated/help/hidden)
	// sub commands
	return false
}

// HasParent determines if the command is a child command.
func (c *Command) HasParent() bool {
	return c.parent != nil
}

// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.
func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
	return c.globNormFunc
}

// Flags returns the complete FlagSet that applies
// to this command (local and persistent declared here and by all parents).
func (c *Command) Flags() *flag.FlagSet {
	if c.flags == nil {
		c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
		if c.flagErrorBuf == nil {
			c.flagErrorBuf = new(bytes.Buffer)
		}
		c.flags.SetOutput(c.flagErrorBuf)
	}

	return c.flags
}

// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.
// This function does not modify the flags of the current command, it's purpose is to return the current state.
func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
	persistentFlags := c.PersistentFlags()

	out := flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
	c.LocalFlags().VisitAll(func(f *flag.Flag) {
		if persistentFlags.Lookup(f.Name) == nil {
			out.AddFlag(f)
		}
	})
	return out
}

// LocalFlags returns the local FlagSet specifically set in the current command.
// This function does not modify the flags of the current command, it's purpose is to return the current state.
func (c *Command) LocalFlags() *flag.FlagSet {
	c.mergePersistentFlags()

	if c.lflags == nil {
		c.lflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
		if c.flagErrorBuf == nil {
			c.flagErrorBuf = new(bytes.Buffer)
		}
		c.lflags.SetOutput(c.flagErrorBuf)
	}
	c.lflags.SortFlags = c.Flags().SortFlags
	if c.globNormFunc != nil {
		c.lflags.SetNormalizeFunc(c.globNormFunc)
	}

	addToLocal := func(f *flag.Flag) {
		// Add the flag if it is not a parent PFlag, or it shadows a parent PFlag
		if c.lflags.Lookup(f.Name) == nil && f != c.parentsPflags.Lookup(f.Name) {
			c.lflags.AddFlag(f)
		}
	}
	c.Flags().VisitAll(addToLocal)
	c.PersistentFlags().VisitAll(addToLocal)
	return c.lflags
}

// InheritedFlags returns all flags which were inherited from parent commands.
// This function does not modify the flags of the current command, it's purpose is to return the current state.
func (c *Command) InheritedFlags() *flag.FlagSet {
	c.mergePersistentFlags()

	if c.iflags == nil {
		c.iflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
		if c.flagErrorBuf == nil {
			c.flagErrorBuf = new(bytes.Buffer)
		}
		c.iflags.SetOutput(c.flagErrorBuf)
	}

	local := c.LocalFlags()
	if c.globNormFunc != nil {
		c.iflags.SetNormalizeFunc(c.globNormFunc)
	}

	c.parentsPflags.VisitAll(func(f *flag.Flag) {
		if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {
			c.iflags.AddFlag(f)
		}
	})
	return c.iflags
}

// NonInheritedFlags returns all flags which were not inherited from parent commands.
// This function does not modify the flags of the current command, it's purpose is to return the current state.
func (c *Command) NonInheritedFlags() *flag.FlagSet {
	return c.LocalFlags()
}

// PersistentFlags returns the persistent FlagSet specifically set in the current command.
func (c *Command) PersistentFlags() *flag.FlagSet {
	if c.pflags == nil {
		c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
		if c.flagErrorBuf == nil {
			c.flagErrorBuf = new(bytes.Buffer)
		}
		c.pflags.SetOutput(c.flagErrorBuf)
	}
	return c.pflags
}

// ResetFlags deletes all flags from command.
func (c *Command) ResetFlags() {
	c.flagErrorBuf = new(bytes.Buffer)
	c.flagErrorBuf.Reset()
	c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
	c.flags.SetOutput(c.flagErrorBuf)
	c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
	c.pflags.SetOutput(c.flagErrorBuf)

	c.lflags = nil
	c.iflags = nil
	c.parentsPflags = nil
}

// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).
func (c *Command) HasFlags() bool {
	return c.Flags().HasFlags()
}

// HasPersistentFlags checks if the command contains persistent flags.
func (c *Command) HasPersistentFlags() bool {
	return c.PersistentFlags().HasFlags()
}

// HasLocalFlags checks if the command has flags specifically declared locally.
func (c *Command) HasLocalFlags() bool {
	return c.LocalFlags().HasFlags()
}

// HasInheritedFlags checks if the command has flags inherited from its parent command.
func (c *Command) HasInheritedFlags() bool {
	return c.InheritedFlags().HasFlags()
}

// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire
// structure) which are not hidden or deprecated.
func (c *Command) HasAvailableFlags() bool {
	return c.Flags().HasAvailableFlags()
}

// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.
func (c *Command) HasAvailablePersistentFlags() bool {
	return c.PersistentFlags().HasAvailableFlags()
}

// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden
// or deprecated.
func (c *Command) HasAvailableLocalFlags() bool {
	return c.LocalFlags().HasAvailableFlags()
}

// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are
// not hidden or deprecated.
func (c *Command) HasAvailableInheritedFlags() bool {
	return c.InheritedFlags().HasAvailableFlags()
}

// Flag climbs up the command tree looking for matching flag.
func (c *Command) Flag(name string) (flag *flag.Flag) {
	flag = c.Flags().Lookup(name)

	if flag == nil {
		flag = c.persistentFlag(name)
	}

	return
}

// Recursively find matching persistent flag.
func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
	if c.HasPersistentFlags() {
		flag = c.PersistentFlags().Lookup(name)
	}

	if flag == nil {
		c.updateParentsPflags()
		flag = c.parentsPflags.Lookup(name)
	}
	return
}

// ParseFlags parses persistent flag tree and local flags.
func (c *Command) ParseFlags(args []string) error {
	if c.DisableFlagParsing {
		return nil
	}

	if c.flagErrorBuf == nil {
		c.flagErrorBuf = new(bytes.Buffer)
	}
	beforeErrorBufLen := c.flagErrorBuf.Len()
	c.mergePersistentFlags()

	// do it here after merging all flags and just before parse
	c.Flags().ParseErrorsAllowlist = flag.ParseErrorsAllowlist(c.FParseErrWhitelist)

	err := c.Flags().Parse(args)
	// Print warnings if they occurred (e.g. deprecated flag messages).
	if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {
		c.Print(c.flagErrorBuf.String())
	}

	return err
}

// Parent returns a commands parent command.
func (c *Command) Parent() *Command {
	return c.parent
}

// mergePersistentFlags merges c.PersistentFlags() to c.Flags()
// and adds missing persistent flags of all parents.
func (c *Command) mergePersistentFlags() {
	c.updateParentsPflags()
	c.Flags().AddFlagSet(c.PersistentFlags())
	c.Flags().AddFlagSet(c.parentsPflags)
}

// updateParentsPflags updates c.parentsPflags by adding
// new persistent flags of all parents.
// If c.parentsPflags == nil, it makes new.
func (c *Command) updateParentsPflags() {
	if c.parentsPflags == nil {
		c.parentsPflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
		c.parentsPflags.SetOutput(c.flagErrorBuf)
		c.parentsPflags.SortFlags = false
	}

	if c.globNormFunc != nil {
		c.parentsPflags.SetNormalizeFunc(c.globNormFunc)
	}

	c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)

	c.VisitParents(func(parent *Command) {
		c.parentsPflags.AddFlagSet(parent.PersistentFlags())
	})
}

// commandNameMatches checks if two command names are equal
// taking into account case sensitivity according to
// EnableCaseInsensitive global configuration.
func commandNameMatches(s string, t string) bool {
	if EnableCaseInsensitive {
		return strings.EqualFold(s, t)
	}

	return s == t
}

// tmplFunc holds a template and a function that will execute said template.
type tmplFunc struct {
	tmpl string
	fn   func(io.Writer, interface{}) error
}

const defaultUsageTemplate = `Usage:{{if .Runnable}}
  {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
  {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}

Aliases:
  {{.NameAndAliases}}{{end}}{{if .HasExample}}

Examples:
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}

Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}

{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}}
  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}}

Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}}
  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}

Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}

Global Flags:
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}

Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
  {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}

Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`

// defaultUsageFunc is equivalent to executing defaultUsageTemplate. The two should be changed in sync.
func defaultUsageFunc(w io.Writer, in interface{}) error {
	c := in.(*Command)
	fmt.Fprint(w, "Usage:")
	if c.Runnable() {
		fmt.Fprintf(w, "\n  %s", c.UseLine())
	}
	if c.HasAvailableSubCommands() {
		fmt.Fprintf(w, "\n  %s [command]", c.CommandPath())
	}
	if len(c.Aliases) > 0 {
		fmt.Fprintf(w, "\n\nAliases:\n")
		fmt.Fprintf(w, "  %s", c.NameAndAliases())
	}
	if c.HasExample() {
		fmt.Fprintf(w, "\n\nExamples:\n")
		fmt.Fprintf(w, "%s", c.Example)
	}
	if c.HasAvailableSubCommands() {
		cmds := c.Commands()
		if len(c.Groups()) == 0 {
			fmt.Fprintf(w, "\n\nAvailable Commands:")
			for _, subcmd := range cmds {
				if subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName {
					fmt.Fprintf(w, "\n  %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)
				}
			}
		} else {
			for _, group := range c.Groups() {
				fmt.Fprintf(w, "\n\n%s", group.Title)
				for _, subcmd := range cmds {
					if subcmd.GroupID == group.ID && (subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName) {
						fmt.Fprintf(w, "\n  %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)
					}
				}
			}
			if !c.AllChildCommandsHaveGroup() {
				fmt.Fprintf(w, "\n\nAdditional Commands:")
				for _, subcmd := range cmds {
					if subcmd.GroupID == "" && (subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName) {
						fmt.Fprintf(w, "\n  %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)
					}
				}
			}
		}
	}
	if c.HasAvailableLocalFlags() {
		fmt.Fprintf(w, "\n\nFlags:\n")
		fmt.Fprint(w, trimRightSpace(c.LocalFlags().FlagUsages()))
	}
	if c.HasAvailableInheritedFlags() {
		fmt.Fprintf(w, "\n\nGlobal Flags:\n")
		fmt.Fprint(w, trimRightSpace(c.InheritedFlags().FlagUsages()))
	}
	if c.HasHelpSubCommands() {
		fmt.Fprintf(w, "\n\nAdditional help topics:")
		for _, subcmd := range c.Commands() {
			if subcmd.IsAdditionalHelpTopicCommand() {
				fmt.Fprintf(w, "\n  %s %s", rpad(subcmd.CommandPath(), subcmd.CommandPathPadding()), subcmd.Short)
			}
		}
	}
	if c.HasAvailableSubCommands() {
		fmt.Fprintf(w, "\n\nUse \"%s [command] --help\" for more information about a command.", c.CommandPath())
	}
	fmt.Fprintln(w)
	return nil
}

const defaultHelpTemplate = `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}

{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`

// defaultHelpFunc is equivalent to executing defaultHelpTemplate. The two should be changed in sync.
func defaultHelpFunc(w io.Writer, in interface{}) error {
	c := in.(*Command)
	usage := c.Long
	if usage == "" {
		usage = c.Short
	}
	usage = trimRightSpace(usage)
	if usage != "" {
		fmt.Fprintln(w, usage)
		fmt.Fprintln(w)
	}
	if c.Runnable() || c.HasSubCommands() {
		fmt.Fprint(w, c.UsageString())
	}
	return nil
}

const defaultVersionTemplate = `{{with .DisplayName}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}
`

// defaultVersionFunc is equivalent to executing defaultVersionTemplate. The two should be changed in sync.
func defaultVersionFunc(w io.Writer, in interface{}) error {
	c := in.(*Command)
	_, err := fmt.Fprintf(w, "%s version %s\n", c.DisplayName(), c.Version)
	return err
}


================================================
FILE: command_notwin.go
================================================
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build !windows
// +build !windows

package cobra

var preExecHookFn func(*Command)


================================================
FILE: command_test.go
================================================
// Copyright 2013-2023 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cobra

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"os"
	"reflect"
	"strings"
	"testing"

	"github.com/spf13/pflag"
)

func emptyRun(*Command, []string) {}

func executeCommand(root *Command, args ...string) (output string, err error) {
	_, output, err = executeCommandC(root, args...)
	return output, err
}

func executeCommandWithContext(ctx context.Context, root *Command, args ...string) (output string, err error) {
	buf := new(bytes.Buffer)
	root.SetOut(buf)
	root.SetErr(buf)
	root.SetArgs(args)

	err = root.ExecuteContext(ctx)

	return buf.String(), err
}

func executeCommandC(root *Command, args ...string) (c *Command, output string, err error) {
	buf := new(bytes.Buffer)
	root.SetOut(buf)
	root.SetErr(buf)
	root.SetArgs(args)

	c, err = root.ExecuteC()

	return c, buf.String(), err
}

func executeCommandWithContextC(ctx context.Context, root *Command, args ...string) (c *Command, output string, err error) {
	buf := new(bytes.Buffer)
	root.SetOut(buf)
	root.SetErr(buf)
	root.SetArgs(args)

	c, err = root.ExecuteContextC(ctx)

	return c, buf.String(), err
}

func resetCommandLineFlagSet() {
	pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)
}

func checkStringContains(t *testing.T, got, expected string) {
	if !strings.Contains(got, expected) {
		t.Errorf("Expected to contain: \n %v\nGot:\n %v\n", ex
Download .txt
gitextract_201ev488/

├── .github/
│   ├── dependabot.yml
│   ├── labeler.yml
│   └── workflows/
│       ├── labeler.yml
│       └── test.yml
├── .gitignore
├── .golangci.yml
├── .mailmap
├── CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE.txt
├── MAINTAINERS
├── Makefile
├── README.md
├── SECURITY.md
├── active_help.go
├── active_help_test.go
├── args.go
├── args_test.go
├── bash_completions.go
├── bash_completionsV2.go
├── bash_completionsV2_test.go
├── bash_completions_test.go
├── cobra.go
├── cobra_test.go
├── command.go
├── command_notwin.go
├── command_test.go
├── command_win.go
├── completions.go
├── completions_test.go
├── doc/
│   ├── cmd_test.go
│   ├── man_docs.go
│   ├── man_docs_test.go
│   ├── man_examples_test.go
│   ├── md_docs.go
│   ├── md_docs_test.go
│   ├── rest_docs.go
│   ├── rest_docs_test.go
│   ├── util.go
│   ├── yaml_docs.go
│   └── yaml_docs_test.go
├── fish_completions.go
├── fish_completions_test.go
├── flag_groups.go
├── flag_groups_test.go
├── go.mod
├── go.sum
├── powershell_completions.go
├── powershell_completions_test.go
├── shell_completions.go
├── site/
│   └── content/
│       ├── active_help.md
│       ├── completions/
│       │   ├── _index.md
│       │   ├── bash.md
│       │   ├── fish.md
│       │   ├── powershell.md
│       │   └── zsh.md
│       ├── docgen/
│       │   ├── _index.md
│       │   ├── man.md
│       │   ├── md.md
│       │   ├── rest.md
│       │   └── yaml.md
│       ├── projects_using_cobra.md
│       └── user_guide.md
├── zsh_completions.go
└── zsh_completions_test.go
Download .txt
SYMBOL INDEX (654 symbols across 35 files)

FILE: active_help.go
  constant activeHelpMarker (line 23) | activeHelpMarker = "_activeHelp_ "
  constant activeHelpEnvVarSuffix (line 26) | activeHelpEnvVarSuffix  = "ACTIVE_HELP"
  constant activeHelpGlobalEnvVar (line 27) | activeHelpGlobalEnvVar  = configEnvVarGlobalPrefix + "_" + activeHelpEnv...
  constant activeHelpGlobalDisable (line 28) | activeHelpGlobalDisable = "0"
  function AppendActiveHelp (line 38) | func AppendActiveHelp(compArray []Completion, activeHelpStr string) []Co...
  function GetActiveHelpConfig (line 47) | func GetActiveHelpConfig(cmd *Command) string {
  function activeHelpEnvVar (line 58) | func activeHelpEnvVar(name string) string {

FILE: active_help_test.go
  constant activeHelpMessage (line 25) | activeHelpMessage  = "This is an activeHelp message"
  constant activeHelpMessage2 (line 26) | activeHelpMessage2 = "This is the rest of the activeHelp message"
  function TestActiveHelpAlone (line 29) | func TestActiveHelpAlone(t *testing.T) {
  function TestActiveHelpWithComps (line 84) | func TestActiveHelpWithComps(t *testing.T) {
  function TestMultiActiveHelp (line 169) | func TestMultiActiveHelp(t *testing.T) {
  function TestActiveHelpForFlag (line 231) | func TestActiveHelpForFlag(t *testing.T) {
  function TestConfigActiveHelp (line 266) | func TestConfigActiveHelp(t *testing.T) {
  function TestDisableActiveHelp (line 319) | func TestDisableActiveHelp(t *testing.T) {

FILE: args.go
  type PositionalArgs (line 22) | type PositionalArgs
  function legacyArgs (line 28) | func legacyArgs(cmd *Command, args []string) error {
  function NoArgs (line 42) | func NoArgs(cmd *Command, args []string) error {
  function OnlyValidArgs (line 51) | func OnlyValidArgs(cmd *Command, args []string) error {
  function ArbitraryArgs (line 69) | func ArbitraryArgs(cmd *Command, args []string) error {
  function MinimumNArgs (line 74) | func MinimumNArgs(n int) PositionalArgs {
  function MaximumNArgs (line 84) | func MaximumNArgs(n int) PositionalArgs {
  function ExactArgs (line 94) | func ExactArgs(n int) PositionalArgs {
  function RangeArgs (line 104) | func RangeArgs(min int, max int) PositionalArgs {
  function MatchAll (line 114) | func MatchAll(pargs ...PositionalArgs) PositionalArgs {
  function ExactValidArgs (line 129) | func ExactValidArgs(n int) PositionalArgs {

FILE: args_test.go
  function getCommand (line 23) | func getCommand(args PositionalArgs, withValid bool) *Command {
  function expectSuccess (line 35) | func expectSuccess(output string, err error, t *testing.T) {
  function validOnlyWithInvalidArgs (line 44) | func validOnlyWithInvalidArgs(err error, t *testing.T) {
  function noArgsWithArgs (line 55) | func noArgsWithArgs(err error, t *testing.T, arg string) {
  function minimumNArgsWithLessArgs (line 66) | func minimumNArgsWithLessArgs(err error, t *testing.T) {
  function maximumNArgsWithMoreArgs (line 77) | func maximumNArgsWithMoreArgs(err error, t *testing.T) {
  function exactArgsWithInvalidCount (line 88) | func exactArgsWithInvalidCount(err error, t *testing.T) {
  function rangeArgsWithInvalidCount (line 99) | func rangeArgsWithInvalidCount(err error, t *testing.T) {
  function TestNoArgs (line 112) | func TestNoArgs(t *testing.T) {
  function TestNoArgs_WithArgs (line 118) | func TestNoArgs_WithArgs(t *testing.T) {
  function TestNoArgs_WithValid_WithArgs (line 124) | func TestNoArgs_WithValid_WithArgs(t *testing.T) {
  function TestNoArgs_WithValid_WithInvalidArgs (line 130) | func TestNoArgs_WithValid_WithInvalidArgs(t *testing.T) {
  function TestNoArgs_WithValidOnly_WithInvalidArgs (line 136) | func TestNoArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
  function TestOnlyValidArgs (line 144) | func TestOnlyValidArgs(t *testing.T) {
  function TestOnlyValidArgs_WithInvalidArgs (line 150) | func TestOnlyValidArgs_WithInvalidArgs(t *testing.T) {
  function TestArbitraryArgs (line 158) | func TestArbitraryArgs(t *testing.T) {
  function TestArbitraryArgs_WithValid (line 164) | func TestArbitraryArgs_WithValid(t *testing.T) {
  function TestArbitraryArgs_WithValid_WithInvalidArgs (line 170) | func TestArbitraryArgs_WithValid_WithInvalidArgs(t *testing.T) {
  function TestArbitraryArgs_WithValidOnly_WithInvalidArgs (line 176) | func TestArbitraryArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
  function TestMinimumNArgs (line 184) | func TestMinimumNArgs(t *testing.T) {
  function TestMinimumNArgs_WithValid (line 190) | func TestMinimumNArgs_WithValid(t *testing.T) {
  function TestMinimumNArgs_WithValid__WithInvalidArgs (line 196) | func TestMinimumNArgs_WithValid__WithInvalidArgs(t *testing.T) {
  function TestMinimumNArgs_WithValidOnly_WithInvalidArgs (line 202) | func TestMinimumNArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
  function TestMinimumNArgs_WithLessArgs (line 208) | func TestMinimumNArgs_WithLessArgs(t *testing.T) {
  function TestMinimumNArgs_WithLessArgs_WithValid (line 214) | func TestMinimumNArgs_WithLessArgs_WithValid(t *testing.T) {
  function TestMinimumNArgs_WithLessArgs_WithValid_WithInvalidArgs (line 220) | func TestMinimumNArgs_WithLessArgs_WithValid_WithInvalidArgs(t *testing....
  function TestMinimumNArgs_WithLessArgs_WithValidOnly_WithInvalidArgs (line 226) | func TestMinimumNArgs_WithLessArgs_WithValidOnly_WithInvalidArgs(t *test...
  function TestMaximumNArgs (line 234) | func TestMaximumNArgs(t *testing.T) {
  function TestMaximumNArgs_WithValid (line 240) | func TestMaximumNArgs_WithValid(t *testing.T) {
  function TestMaximumNArgs_WithValid_WithInvalidArgs (line 246) | func TestMaximumNArgs_WithValid_WithInvalidArgs(t *testing.T) {
  function TestMaximumNArgs_WithValidOnly_WithInvalidArgs (line 252) | func TestMaximumNArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
  function TestMaximumNArgs_WithMoreArgs (line 258) | func TestMaximumNArgs_WithMoreArgs(t *testing.T) {
  function TestMaximumNArgs_WithMoreArgs_WithValid (line 264) | func TestMaximumNArgs_WithMoreArgs_WithValid(t *testing.T) {
  function TestMaximumNArgs_WithMoreArgs_WithValid_WithInvalidArgs (line 270) | func TestMaximumNArgs_WithMoreArgs_WithValid_WithInvalidArgs(t *testing....
  function TestMaximumNArgs_WithMoreArgs_WithValidOnly_WithInvalidArgs (line 276) | func TestMaximumNArgs_WithMoreArgs_WithValidOnly_WithInvalidArgs(t *test...
  function TestExactArgs (line 284) | func TestExactArgs(t *testing.T) {
  function TestExactArgs_WithValid (line 290) | func TestExactArgs_WithValid(t *testing.T) {
  function TestExactArgs_WithValid_WithInvalidArgs (line 296) | func TestExactArgs_WithValid_WithInvalidArgs(t *testing.T) {
  function TestExactArgs_WithValidOnly_WithInvalidArgs (line 302) | func TestExactArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
  function TestExactArgs_WithInvalidCount (line 308) | func TestExactArgs_WithInvalidCount(t *testing.T) {
  function TestExactArgs_WithInvalidCount_WithValid (line 314) | func TestExactArgs_WithInvalidCount_WithValid(t *testing.T) {
  function TestExactArgs_WithInvalidCount_WithValid_WithInvalidArgs (line 320) | func TestExactArgs_WithInvalidCount_WithValid_WithInvalidArgs(t *testing...
  function TestExactArgs_WithInvalidCount_WithValidOnly_WithInvalidArgs (line 326) | func TestExactArgs_WithInvalidCount_WithValidOnly_WithInvalidArgs(t *tes...
  function TestRangeArgs (line 334) | func TestRangeArgs(t *testing.T) {
  function TestRangeArgs_WithValid (line 340) | func TestRangeArgs_WithValid(t *testing.T) {
  function TestRangeArgs_WithValid_WithInvalidArgs (line 346) | func TestRangeArgs_WithValid_WithInvalidArgs(t *testing.T) {
  function TestRangeArgs_WithValidOnly_WithInvalidArgs (line 352) | func TestRangeArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {
  function TestRangeArgs_WithInvalidCount (line 358) | func TestRangeArgs_WithInvalidCount(t *testing.T) {
  function TestRangeArgs_WithInvalidCount_WithValid (line 364) | func TestRangeArgs_WithInvalidCount_WithValid(t *testing.T) {
  function TestRangeArgs_WithInvalidCount_WithValid_WithInvalidArgs (line 370) | func TestRangeArgs_WithInvalidCount_WithValid_WithInvalidArgs(t *testing...
  function TestRangeArgs_WithInvalidCount_WithValidOnly_WithInvalidArgs (line 376) | func TestRangeArgs_WithInvalidCount_WithValidOnly_WithInvalidArgs(t *tes...
  function TestRootTakesNoArgs (line 384) | func TestRootTakesNoArgs(t *testing.T) {
  function TestRootTakesArgs (line 401) | func TestRootTakesArgs(t *testing.T) {
  function TestChildTakesNoArgs (line 412) | func TestChildTakesNoArgs(t *testing.T) {
  function TestChildTakesArgs (line 429) | func TestChildTakesArgs(t *testing.T) {
  function TestMatchAll (line 440) | func TestMatchAll(t *testing.T) {
  function TestExactValidArgs (line 490) | func TestExactValidArgs(t *testing.T) {
  function TestExactValidArgs_WithInvalidCount (line 496) | func TestExactValidArgs_WithInvalidCount(t *testing.T) {
  function TestExactValidArgs_WithInvalidCount_WithInvalidArgs (line 502) | func TestExactValidArgs_WithInvalidCount_WithInvalidArgs(t *testing.T) {
  function TestExactValidArgs_WithInvalidArgs (line 508) | func TestExactValidArgs_WithInvalidArgs(t *testing.T) {
  function TestLegacyArgsRootAcceptsArgs (line 518) | func TestLegacyArgsRootAcceptsArgs(t *testing.T) {
  function TestLegacyArgsSubcmdAcceptsArgs (line 530) | func TestLegacyArgsSubcmdAcceptsArgs(t *testing.T) {

FILE: bash_completions.go
  constant BashCompFilenameExt (line 30) | BashCompFilenameExt     = "cobra_annotation_bash_completion_filename_ext...
  constant BashCompCustom (line 31) | BashCompCustom          = "cobra_annotation_bash_completion_custom"
  constant BashCompOneRequiredFlag (line 32) | BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required...
  constant BashCompSubdirsInDir (line 33) | BashCompSubdirsInDir    = "cobra_annotation_bash_completion_subdirs_in_dir"
  function writePreamble (line 36) | func writePreamble(buf io.StringWriter, name string) {
  function writePostscript (line 404) | func writePostscript(buf io.StringWriter, name string) {
  function writeCommands (line 447) | func writeCommands(buf io.StringWriter, cmd *Command) {
  function writeFlagHandler (line 459) | func writeFlagHandler(buf io.StringWriter, name string, annotations map[...
  constant cbn (line 495) | cbn = "\")\n"
  function writeShortFlag (line 497) | func writeShortFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) {
  function writeFlag (line 508) | func writeFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) {
  function writeLocalNonPersistentFlag (line 523) | func writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) {
  function prepareCustomAnnotationsForFlags (line 536) | func prepareCustomAnnotationsForFlags(cmd *Command) {
  function writeFlags (line 551) | func writeFlags(buf io.StringWriter, cmd *Command) {
  function writeRequiredFlag (line 593) | func writeRequiredFlag(buf io.StringWriter, cmd *Command) {
  function writeRequiredNouns (line 615) | func writeRequiredNouns(buf io.StringWriter, cmd *Command) {
  function writeCmdAliases (line 629) | func writeCmdAliases(buf io.StringWriter, cmd *Command) {
  function writeArgAliases (line 644) | func writeArgAliases(buf io.StringWriter, cmd *Command) {
  function gen (line 652) | func gen(buf io.StringWriter, cmd *Command) {
  method GenBashCompletion (line 683) | func (c *Command) GenBashCompletion(w io.Writer) error {
  function nonCompletableFlag (line 696) | func nonCompletableFlag(flag *pflag.Flag) bool {
  method GenBashCompletionFile (line 701) | func (c *Command) GenBashCompletionFile(filename string) error {

FILE: bash_completionsV2.go
  method genBashCompletion (line 24) | func (c *Command) genBashCompletion(w io.Writer, includeDesc bool) error {
  function genBashComp (line 31) | func genBashComp(buf io.StringWriter, name string, includeDesc bool) {
  method GenBashCompletionFileV2 (line 470) | func (c *Command) GenBashCompletionFileV2(filename string, includeDesc b...
  method GenBashCompletionV2 (line 482) | func (c *Command) GenBashCompletionV2(w io.Writer, includeDesc bool) err...

FILE: bash_completionsV2_test.go
  function TestBashCompletionV2WithActiveHelp (line 23) | func TestBashCompletionV2WithActiveHelp(t *testing.T) {

FILE: bash_completions_test.go
  function checkOmit (line 27) | func checkOmit(t *testing.T, found, unexpected string) {
  function check (line 33) | func check(t *testing.T, found, expected string) {
  function checkNumOccurrences (line 39) | func checkNumOccurrences(t *testing.T, found, expected string, expectedO...
  function checkRegex (line 46) | func checkRegex(t *testing.T, found, pattern string) {
  function runShellCheck (line 56) | func runShellCheck(s string) error {
  constant bashCompletionFunc (line 78) | bashCompletionFunc = `__root_custom_func() {
  function TestBashCompletions (line 83) | func TestBashCompletions(t *testing.T) {
  function TestBashCompletionHiddenFlag (line 229) | func TestBashCompletionHiddenFlag(t *testing.T) {
  function TestBashCompletionDeprecatedFlag (line 245) | func TestBashCompletionDeprecatedFlag(t *testing.T) {
  function TestBashCompletionTraverseChildren (line 261) | func TestBashCompletionTraverseChildren(t *testing.T) {
  function TestBashCompletionNoActiveHelp (line 279) | func TestBashCompletionNoActiveHelp(t *testing.T) {

FILE: cobra.go
  constant defaultPrefixMatching (line 46) | defaultPrefixMatching   = false
  constant defaultCommandSorting (line 47) | defaultCommandSorting   = true
  constant defaultCaseInsensitive (line 48) | defaultCaseInsensitive  = false
  constant defaultTraverseRunHooks (line 49) | defaultTraverseRunHooks = false
  function AddTemplateFunc (line 85) | func AddTemplateFunc(name string, tmplFunc interface{}) {
  function AddTemplateFuncs (line 91) | func AddTemplateFuncs(tmplFuncs template.FuncMap) {
  function OnInitialize (line 99) | func OnInitialize(y ...func()) {
  function OnFinalize (line 105) | func OnFinalize(y ...func()) {
  function Gt (line 114) | func Gt(a interface{}, b interface{}) bool {
  function Eq (line 144) | func Eq(a interface{}, b interface{}) bool {
  function trimRightSpace (line 159) | func trimRightSpace(s string) string {
  function appendIfNotPresent (line 166) | func appendIfNotPresent(s, stringToAppend string) string {
  function rpad (line 174) | func rpad(s string, padding int) string {
  function tmpl (line 179) | func tmpl(text string) *tmplFunc {
  function ld (line 192) | func ld(s, t string, ignoreCase bool) int {
  function stringInSlice (line 225) | func stringInSlice(a string, list []string) bool {
  function CheckErr (line 235) | func CheckErr(msg interface{}) {
  function WriteStringAndCheck (line 243) | func WriteStringAndCheck(b io.StringWriter, s string) {

FILE: cobra_test.go
  function assertNoErr (line 27) | func assertNoErr(t *testing.T, e error) {
  function TestAddTemplateFunctions (line 33) | func TestAddTemplateFunctions(t *testing.T) {
  function TestLevenshteinDistance (line 49) | func TestLevenshteinDistance(t *testing.T) {
  function TestStringInSlice (line 121) | func TestStringInSlice(t *testing.T) {
  function TestRpad (line 185) | func TestRpad(t *testing.T) {
  function TestDeadcodeElimination (line 245) | func TestDeadcodeElimination(t *testing.T) {

FILE: command.go
  constant FlagSetByCobraAnnotation (line 34) | FlagSetByCobraAnnotation     = "cobra_annotation_flag_set_by_cobra"
  constant CommandDisplayNameAnnotation (line 35) | CommandDisplayNameAnnotation = "cobra_annotation_command_display_name"
  constant helpFlagName (line 37) | helpFlagName    = "help"
  constant helpCommandName (line 38) | helpCommandName = "help"
  type FParseErrWhitelist (line 42) | type FParseErrWhitelist
  type Group (line 45) | type Group struct
  type Command (line 54) | type Command struct
    method Context (line 269) | func (c *Command) Context() context.Context {
    method SetContext (line 275) | func (c *Command) SetContext(ctx context.Context) {
    method SetArgs (line 281) | func (c *Command) SetArgs(a []string) {
    method SetOutput (line 289) | func (c *Command) SetOutput(output io.Writer) {
    method SetOut (line 296) | func (c *Command) SetOut(newOut io.Writer) {
    method SetErr (line 302) | func (c *Command) SetErr(newErr io.Writer) {
    method SetIn (line 308) | func (c *Command) SetIn(newIn io.Reader) {
    method SetUsageFunc (line 313) | func (c *Command) SetUsageFunc(f func(*Command) error) {
    method SetUsageTemplate (line 318) | func (c *Command) SetUsageTemplate(s string) {
    method SetFlagErrorFunc (line 328) | func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {
    method SetHelpFunc (line 333) | func (c *Command) SetHelpFunc(f func(*Command, []string)) {
    method SetHelpCommand (line 338) | func (c *Command) SetHelpCommand(cmd *Command) {
    method SetHelpCommandGroupID (line 343) | func (c *Command) SetHelpCommandGroupID(groupID string) {
    method SetCompletionCommandGroupID (line 352) | func (c *Command) SetCompletionCommandGroupID(groupID string) {
    method SetHelpTemplate (line 358) | func (c *Command) SetHelpTemplate(s string) {
    method SetVersionTemplate (line 367) | func (c *Command) SetVersionTemplate(s string) {
    method SetErrPrefix (line 376) | func (c *Command) SetErrPrefix(s string) {
    method SetGlobalNormalizationFunc (line 382) | func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, n...
    method OutOrStdout (line 393) | func (c *Command) OutOrStdout() io.Writer {
    method OutOrStderr (line 398) | func (c *Command) OutOrStderr() io.Writer {
    method ErrOrStderr (line 403) | func (c *Command) ErrOrStderr() io.Writer {
    method InOrStdin (line 408) | func (c *Command) InOrStdin() io.Reader {
    method getOut (line 412) | func (c *Command) getOut(def io.Writer) io.Writer {
    method getErr (line 422) | func (c *Command) getErr(def io.Writer) io.Writer {
    method getIn (line 432) | func (c *Command) getIn(def io.Reader) io.Reader {
    method UsageFunc (line 444) | func (c *Command) UsageFunc() (f func(*Command) error) {
    method getUsageTemplateFunc (line 464) | func (c *Command) getUsageTemplateFunc() func(w io.Writer, data interf...
    method Usage (line 478) | func (c *Command) Usage() error {
    method HelpFunc (line 484) | func (c *Command) HelpFunc() func(*Command, []string) {
    method getHelpTemplateFunc (line 505) | func (c *Command) getHelpTemplateFunc() func(w io.Writer, data interfa...
    method Help (line 520) | func (c *Command) Help() error {
    method UsageString (line 526) | func (c *Command) UsageString() string {
    method FlagErrorFunc (line 547) | func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {
    method UsagePadding (line 563) | func (c *Command) UsagePadding() int {
    method CommandPathPadding (line 573) | func (c *Command) CommandPathPadding() int {
    method NamePadding (line 583) | func (c *Command) NamePadding() int {
    method UsageTemplate (line 592) | func (c *Command) UsageTemplate() string {
    method HelpTemplate (line 605) | func (c *Command) HelpTemplate() string {
    method VersionTemplate (line 618) | func (c *Command) VersionTemplate() string {
    method getVersionTemplateFunc (line 631) | func (c *Command) getVersionTemplateFunc() func(w io.Writer, data inte...
    method ErrPrefix (line 643) | func (c *Command) ErrPrefix() string {
    method argsMinusFirstX (line 715) | func (c *Command) argsMinusFirstX(args []string, x string) []string {
    method Find (line 757) | func (c *Command) Find(args []string) (*Command, []string, error) {
    method findSuggestions (line 781) | func (c *Command) findSuggestions(arg string) string {
    method findNext (line 798) | func (c *Command) findNext(next string) *Command {
    method Traverse (line 821) | func (c *Command) Traverse(args []string) (*Command, []string, error) {
    method SuggestionsFor (line 863) | func (c *Command) SuggestionsFor(typedName string) []string {
    method VisitParents (line 884) | func (c *Command) VisitParents(fn func(*Command)) {
    method Root (line 892) | func (c *Command) Root() *Command {
    method ArgsLenAtDash (line 901) | func (c *Command) ArgsLenAtDash() int {
    method execute (line 905) | func (c *Command) execute(a []string) (err error) {
    method preRun (line 1047) | func (c *Command) preRun() {
    method postRun (line 1053) | func (c *Command) postRun() {
    method ExecuteContext (line 1062) | func (c *Command) ExecuteContext(ctx context.Context) error {
    method Execute (line 1070) | func (c *Command) Execute() error {
    method ExecuteContextC (line 1078) | func (c *Command) ExecuteContextC(ctx context.Context) (*Command, erro...
    method ExecuteC (line 1084) | func (c *Command) ExecuteC() (cmd *Command, err error) {
    method ValidateArgs (line 1172) | func (c *Command) ValidateArgs(args []string) error {
    method ValidateRequiredFlags (line 1180) | func (c *Command) ValidateRequiredFlags() error {
    method checkCommandGroups (line 1205) | func (c *Command) checkCommandGroups() {
    method InitDefaultHelpFlag (line 1219) | func (c *Command) InitDefaultHelpFlag() {
    method InitDefaultVersionFlag (line 1238) | func (c *Command) InitDefaultVersionFlag() {
    method InitDefaultHelpCmd (line 1263) | func (c *Command) InitDefaultHelpCmd() {
    method ResetCommands (line 1317) | func (c *Command) ResetCommands() {
    method Commands (line 1332) | func (c *Command) Commands() []*Command {
    method AddCommand (line 1342) | func (c *Command) AddCommand(cmds ...*Command) {
    method Groups (line 1371) | func (c *Command) Groups() []*Group {
    method AllChildCommandsHaveGroup (line 1376) | func (c *Command) AllChildCommandsHaveGroup() bool {
    method ContainsGroup (line 1386) | func (c *Command) ContainsGroup(groupID string) bool {
    method AddGroup (line 1396) | func (c *Command) AddGroup(groups ...*Group) {
    method RemoveCommand (line 1401) | func (c *Command) RemoveCommand(cmds ...*Command) {
    method Print (line 1435) | func (c *Command) Print(i ...interface{}) {
    method Println (line 1440) | func (c *Command) Println(i ...interface{}) {
    method Printf (line 1445) | func (c *Command) Printf(format string, i ...interface{}) {
    method PrintErr (line 1450) | func (c *Command) PrintErr(i ...interface{}) {
    method PrintErrln (line 1455) | func (c *Command) PrintErrln(i ...interface{}) {
    method PrintErrf (line 1460) | func (c *Command) PrintErrf(format string, i ...interface{}) {
    method CommandPath (line 1465) | func (c *Command) CommandPath() string {
    method DisplayName (line 1474) | func (c *Command) DisplayName() string {
    method UseLine (line 1482) | func (c *Command) UseLine() string {
    method DebugFlags (line 1501) | func (c *Command) DebugFlags() {
    method Name (line 1541) | func (c *Command) Name() string {
    method HasAlias (line 1551) | func (c *Command) HasAlias(s string) bool {
    method CalledAs (line 1562) | func (c *Command) CalledAs() string {
    method hasNameOrAliasPrefix (line 1571) | func (c *Command) hasNameOrAliasPrefix(prefix string) bool {
    method NameAndAliases (line 1586) | func (c *Command) NameAndAliases() string {
    method HasExample (line 1591) | func (c *Command) HasExample() bool {
    method Runnable (line 1596) | func (c *Command) Runnable() bool {
    method HasSubCommands (line 1601) | func (c *Command) HasSubCommands() bool {
    method IsAvailableCommand (line 1607) | func (c *Command) IsAvailableCommand() bool {
    method IsAdditionalHelpTopicCommand (line 1628) | func (c *Command) IsAdditionalHelpTopicCommand() bool {
    method HasHelpSubCommands (line 1648) | func (c *Command) HasHelpSubCommands() bool {
    method HasAvailableSubCommands (line 1662) | func (c *Command) HasAvailableSubCommands() bool {
    method HasParent (line 1677) | func (c *Command) HasParent() bool {
    method GlobalNormalizationFunc (line 1682) | func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name...
    method Flags (line 1688) | func (c *Command) Flags() *flag.FlagSet {
    method LocalNonPersistentFlags (line 1702) | func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
    method LocalFlags (line 1716) | func (c *Command) LocalFlags() *flag.FlagSet {
    method InheritedFlags (line 1744) | func (c *Command) InheritedFlags() *flag.FlagSet {
    method NonInheritedFlags (line 1770) | func (c *Command) NonInheritedFlags() *flag.FlagSet {
    method PersistentFlags (line 1775) | func (c *Command) PersistentFlags() *flag.FlagSet {
    method ResetFlags (line 1787) | func (c *Command) ResetFlags() {
    method HasFlags (line 1801) | func (c *Command) HasFlags() bool {
    method HasPersistentFlags (line 1806) | func (c *Command) HasPersistentFlags() bool {
    method HasLocalFlags (line 1811) | func (c *Command) HasLocalFlags() bool {
    method HasInheritedFlags (line 1816) | func (c *Command) HasInheritedFlags() bool {
    method HasAvailableFlags (line 1822) | func (c *Command) HasAvailableFlags() bool {
    method HasAvailablePersistentFlags (line 1827) | func (c *Command) HasAvailablePersistentFlags() bool {
    method HasAvailableLocalFlags (line 1833) | func (c *Command) HasAvailableLocalFlags() bool {
    method HasAvailableInheritedFlags (line 1839) | func (c *Command) HasAvailableInheritedFlags() bool {
    method Flag (line 1844) | func (c *Command) Flag(name string) (flag *flag.Flag) {
    method persistentFlag (line 1855) | func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
    method ParseFlags (line 1868) | func (c *Command) ParseFlags(args []string) error {
    method Parent (line 1892) | func (c *Command) Parent() *Command {
    method mergePersistentFlags (line 1898) | func (c *Command) mergePersistentFlags() {
    method updateParentsPflags (line 1907) | func (c *Command) updateParentsPflags() {
  constant minUsagePadding (line 560) | minUsagePadding = 25
  constant minCommandPathPadding (line 570) | minCommandPathPadding = 11
  constant minNamePadding (line 580) | minNamePadding = 11
  function hasNoOptDefVal (line 654) | func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {
  function shortHasNoOptDefVal (line 662) | func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {
  function stripFlags (line 674) | func stripFlags(args []string, c *Command) []string {
  function isFlagArg (line 750) | func isFlagArg(arg string) bool {
  type commandSorterByName (line 1325) | type commandSorterByName
    method Len (line 1327) | func (c commandSorterByName) Len() int           { return len(c) }
    method Swap (line 1328) | func (c commandSorterByName) Swap(i, j int)      { c[i], c[j] = c[j], ...
    method Less (line 1329) | func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() ...
  function commandNameMatches (line 1928) | func commandNameMatches(s string, t string) bool {
  type tmplFunc (line 1937) | type tmplFunc struct
  constant defaultUsageTemplate (line 1942) | defaultUsageTemplate = `Usage:{{if .Runnable}}
  function defaultUsageFunc (line 1974) | func defaultUsageFunc(w io.Writer, in interface{}) error {
  constant defaultHelpTemplate (line 2042) | defaultHelpTemplate = `{{with (or .Long .Short)}}{{. | trimTrailingWhite...
  function defaultHelpFunc (line 2047) | func defaultHelpFunc(w io.Writer, in interface{}) error {
  constant defaultVersionTemplate (line 2064) | defaultVersionTemplate = `{{with .DisplayName}}{{printf "%s " .}}{{end}}...
  function defaultVersionFunc (line 2068) | func defaultVersionFunc(w io.Writer, in interface{}) error {

FILE: command_test.go
  function emptyRun (line 30) | func emptyRun(*Command, []string) {}
  function executeCommand (line 32) | func executeCommand(root *Command, args ...string) (output string, err e...
  function executeCommandWithContext (line 37) | func executeCommandWithContext(ctx context.Context, root *Command, args ...
  function executeCommandC (line 48) | func executeCommandC(root *Command, args ...string) (c *Command, output ...
  function executeCommandWithContextC (line 59) | func executeCommandWithContextC(ctx context.Context, root *Command, args...
  function resetCommandLineFlagSet (line 70) | func resetCommandLineFlagSet() {
  function checkStringContains (line 74) | func checkStringContains(t *testing.T, got, expected string) {
  function checkStringOmits (line 80) | func checkStringOmits(t *testing.T, got, expected string) {
  constant onetwo (line 86) | onetwo = "one two"
  function TestSingleCommand (line 88) | func TestSingleCommand(t *testing.T) {
  function TestChildCommand (line 113) | func TestChildCommand(t *testing.T) {
  function TestCallCommandWithoutSubcommands (line 138) | func TestCallCommandWithoutSubcommands(t *testing.T) {
  function TestRootExecuteUnknownCommand (line 146) | func TestRootExecuteUnknownCommand(t *testing.T) {
  function TestSubcommandExecuteC (line 159) | func TestSubcommandExecuteC(t *testing.T) {
  function TestExecuteContext (line 177) | func TestExecuteContext(t *testing.T) {
  function TestExecuteContextC (line 206) | func TestExecuteContextC(t *testing.T) {
  function TestExecute_NoContext (line 235) | func TestExecute_NoContext(t *testing.T) {
  function TestRootUnknownCommandSilenced (line 262) | func TestRootUnknownCommandSilenced(t *testing.T) {
  function TestCommandAlias (line 274) | func TestCommandAlias(t *testing.T) {
  function TestEnablePrefixMatching (line 305) | func TestEnablePrefixMatching(t *testing.T) {
  function TestAliasPrefixMatching (line 334) | func TestAliasPrefixMatching(t *testing.T) {
  function TestPlugin (line 372) | func TestPlugin(t *testing.T) {
  function TestPluginWithSubCommands (line 394) | func TestPluginWithSubCommands(t *testing.T) {
  function TestChildSameName (line 437) | func TestChildSameName(t *testing.T) {
  function TestGrandChildSameName (line 465) | func TestGrandChildSameName(t *testing.T) {
  function TestFlagLong (line 491) | func TestFlagLong(t *testing.T) {
  function TestFlagShort (line 528) | func TestFlagShort(t *testing.T) {
  function TestChildFlag (line 562) | func TestChildFlag(t *testing.T) {
  function TestChildFlagWithParentLocalFlag (line 583) | func TestChildFlagWithParentLocalFlag(t *testing.T) {
  function TestFlagInvalidInput (line 604) | func TestFlagInvalidInput(t *testing.T) {
  function TestFlagBeforeCommand (line 616) | func TestFlagBeforeCommand(t *testing.T) {
  function TestStripFlags (line 643) | func TestStripFlags(t *testing.T) {
  function TestDisableFlagParsing (line 716) | func TestDisableFlagParsing(t *testing.T) {
  function TestPersistentFlagsOnSameCommand (line 740) | func TestPersistentFlagsOnSameCommand(t *testing.T) {
  function TestEmptyInputs (line 770) | func TestEmptyInputs(t *testing.T) {
  function TestChildFlagShadowsParentPersistentFlag (line 789) | func TestChildFlagShadowsParentPersistentFlag(t *testing.T) {
  function TestPersistentFlagsOnChild (line 818) | func TestPersistentFlagsOnChild(t *testing.T) {
  function TestRequiredFlags (line 853) | func TestRequiredFlags(t *testing.T) {
  function TestPersistentRequiredFlags (line 871) | func TestPersistentRequiredFlags(t *testing.T) {
  function TestPersistentRequiredFlagsWithDisableFlagParsing (line 896) | func TestPersistentRequiredFlagsWithDisableFlagParsing(t *testing.T) {
  function TestInitHelpFlagMergesFlags (line 927) | func TestInitHelpFlagMergesFlags(t *testing.T) {
  function TestHelpCommandExecuted (line 941) | func TestHelpCommandExecuted(t *testing.T) {
  function TestHelpCommandExecutedOnChild (line 953) | func TestHelpCommandExecutedOnChild(t *testing.T) {
  function TestHelpCommandExecutedOnChildWithFlagThatShadowsParentFlag (line 966) | func TestHelpCommandExecutedOnChildWithFlagThatShadowsParentFlag(t *test...
  function TestSetHelpCommand (line 998) | func TestSetHelpCommand(t *testing.T) {
  function TestSetHelpTemplate (line 1021) | func TestSetHelpTemplate(t *testing.T) {
  function TestHelpFlagExecuted (line 1064) | func TestHelpFlagExecuted(t *testing.T) {
  function TestHelpFlagExecutedOnChild (line 1075) | func TestHelpFlagExecutedOnChild(t *testing.T) {
  function TestHelpFlagInHelp (line 1092) | func TestHelpFlagInHelp(t *testing.T) {
  function TestFlagsInUsage (line 1106) | func TestFlagsInUsage(t *testing.T) {
  function TestHelpExecutedOnNonRunnableChild (line 1116) | func TestHelpExecutedOnNonRunnableChild(t *testing.T) {
  function TestSetUsageTemplate (line 1129) | func TestSetUsageTemplate(t *testing.T) {
  function TestVersionFlagExecuted (line 1168) | func TestVersionFlagExecuted(t *testing.T) {
  function TestVersionFlagExecutedDiplayName (line 1179) | func TestVersionFlagExecutedDiplayName(t *testing.T) {
  function TestVersionFlagExecutedWithNoName (line 1197) | func TestVersionFlagExecutedWithNoName(t *testing.T) {
  function TestShortAndLongVersionFlagInHelp (line 1208) | func TestShortAndLongVersionFlagInHelp(t *testing.T) {
  function TestLongVersionFlagOnlyInHelpWhenShortPredefined (line 1219) | func TestLongVersionFlagOnlyInHelpWhenShortPredefined(t *testing.T) {
  function TestShorthandVersionFlagExecuted (line 1232) | func TestShorthandVersionFlagExecuted(t *testing.T) {
  function TestVersionTemplate (line 1243) | func TestVersionTemplate(t *testing.T) {
  function TestShorthandVersionTemplate (line 1255) | func TestShorthandVersionTemplate(t *testing.T) {
  function TestRootErrPrefixExecutedOnSubcommand (line 1267) | func TestRootErrPrefixExecutedOnSubcommand(t *testing.T) {
  function TestRootAndSubErrPrefix (line 1280) | func TestRootAndSubErrPrefix(t *testing.T) {
  function TestVersionFlagExecutedOnSubcommand (line 1300) | func TestVersionFlagExecutedOnSubcommand(t *testing.T) {
  function TestShorthandVersionFlagExecutedOnSubcommand (line 1312) | func TestShorthandVersionFlagExecutedOnSubcommand(t *testing.T) {
  function TestVersionFlagOnlyAddedToRoot (line 1324) | func TestVersionFlagOnlyAddedToRoot(t *testing.T) {
  function TestShortVersionFlagOnlyAddedToRoot (line 1336) | func TestShortVersionFlagOnlyAddedToRoot(t *testing.T) {
  function TestVersionFlagOnlyExistsIfVersionNonEmpty (line 1348) | func TestVersionFlagOnlyExistsIfVersionNonEmpty(t *testing.T) {
  function TestShorthandVersionFlagOnlyExistsIfVersionNonEmpty (line 1358) | func TestShorthandVersionFlagOnlyExistsIfVersionNonEmpty(t *testing.T) {
  function TestShorthandVersionFlagOnlyAddedIfShorthandNotDefined (line 1368) | func TestShorthandVersionFlagOnlyAddedIfShorthandNotDefined(t *testing.T) {
  function TestShorthandVersionFlagOnlyAddedIfVersionNotDefined (line 1380) | func TestShorthandVersionFlagOnlyAddedIfVersionNotDefined(t *testing.T) {
  function TestUsageIsNotPrintedTwice (line 1391) | func TestUsageIsNotPrintedTwice(t *testing.T) {
  function TestVisitParents (line 1402) | func TestVisitParents(t *testing.T) {
  function TestSuggestions (line 1431) | func TestSuggestions(t *testing.T) {
  function TestCaseInsensitive (line 1478) | func TestCaseInsensitive(t *testing.T) {
  function TestCaseSensitivityBackwardCompatibility (line 1573) | func TestCaseSensitivityBackwardCompatibility(t *testing.T) {
  function TestRemoveCommand (line 1585) | func TestRemoveCommand(t *testing.T) {
  function TestReplaceCommandWithRemove (line 1597) | func TestReplaceCommandWithRemove(t *testing.T) {
  function TestDeprecatedCommand (line 1628) | func TestDeprecatedCommand(t *testing.T) {
  function TestHooks (line 1645) | func TestHooks(t *testing.T) {
  function TestPersistentHooks (line 1697) | func TestPersistentHooks(t *testing.T) {
  function testPersistentHooks (line 1719) | func testPersistentHooks(t *testing.T, expectedHookRunOrder []string) {
  function TestGlobalNormFuncPropagation (line 1789) | func TestGlobalNormFuncPropagation(t *testing.T) {
  function TestNormPassedOnLocal (line 1809) | func TestNormPassedOnLocal(t *testing.T) {
  function TestNormPassedOnInherited (line 1823) | func TestNormPassedOnInherited(t *testing.T) {
  function TestConsistentNormalizedName (line 1851) | func TestConsistentNormalizedName(t *testing.T) {
  function TestFlagOnPflagCommandLine (line 1869) | func TestFlagOnPflagCommandLine(t *testing.T) {
  function TestHiddenCommandExecutes (line 1884) | func TestHiddenCommandExecutes(t *testing.T) {
  function TestHiddenCommandIsHidden (line 1906) | func TestHiddenCommandIsHidden(t *testing.T) {
  function TestCommandsAreSorted (line 1913) | func TestCommandsAreSorted(t *testing.T) {
  function TestEnableCommandSortingIsDisabled (line 1935) | func TestEnableCommandSortingIsDisabled(t *testing.T) {
  function TestUsageWithGroup (line 1956) | func TestUsageWithGroup(t *testing.T) {
  function TestUsageHelpGroup (line 1977) | func TestUsageHelpGroup(t *testing.T) {
  function TestUsageCompletionGroup (line 1995) | func TestUsageCompletionGroup(t *testing.T) {
  function TestUngroupedCommand (line 2015) | func TestUngroupedCommand(t *testing.T) {
  function TestAddGroup (line 2037) | func TestAddGroup(t *testing.T) {
  function TestWrongGroupFirstLevel (line 2051) | func TestWrongGroupFirstLevel(t *testing.T) {
  function TestWrongGroupNestedLevel (line 2069) | func TestWrongGroupNestedLevel(t *testing.T) {
  function TestWrongGroupForHelp (line 2089) | func TestWrongGroupForHelp(t *testing.T) {
  function TestWrongGroupForCompletion (line 2109) | func TestWrongGroupForCompletion(t *testing.T) {
  function TestSetOutput (line 2129) | func TestSetOutput(t *testing.T) {
  function TestSetOut (line 2137) | func TestSetOut(t *testing.T) {
  function TestSetErr (line 2145) | func TestSetErr(t *testing.T) {
  function TestSetIn (line 2153) | func TestSetIn(t *testing.T) {
  function TestUsageStringRedirected (line 2161) | func TestUsageStringRedirected(t *testing.T) {
  function TestCommandPrintRedirection (line 2177) | func TestCommandPrintRedirection(t *testing.T) {
  function TestFlagErrorFunc (line 2218) | func TestFlagErrorFunc(t *testing.T) {
  function TestFlagErrorFuncHelp (line 2235) | func TestFlagErrorFuncHelp(t *testing.T) {
  function TestSortedFlags (line 2270) | func TestSortedFlags(t *testing.T) {
  function TestMergeCommandLineToFlags (line 2296) | func TestMergeCommandLineToFlags(t *testing.T) {
  function TestUseDeprecatedFlags (line 2310) | func TestUseDeprecatedFlags(t *testing.T) {
  function TestTraverseWithParentFlags (line 2322) | func TestTraverseWithParentFlags(t *testing.T) {
  function TestTraverseNoParentFlags (line 2344) | func TestTraverseNoParentFlags(t *testing.T) {
  function TestTraverseWithBadParentFlags (line 2364) | func TestTraverseWithBadParentFlags(t *testing.T) {
  function TestTraverseWithBadChildFlag (line 2382) | func TestTraverseWithBadChildFlag(t *testing.T) {
  function TestTraverseWithTwoSubcommands (line 2403) | func TestTraverseWithTwoSubcommands(t *testing.T) {
  function TestUpdateName (line 2425) | func TestUpdateName(t *testing.T) {
  type calledAsTestcase (line 2435) | type calledAsTestcase struct
    method test (line 2442) | func (tc *calledAsTestcase) test(t *testing.T) {
  function TestCalledAs (line 2477) | func TestCalledAs(t *testing.T) {
  function TestFParseErrWhitelistBackwardCompatibility (line 2498) | func TestFParseErrWhitelistBackwardCompatibility(t *testing.T) {
  function TestFParseErrWhitelistSameCommand (line 2509) | func TestFParseErrWhitelistSameCommand(t *testing.T) {
  function TestFParseErrWhitelistParentCommand (line 2525) | func TestFParseErrWhitelistParentCommand(t *testing.T) {
  function TestFParseErrWhitelistChildCommand (line 2549) | func TestFParseErrWhitelistChildCommand(t *testing.T) {
  function TestFParseErrWhitelistSiblingCommand (line 2572) | func TestFParseErrWhitelistSiblingCommand(t *testing.T) {
  function TestSetContext (line 2603) | func TestSetContext(t *testing.T) {
  function TestSetContextPreRun (line 2628) | func TestSetContextPreRun(t *testing.T) {
  function TestSetContextPreRunOverwrite (line 2654) | func TestSetContextPreRunOverwrite(t *testing.T) {
  function TestSetContextPersistentPreRun (line 2675) | func TestSetContextPersistentPreRun(t *testing.T) {
  constant VersionFlag (line 2706) | VersionFlag = "--version"
  constant HelpFlag (line 2707) | HelpFlag = "--help"
  function TestNoRootRunCommandExecutedWithVersionSet (line 2709) | func TestNoRootRunCommandExecutedWithVersionSet(t *testing.T) {
  function TestNoRootRunCommandExecutedWithoutVersionSet (line 2723) | func TestNoRootRunCommandExecutedWithoutVersionSet(t *testing.T) {
  function TestHelpCommandExecutedWithVersionSet (line 2737) | func TestHelpCommandExecutedWithVersionSet(t *testing.T) {
  function TestHelpCommandExecutedWithoutVersionSet (line 2751) | func TestHelpCommandExecutedWithoutVersionSet(t *testing.T) {
  function TestHelpflagCommandExecutedWithVersionSet (line 2765) | func TestHelpflagCommandExecutedWithVersionSet(t *testing.T) {
  function TestHelpflagCommandExecutedWithoutVersionSet (line 2779) | func TestHelpflagCommandExecutedWithoutVersionSet(t *testing.T) {
  function TestFind (line 2793) | func TestFind(t *testing.T) {
  function TestUnknownFlagShouldReturnSameErrorRegardlessOfArgPosition (line 2882) | func TestUnknownFlagShouldReturnSameErrorRegardlessOfArgPosition(t *test...
  function TestHelpFuncExecuted (line 2925) | func TestHelpFuncExecuted(t *testing.T) {

FILE: command_win.go
  function preExecHook (line 30) | func preExecHook(c *Command) {

FILE: completions.go
  constant ShellCompRequestCmd (line 31) | ShellCompRequestCmd = "__complete"
  constant ShellCompNoDescRequestCmd (line 34) | ShellCompNoDescRequestCmd = "__completeNoDesc"
  type ShellCompDirective (line 45) | type ShellCompDirective
    method string (line 200) | func (d ShellCompDirective) string() string {
  type flagCompError (line 47) | type flagCompError struct
    method Error (line 52) | func (e *flagCompError) Error() string {
  constant ShellCompDirectiveError (line 58) | ShellCompDirectiveError ShellCompDirective = 1 << iota
  constant ShellCompDirectiveNoSpace (line 62) | ShellCompDirectiveNoSpace
  constant ShellCompDirectiveNoFileComp (line 66) | ShellCompDirectiveNoFileComp
  constant ShellCompDirectiveFilterFileExt (line 73) | ShellCompDirectiveFilterFileExt
  constant ShellCompDirectiveFilterDirs (line 80) | ShellCompDirectiveFilterDirs
  constant ShellCompDirectiveKeepOrder (line 84) | ShellCompDirectiveKeepOrder
  constant shellCompDirectiveMaxValue (line 90) | shellCompDirectiveMaxValue
  constant ShellCompDirectiveDefault (line 95) | ShellCompDirectiveDefault ShellCompDirective = 0
  constant compCmdName (line 100) | compCmdName              = "completion"
  constant compCmdNoDescFlagName (line 101) | compCmdNoDescFlagName    = "no-descriptions"
  constant compCmdNoDescFlagDesc (line 102) | compCmdNoDescFlagDesc    = "disable completion descriptions"
  constant compCmdNoDescFlagDefault (line 103) | compCmdNoDescFlagDefault = false
  type CompletionOptions (line 107) | type CompletionOptions struct
    method SetDefaultShellCompDirective (line 123) | func (receiver *CompletionOptions) SetDefaultShellCompDirective(direct...
  function CompletionWithDesc (line 142) | func CompletionWithDesc(choice string, description string) Completion {
  function NoFileCompletions (line 151) | func NoFileCompletions(cmd *Command, args []string, toComplete string) (...
  function FixedCompletions (line 160) | func FixedCompletions(choices []Completion, directive ShellCompDirective...
  method RegisterFlagCompletionFunc (line 170) | func (c *Command) RegisterFlagCompletionFunc(flagName string, f Completi...
  method GetFlagCompletionFunc (line 186) | func (c *Command) GetFlagCompletionFunc(flagName string) (CompletionFunc...
  method initCompleteCmd (line 231) | func (c *Command) initCompleteCmd(args []string) {
  type SliceValue (line 311) | type SliceValue interface
  method getCompletions (line 316) | func (c *Command) getCompletions(args []string) (*Command, []Completion,...
  function helpOrVersionFlagPresent (line 584) | func helpOrVersionFlagPresent(cmd *Command) bool {
  function getFlagNameCompletions (line 596) | func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []Compl...
  function completeRequireFlags (line 629) | func completeRequireFlags(finalCmd *Command, toComplete string) []Comple...
  function checkIfFlagCompletion (line 654) | func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg str...
  method InitDefaultCompletionCmd (line 745) | func (c *Command) InitDefaultCompletionCmd(args ...string) {
  function findFlag (line 929) | func findFlag(cmd *Command, name string) *pflag.Flag {
  function CompDebug (line 952) | func CompDebug(msg string, printToStdErr bool) {
  function CompDebugln (line 976) | func CompDebugln(msg string, printToStdErr bool) {
  function CompError (line 981) | func CompError(msg string) {
  function CompErrorln (line 987) | func CompErrorln(msg string) {
  constant configEnvVarGlobalPrefix (line 993) | configEnvVarGlobalPrefix       = "COBRA"
  constant configEnvVarSuffixDescriptions (line 994) | configEnvVarSuffixDescriptions = "COMPLETION_DESCRIPTIONS"
  function configEnvVar (line 1002) | func configEnvVar(name, suffix string) string {
  function getEnvConfig (line 1014) | func getEnvConfig(cmd *Command, suffix string) string {

FILE: completions_test.go
  function validArgsFunc (line 27) | func validArgsFunc(cmd *Command, args []string, toComplete string) ([]st...
  function validArgsFunc2 (line 41) | func validArgsFunc2(cmd *Command, args []string, toComplete string) ([]s...
  function TestCmdNameCompletionInGo (line 55) | func TestCmdNameCompletionInGo(t *testing.T) {
  function TestNoCmdNameCompletionInGo (line 157) | func TestNoCmdNameCompletionInGo(t *testing.T) {
  function TestValidArgsCompletionInGo (line 322) | func TestValidArgsCompletionInGo(t *testing.T) {
  function TestValidArgsAndCmdCompletionInGo (line 376) | func TestValidArgsAndCmdCompletionInGo(t *testing.T) {
  function TestValidArgsFuncAndCmdCompletionInGo (line 426) | func TestValidArgsFuncAndCmdCompletionInGo(t *testing.T) {
  function TestFlagNameCompletionInGo (line 493) | func TestFlagNameCompletionInGo(t *testing.T) {
  function TestFlagNameCompletionInGoWithDesc (line 583) | func TestFlagNameCompletionInGoWithDesc(t *testing.T) {
  type customMultiString (line 676) | type customMultiString
    method String (line 680) | func (s *customMultiString) String() string {
    method Set (line 684) | func (s *customMultiString) Set(v string) error {
    method Type (line 689) | func (s *customMultiString) Type() string {
    method GetSlice (line 693) | func (s *customMultiString) GetSlice() []string {
  function TestFlagNameCompletionRepeat (line 697) | func TestFlagNameCompletionRepeat(t *testing.T) {
  function TestRequiredFlagNameCompletionInGo (line 844) | func TestRequiredFlagNameCompletionInGo(t *testing.T) {
  function TestFlagFileExtFilterCompletionInGo (line 1038) | func TestFlagFileExtFilterCompletionInGo(t *testing.T) {
  function TestFlagDirFilterCompletionInGo (line 1160) | func TestFlagDirFilterCompletionInGo(t *testing.T) {
  function TestValidArgsFuncCmdContext (line 1276) | func TestValidArgsFuncCmdContext(t *testing.T) {
  function TestValidArgsFuncSingleCmd (line 1318) | func TestValidArgsFuncSingleCmd(t *testing.T) {
  function TestValidArgsFuncSingleCmdInvalidArg (line 1357) | func TestValidArgsFuncSingleCmdInvalidArg(t *testing.T) {
  function TestValidArgsFuncChildCmds (line 1384) | func TestValidArgsFuncChildCmds(t *testing.T) {
  function TestValidArgsFuncAliases (line 1488) | func TestValidArgsFuncAliases(t *testing.T) {
  function TestValidArgsFuncInBashScript (line 1544) | func TestValidArgsFuncInBashScript(t *testing.T) {
  function TestNoValidArgsFuncInBashScript (line 1560) | func TestNoValidArgsFuncInBashScript(t *testing.T) {
  function TestCompleteCmdInBashScript (line 1575) | func TestCompleteCmdInBashScript(t *testing.T) {
  function TestCompleteNoDesCmdInZshScript (line 1591) | func TestCompleteNoDesCmdInZshScript(t *testing.T) {
  function TestCompleteCmdInZshScript (line 1607) | func TestCompleteCmdInZshScript(t *testing.T) {
  function TestFlagCompletionInGo (line 1624) | func TestFlagCompletionInGo(t *testing.T) {
  function TestValidArgsFuncChildCmdsWithDesc (line 1717) | func TestValidArgsFuncChildCmdsWithDesc(t *testing.T) {
  function TestFlagCompletionWithNotInterspersedArgs (line 1821) | func TestFlagCompletionWithNotInterspersedArgs(t *testing.T) {
  function TestFlagCompletionWorksRootCommandAddedAfterFlags (line 2044) | func TestFlagCompletionWorksRootCommandAddedAfterFlags(t *testing.T) {
  function TestFlagCompletionForPersistentFlagsCalledFromSubCmd (line 2079) | func TestFlagCompletionForPersistentFlagsCalledFromSubCmd(t *testing.T) {
  function TestFlagCompletionConcurrentRegistration (line 2121) | func TestFlagCompletionConcurrentRegistration(t *testing.T) {
  function TestFlagCompletionInGoWithDesc (line 2187) | func TestFlagCompletionInGoWithDesc(t *testing.T) {
  function TestValidArgsNotValidArgsFunc (line 2280) | func TestValidArgsNotValidArgsFunc(t *testing.T) {
  function TestArgAliasesCompletionInGo (line 2323) | func TestArgAliasesCompletionInGo(t *testing.T) {
  function TestCompleteHelp (line 2381) | func TestCompleteHelp(t *testing.T) {
  function removeCompCmd (line 2451) | func removeCompCmd(rootCmd *Command) {
  function TestDefaultCompletionCmd (line 2461) | func TestDefaultCompletionCmd(t *testing.T) {
  function TestCompleteCompletion (line 2607) | func TestCompleteCompletion(t *testing.T) {
  function TestMultipleShorthandFlagCompletion (line 2694) | func TestMultipleShorthandFlagCompletion(t *testing.T) {
  function TestCompleteWithDisableFlagParsing (line 2787) | func TestCompleteWithDisableFlagParsing(t *testing.T) {
  function TestCompleteWithRootAndLegacyArgs (line 2850) | func TestCompleteWithRootAndLegacyArgs(t *testing.T) {
  function TestCompletionFuncCompatibility (line 2896) | func TestCompletionFuncCompatibility(t *testing.T) {
  function TestFixedCompletions (line 2980) | func TestFixedCompletions(t *testing.T) {
  function TestFixedCompletionsWithCompletionHelpers (line 3007) | func TestFixedCompletionsWithCompletionHelpers(t *testing.T) {
  function TestCompletionForGroupedFlags (line 3057) | func TestCompletionForGroupedFlags(t *testing.T) {
  function TestCompletionForOneRequiredGroupFlags (line 3157) | func TestCompletionForOneRequiredGroupFlags(t *testing.T) {
  function TestCompletionForMutuallyExclusiveFlags (line 3255) | func TestCompletionForMutuallyExclusiveFlags(t *testing.T) {
  function TestCompletionCobraFlags (line 3349) | func TestCompletionCobraFlags(t *testing.T) {
  function TestArgsNotDetectedAsFlagsCompletionInGo (line 3583) | func TestArgsNotDetectedAsFlagsCompletionInGo(t *testing.T) {
  function TestGetFlagCompletion (line 3647) | func TestGetFlagCompletion(t *testing.T) {
  function TestGetEnvConfig (line 3737) | func TestGetEnvConfig(t *testing.T) {
  function TestDisableDescriptions (line 3822) | func TestDisableDescriptions(t *testing.T) {
  function TestInitDefaultCompletionCmd (line 3930) | func TestInitDefaultCompletionCmd(t *testing.T) {
  function TestCustomDefaultShellCompDirective (line 4019) | func TestCustomDefaultShellCompDirective(t *testing.T) {

FILE: doc/cmd_test.go
  function emptyRun (line 24) | func emptyRun(*cobra.Command, []string) {}
  function init (line 26) | func init() {
  function checkStringContains (line 95) | func checkStringContains(t *testing.T, got, expected string) {
  function checkStringOmits (line 101) | func checkStringOmits(t *testing.T, got, expected string) {

FILE: doc/man_docs.go
  function GenManTree (line 38) | func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) er...
  function GenManTreeFromOpts (line 48) | func GenManTreeFromOpts(cmd *cobra.Command, opts GenManTreeOptions) error {
  type GenManTreeOptions (line 84) | type GenManTreeOptions struct
  type GenManHeader (line 94) | type GenManHeader struct
  function GenMan (line 105) | func GenMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error {
  function fillHeader (line 118) | func fillHeader(header *GenManHeader, name string, disableAutoGen bool) ...
  function manPreamble (line 143) | func manPreamble(buf io.StringWriter, header *GenManHeader, cmd *cobra.C...
  function manPrintFlags (line 159) | func manPrintFlags(buf io.StringWriter, flags *pflag.FlagSet) {
  function manPrintOptions (line 187) | func manPrintOptions(buf io.StringWriter, command *cobra.Command) {
  function genMan (line 202) | func genMan(cmd *cobra.Command, header *GenManHeader) []byte {

FILE: doc/man_docs_test.go
  function assertNoErr (line 29) | func assertNoErr(t *testing.T, e error) {
  function translate (line 35) | func translate(in string) string {
  function TestGenManDoc (line 39) | func TestGenManDoc(t *testing.T) {
  function TestGenManNoHiddenParents (line 69) | func TestGenManNoHiddenParents(t *testing.T) {
  function TestGenManNoGenTag (line 105) | func TestGenManNoGenTag(t *testing.T) {
  function TestGenManSeeAlso (line 127) | func TestGenManSeeAlso(t *testing.T) {
  function TestManPrintFlagsHidesShortDeprecated (line 149) | func TestManPrintFlagsHidesShortDeprecated(t *testing.T) {
  function TestGenManTree (line 164) | func TestGenManTree(t *testing.T) {
  function assertLineFound (line 186) | func assertLineFound(scanner *bufio.Scanner, expectedLine string) error {
  function assertNextLineEquals (line 201) | func assertNextLineEquals(scanner *bufio.Scanner, expectedLine string) e...
  function BenchmarkGenManToFile (line 217) | func BenchmarkGenManToFile(b *testing.B) {

FILE: doc/man_examples_test.go
  function ExampleGenManTree (line 25) | func ExampleGenManTree() {
  function ExampleGenMan (line 37) | func ExampleGenMan() {

FILE: doc/md_docs.go
  constant markdownExtension (line 30) | markdownExtension = ".md"
  function printOptions (line 32) | func printOptions(buf *bytes.Buffer, cmd *cobra.Command, name string) er...
  function GenMarkdown (line 52) | func GenMarkdown(cmd *cobra.Command, w io.Writer) error {
  function GenMarkdownCustom (line 57) | func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func...
  function GenMarkdownTree (line 125) | func GenMarkdownTree(cmd *cobra.Command, dir string) error {
  function GenMarkdownTreeCustom (line 133) | func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender...

FILE: doc/md_docs_test.go
  function TestGenMdDoc (line 26) | func TestGenMdDoc(t *testing.T) {
  function TestGenMdDocWithNoLongOrSynopsis (line 44) | func TestGenMdDocWithNoLongOrSynopsis(t *testing.T) {
  function TestGenMdNoHiddenParents (line 58) | func TestGenMdNoHiddenParents(t *testing.T) {
  function TestGenMdNoTag (line 81) | func TestGenMdNoTag(t *testing.T) {
  function TestGenMdTree (line 94) | func TestGenMdTree(t *testing.T) {
  function BenchmarkGenMarkdownToFile (line 111) | func BenchmarkGenMarkdownToFile(b *testing.B) {

FILE: doc/rest_docs.go
  function printOptionsReST (line 30) | func printOptionsReST(buf *bytes.Buffer, cmd *cobra.Command, name string...
  function defaultLinkHandler (line 52) | func defaultLinkHandler(name, ref string) string {
  function GenReST (line 57) | func GenReST(cmd *cobra.Command, w io.Writer) error {
  function GenReSTCustom (line 62) | func GenReSTCustom(cmd *cobra.Command, w io.Writer, linkHandler func(str...
  function GenReSTTree (line 138) | func GenReSTTree(cmd *cobra.Command, dir string) error {
  function GenReSTTreeCustom (line 145) | func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender fun...
  function indentString (line 173) | func indentString(s, p string) string {

FILE: doc/rest_docs_test.go
  function TestGenRSTDoc (line 26) | func TestGenRSTDoc(t *testing.T) {
  function TestGenRSTNoHiddenParents (line 43) | func TestGenRSTNoHiddenParents(t *testing.T) {
  function TestGenRSTNoTag (line 66) | func TestGenRSTNoTag(t *testing.T) {
  function TestGenRSTTree (line 80) | func TestGenRSTTree(t *testing.T) {
  function BenchmarkGenReSTToFile (line 98) | func BenchmarkGenReSTToFile(b *testing.B) {

FILE: doc/util.go
  function hasSeeAlso (line 26) | func hasSeeAlso(cmd *cobra.Command) bool {
  function forceMultiLine (line 41) | func forceMultiLine(s string) string {
  type byName (line 48) | type byName
    method Len (line 50) | func (s byName) Len() int           { return len(s) }
    method Swap (line 51) | func (s byName) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
    method Less (line 52) | func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() }

FILE: doc/yaml_docs.go
  type cmdOption (line 30) | type cmdOption struct
  type cmdDoc (line 37) | type cmdDoc struct
  function GenYamlTree (line 53) | func GenYamlTree(cmd *cobra.Command, dir string) error {
  function GenYamlTreeCustom (line 60) | func GenYamlTreeCustom(cmd *cobra.Command, dir string, filePrepender, li...
  function GenYaml (line 88) | func GenYaml(cmd *cobra.Command, w io.Writer) error {
  function GenYamlCustom (line 93) | func GenYamlCustom(cmd *cobra.Command, w io.Writer, linkHandler func(str...
  function genFlagResult (line 149) | func genFlagResult(flags *pflag.FlagSet) []cmdOption {

FILE: doc/yaml_docs_test.go
  function TestGenYamlDoc (line 27) | func TestGenYamlDoc(t *testing.T) {
  function TestGenYamlNoTag (line 44) | func TestGenYamlNoTag(t *testing.T) {
  function TestGenYamlTree (line 57) | func TestGenYamlTree(t *testing.T) {
  function TestGenYamlDocRunnable (line 75) | func TestGenYamlDocRunnable(t *testing.T) {
  function BenchmarkGenYamlToFile (line 86) | func BenchmarkGenYamlToFile(b *testing.B) {

FILE: fish_completions.go
  function genFishComp (line 25) | func genFishComp(buf io.StringWriter, name string, includeDesc bool) {
  method GenFishCompletion (line 276) | func (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error {
  method GenFishCompletionFile (line 284) | func (c *Command) GenFishCompletionFile(filename string, includeDesc boo...

FILE: fish_completions_test.go
  function TestCompleteNoDesCmdInFishScript (line 26) | func TestCompleteNoDesCmdInFishScript(t *testing.T) {
  function TestCompleteCmdInFishScript (line 42) | func TestCompleteCmdInFishScript(t *testing.T) {
  function TestProgWithDash (line 59) | func TestProgWithDash(t *testing.T) {
  function TestProgWithColon (line 74) | func TestProgWithColon(t *testing.T) {
  function TestFishCompletionNoActiveHelp (line 89) | func TestFishCompletionNoActiveHelp(t *testing.T) {
  function TestGenFishCompletionFile (line 101) | func TestGenFishCompletionFile(t *testing.T) {
  function TestFailGenFishCompletionFile (line 120) | func TestFailGenFishCompletionFile(t *testing.T) {

FILE: flag_groups.go
  constant requiredAsGroupAnnotation (line 26) | requiredAsGroupAnnotation   = "cobra_annotation_required_if_others_set"
  constant oneRequiredAnnotation (line 27) | oneRequiredAnnotation       = "cobra_annotation_one_required"
  constant mutuallyExclusiveAnnotation (line 28) | mutuallyExclusiveAnnotation = "cobra_annotation_mutually_exclusive"
  method MarkFlagsRequiredTogether (line 33) | func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) {
  method MarkFlagsOneRequired (line 49) | func (c *Command) MarkFlagsOneRequired(flagNames ...string) {
  method MarkFlagsMutuallyExclusive (line 65) | func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) {
  method ValidateFlagGroups (line 81) | func (c *Command) ValidateFlagGroups() error {
  function hasAllFlags (line 111) | func hasAllFlags(fs *flag.FlagSet, flagnames ...string) bool {
  function processFlagForGroupAnnotation (line 121) | func processFlagForGroupAnnotation(flags *flag.FlagSet, pflag *flag.Flag...
  function validateRequiredFlagGroups (line 144) | func validateRequiredFlagGroups(data map[string]map[string]bool) error {
  function validateOneRequiredFlagGroups (line 167) | func validateOneRequiredFlagGroups(data map[string]map[string]bool) error {
  function validateExclusiveFlagGroups (line 188) | func validateExclusiveFlagGroups(data map[string]map[string]bool) error {
  function sortedKeys (line 209) | func sortedKeys(m map[string]map[string]bool) []string {
  method enforceFlagGroupsForCompletion (line 225) | func (c *Command) enforceFlagGroupsForCompletion() {

FILE: flag_groups_test.go
  function TestValidateFlagGroups (line 22) | func TestValidateFlagGroups(t *testing.T) {

FILE: powershell_completions.go
  function genPowerShellComp (line 28) | func genPowerShellComp(buf io.StringWriter, name string, includeDesc boo...
  method genPowerShellCompletion (line 313) | func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool)...
  method genPowerShellCompletionFile (line 320) | func (c *Command) genPowerShellCompletionFile(filename string, includeDe...
  method GenPowerShellCompletionFile (line 331) | func (c *Command) GenPowerShellCompletionFile(filename string) error {
  method GenPowerShellCompletion (line 337) | func (c *Command) GenPowerShellCompletion(w io.Writer) error {
  method GenPowerShellCompletionFileWithDesc (line 342) | func (c *Command) GenPowerShellCompletionFileWithDesc(filename string) e...
  method GenPowerShellCompletionWithDesc (line 348) | func (c *Command) GenPowerShellCompletionWithDesc(w io.Writer) error {

FILE: powershell_completions_test.go
  function TestPwshCompletionNoActiveHelp (line 23) | func TestPwshCompletionNoActiveHelp(t *testing.T) {

FILE: shell_completions.go
  method MarkFlagRequired (line 24) | func (c *Command) MarkFlagRequired(name string) error {
  method MarkPersistentFlagRequired (line 31) | func (c *Command) MarkPersistentFlagRequired(name string) error {
  function MarkFlagRequired (line 38) | func MarkFlagRequired(flags *pflag.FlagSet, name string) error {
  method MarkFlagFilename (line 44) | func (c *Command) MarkFlagFilename(name string, extensions ...string) er...
  method MarkFlagCustom (line 54) | func (c *Command) MarkFlagCustom(name string, f string) error {
  method MarkPersistentFlagFilename (line 61) | func (c *Command) MarkPersistentFlagFilename(name string, extensions ......
  function MarkFlagFilename (line 67) | func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...s...
  function MarkFlagCustom (line 77) | func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error {
  method MarkFlagDirname (line 83) | func (c *Command) MarkFlagDirname(name string) error {
  method MarkPersistentFlagDirname (line 90) | func (c *Command) MarkPersistentFlagDirname(name string) error {
  function MarkFlagDirname (line 96) | func MarkFlagDirname(flags *pflag.FlagSet, name string) error {

FILE: zsh_completions.go
  method GenZshCompletionFile (line 25) | func (c *Command) GenZshCompletionFile(filename string) error {
  method GenZshCompletion (line 31) | func (c *Command) GenZshCompletion(w io.Writer) error {
  method GenZshCompletionFileNoDesc (line 36) | func (c *Command) GenZshCompletionFileNoDesc(filename string) error {
  method GenZshCompletionNoDesc (line 42) | func (c *Command) GenZshCompletionNoDesc(w io.Writer) error {
  method MarkZshCompPositionalArgumentFile (line 55) | func (c *Command) MarkZshCompPositionalArgumentFile(argPosition int, pat...
  method MarkZshCompPositionalArgumentWords (line 66) | func (c *Command) MarkZshCompPositionalArgumentWords(argPosition int, wo...
  method genZshCompletionFile (line 70) | func (c *Command) genZshCompletionFile(filename string, includeDesc bool...
  method genZshCompletion (line 80) | func (c *Command) genZshCompletion(w io.Writer, includeDesc bool) error {
  function genZshComp (line 87) | func genZshComp(buf io.StringWriter, name string, includeDesc bool) {

FILE: zsh_completions_test.go
  function TestZshCompletionWithActiveHelp (line 23) | func TestZshCompletionWithActiveHelp(t *testing.T) {
Condensed preview — 65 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (681K chars).
[
  {
    "path": ".github/dependabot.yml",
    "chars": 241,
    "preview": "version: 2\nupdates:\n- package-ecosystem: gomod\n  directory: /\n  schedule:\n    interval: weekly\n  open-pull-requests-limi"
  },
  {
    "path": ".github/labeler.yml",
    "chars": 597,
    "preview": "# changes to documentation generation\n\"area/docs-generation\": \n- changed-files:\n  - any-glob-to-any-file: 'doc/**'\n\n# ch"
  },
  {
    "path": ".github/workflows/labeler.yml",
    "chars": 387,
    "preview": "name: \"Pull Request Labeler\"\non:\n- pull_request_target\n\npermissions:\n  contents: read\n\njobs:\n  triage:\n    permissions:\n"
  },
  {
    "path": ".github/workflows/test.yml",
    "chars": 2500,
    "preview": "name: Test\n\non:\n  push:\n  pull_request:\n  workflow_dispatch:\n\nenv:\n  GO111MODULE: on\n\npermissions:\n  contents: read\n\njob"
  },
  {
    "path": ".gitignore",
    "chars": 484,
    "preview": "# 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 spe"
  },
  {
    "path": ".golangci.yml",
    "chars": 1545,
    "preview": "# Copyright 2013-2023 The Cobra Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may no"
  },
  {
    "path": ".mailmap",
    "chars": 171,
    "preview": "Steve Francia <steve.francia@gmail.com>\nBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>\nFabiano Franz <ffranz@redhat"
  },
  {
    "path": "CONDUCT.md",
    "chars": 3122,
    "preview": "## Cobra User Contract\n\n### Versioning\nCobra will follow a steady release cadence. Non breaking changes will be released"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 2097,
    "preview": "# Contributing to Cobra\n\nThank you so much for contributing to Cobra. We appreciate your time and help.\nHere are some gu"
  },
  {
    "path": "LICENSE.txt",
    "chars": 10140,
    "preview": "                                Apache License\n                           Version 2.0, January 2004\n                    "
  },
  {
    "path": "MAINTAINERS",
    "chars": 137,
    "preview": "maintainers:\n- spf13\n- johnSchnake\n- jpmcb\n- marckhouzam\ninactive:\n- anthonyfok\n- bep\n- bogem\n- broady\n- eparis\n- jharsh"
  },
  {
    "path": "Makefile",
    "chars": 907,
    "preview": "BIN=\"./bin\"\nSRC=$(shell find . -name \"*.go\")\n\nifeq (, $(shell which golangci-lint))\n$(warning \"could not find golangci-l"
  },
  {
    "path": "README.md",
    "chars": 4949,
    "preview": "<div align=\"center\">\n<a href=\"https://cobra.dev\">\n<img width=\"512\" height=\"535\" alt=\"cobra-logo\" src=\"https://github.com"
  },
  {
    "path": "SECURITY.md",
    "chars": 5109,
    "preview": "# Security Policy\n\n## Reporting a Vulnerability\n\nThe `cobra` maintainers take security issues seriously and\nwe appreciat"
  },
  {
    "path": "active_help.go",
    "chars": 2634,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "active_help_test.go",
    "chars": 12293,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "args.go",
    "chars": 4110,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "args_test.go",
    "chars": 14875,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "bash_completions.go",
    "chars": 23022,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "bash_completionsV2.go",
    "chars": 17851,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "bash_completionsV2_test.go",
    "chars": 1007,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "bash_completions_test.go",
    "chars": 10211,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "cobra.go",
    "chars": 7481,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "cobra_test.go",
    "chars": 7056,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "command.go",
    "chars": 61142,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "command_notwin.go",
    "chars": 689,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "command_test.go",
    "chars": 80115,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "command_win.go",
    "chars": 1053,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "completions.go",
    "chars": 38776,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "completions_test.go",
    "chars": 117138,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "doc/cmd_test.go",
    "chars": 3539,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "doc/man_docs.go",
    "chars": 7349,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "doc/man_docs_test.go",
    "chars": 6560,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "doc/man_examples_test.go",
    "chars": 1189,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "doc/md_docs.go",
    "chars": 4654,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "doc/md_docs_test.go",
    "chars": 3634,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "doc/rest_docs.go",
    "chars": 5294,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "doc/rest_docs_test.go",
    "chars": 3118,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "doc/util.go",
    "chars": 1553,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "doc/yaml_docs.go",
    "chars": 4945,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "doc/yaml_docs_test.go",
    "chars": 2645,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "fish_completions.go",
    "chars": 11534,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "fish_completions_test.go",
    "chars": 4002,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "flag_groups.go",
    "chars": 9620,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "flag_groups_test.go",
    "chars": 8893,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "go.mod",
    "chars": 196,
    "preview": "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/m"
  },
  {
    "path": "go.sum",
    "chars": 1088,
    "preview": "github.com/cpuguy83/go-md2man/v2 v2.0.6 h1:XJtiaUW6dEEqVuZiMTn1ldk455QWwEIsMIJlo5vtkx0=\ngithub.com/cpuguy83/go-md2man/v2"
  },
  {
    "path": "powershell_completions.go",
    "chars": 13611,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "powershell_completions_test.go",
    "chars": 1000,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "shell_completions.go",
    "chars": 4349,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "site/content/active_help.md",
    "chars": 8638,
    "preview": "# Active Help\n\nActive Help is a framework provided by Cobra which allows a program to define messages (hints, warnings, "
  },
  {
    "path": "site/content/completions/_index.md",
    "chars": 28046,
    "preview": "# Generating shell completions\n\nCobra can generate shell completions for multiple shells.\nThe currently supported shells"
  },
  {
    "path": "site/content/completions/bash.md",
    "chars": 3794,
    "preview": "# Generating Bash Completions For Your cobra.Command\n\nPlease refer to [Shell Completions](_index.md) for details.\n\n## Ba"
  },
  {
    "path": "site/content/completions/fish.md",
    "chars": 116,
    "preview": "## 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",
    "chars": 147,
    "preview": "# Generating PowerShell Completions For Your Own cobra.Command\n\nPlease refer to [Shell Completions](_index.md#powershell"
  },
  {
    "path": "site/content/completions/zsh.md",
    "chars": 3636,
    "preview": "## Generating Zsh Completion For Your cobra.Command\n\nPlease refer to [Shell Completions](_index.md) for details.\n\n## Zsh"
  },
  {
    "path": "site/content/docgen/_index.md",
    "chars": 445,
    "preview": "# Documentation generation\n\n- [Man page docs](man.md)\n- [Markdown docs](md.md)\n- [Rest docs](rest.md)\n- [Yaml docs](yaml"
  },
  {
    "path": "site/content/docgen/man.md",
    "chars": 519,
    "preview": "# Generating Man Pages For Your Own cobra.Command\n\nGenerating man pages from a cobra command is incredibly easy. An exam"
  },
  {
    "path": "site/content/docgen/md.md",
    "chars": 2794,
    "preview": "# Generating Markdown Docs For Your Own cobra.Command\n\nGenerating Markdown pages from a cobra command is incredibly easy"
  },
  {
    "path": "site/content/docgen/rest.md",
    "chars": 2903,
    "preview": "# Generating ReStructured Text Docs For Your Own cobra.Command\n\nGenerating ReST pages from a cobra command is incredibly"
  },
  {
    "path": "site/content/docgen/yaml.md",
    "chars": 2688,
    "preview": "# Generating Yaml Docs For Your Own cobra.Command\n\nGenerating yaml files from a cobra command is incredibly easy. An exa"
  },
  {
    "path": "site/content/projects_using_cobra.md",
    "chars": 3464,
    "preview": "## Projects using Cobra\n\n- [Allero](https://github.com/allero-io/allero)\n- [Arewefastyet](https://benchmark.vitess.io)\n-"
  },
  {
    "path": "site/content/user_guide.md",
    "chars": 27070,
    "preview": "# User Guide\n\nWhile you are welcome to provide your own organization, typically a Cobra-based\napplication will follow th"
  },
  {
    "path": "zsh_completions.go",
    "chars": 11020,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  },
  {
    "path": "zsh_completions_test.go",
    "chars": 995,
    "preview": "// Copyright 2013-2023 The Cobra Authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you ma"
  }
]

About this extraction

This page contains the full source code of the spf13/cobra GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 65 files (612.2 KB), approximately 167.0k tokens, and a symbol index with 654 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!