Coder Social home page Coder Social logo

cobra-cli's Introduction

Cobra Generator

Cobra provides its own program that will create your application and add any commands you want. It's the easiest way to incorporate Cobra into your application.

Install the cobra generator with the command go install github.com/spf13/cobra-cli@latest. Go will automatically install it in your $GOPATH/bin directory which should be in your $PATH.

Once installed you should have the cobra-cli command available. Confirm by typing cobra-cli at a command line.

There are only two operations currently supported by the Cobra generator:

cobra-cli init

The cobra-cli init [app] command will create your initial application code for you. It is a very powerful application that will populate your program with the right structure so you can immediately enjoy all the benefits of Cobra. It can also apply the license you specify to your application.

With the introduction of Go modules, the Cobra generator has been simplified to take advantage of modules. The Cobra generator works from within a Go module.

Initalizing a module

If you already have a module, skip this step.

If you want to initialize a new Go module:

  1. Create a new directory
  2. cd into that directory
  3. run go mod init <MODNAME>

e.g.

cd $HOME/code 
mkdir myapp
cd myapp
go mod init github.com/spf13/myapp

Initalizing a Cobra CLI application

From within a Go module run cobra-cli init. This will create a new barebones project for you to edit.

You should be able to run your new application immediately. Try it with go run main.go.

You will want to open up and edit 'cmd/root.go' and provide your own description and logic.

e.g.

cd $HOME/code/myapp
cobra-cli init
go run main.go

cobra-cli init can also be run from a subdirectory such as how the cobra generator itself is organized. This is useful if you want to keep your application code separate from your library code.

Optional flags:

You can provide it your author name with the --author flag. e.g. cobra-cli init --author "Steve Francia [email protected]"

You can provide a license to use with --license e.g. cobra-cli init --license apache

Use the --viper flag to automatically setup viper

Viper is a companion to Cobra intended to provide easy handling of environment variables and config files and seamlessly connecting them to the application flags.

Add commands to a project

Once a cobra application is initialized you can continue to use the Cobra generator to add additional commands to your application. The command to do this is cobra-cli add.

Let's say you created an app and you wanted the following commands for it:

  • app serve
  • app config
  • app config create

In your project directory (where your main.go file is) you would run the following:

cobra-cli add serve
cobra-cli add config
cobra-cli add create -p 'configCmd'

cobra-cli add supports all the same optional flags as cobra-cli init does (described above).

You'll notice that this final command has a -p flag. This is used to assign a parent command to the newly added command. In this case, we want to assign the "create" command to the "config" command. All commands have a default parent of rootCmd if not specified.

By default cobra-cli will append Cmd to the name provided and uses this name for the internal variable name. When specifying a parent, be sure to match the variable name used in the code.

Note: Use camelCase (not snake_case/kebab-case) for command names. Otherwise, you will encounter errors. For example, cobra-cli add add-user is incorrect, but cobra-cli add addUser is valid.

Once you have run these three commands you would have an app structure similar to the following:

  ▾ app/
    ▾ cmd/
        config.go
        create.go
        serve.go
        root.go
      main.go

At this point you can run go run main.go and it would run your app. go run main.go serve, go run main.go config, go run main.go config create along with go run main.go help serve, etc. would all work.

You now have a basic Cobra-based application up and running. Next step is to edit the files in cmd and customize them for your application.

For complete details on using the Cobra library, please read the The Cobra User Guide.

Have fun!

Configuring the cobra generator

The Cobra generator will be easier to use if you provide a simple configuration file which will help you eliminate providing a bunch of repeated information in flags over and over.

An example ~/.cobra.yaml file:

author: Steve Francia <[email protected]>
license: MIT
useViper: true

You can also use built-in licenses. For example, GPLv2, GPLv3, LGPL, AGPL, MIT, 2-Clause BSD or 3-Clause BSD.

You can specify no license by setting license to none or you can specify a custom license:

author: Steve Francia <[email protected]>
year: 2020
license:
  header: This file is part of CLI application foo.
  text: |
    {{ .copyright }}

    This is my license. There are many like it, but this one is mine.
    My license is my best friend. It is my life. I must master it as I must
    master my life.

In the above custom license configuration the copyright line in the License text is generated from the author and year properties. The content of the LICENSE file is

Copyright © 2020 Steve Francia <[email protected]>

This is my license. There are many like it, but this one is mine.
My license is my best friend. It is my life. I must master it as I must
master my life.

The header property is used as the license header files. No interpolation is done. This is the example of the go file header.

/*
Copyright © 2020 Steve Francia <[email protected]>
This file is part of CLI application foo.
*/

cobra-cli's People

Contributors

acehinnnqru avatar andreaangiolillo avatar andregri avatar anthonyfok avatar bruceadowns avatar darklore avatar dependabot[bot] avatar jbydeley avatar jharshman avatar johnschnake avatar jpmcb avatar kaitou-1412 avatar kkirsche avatar krtffl avatar liggitt avatar marckhouzam avatar n10v avatar nsapse avatar puiterwijk avatar rajatjindal avatar robbyt avatar sobit avatar spf13 avatar stevenpitts avatar swinslow avatar theothertomelliott avatar timecode avatar umarcor avatar wfernandes avatar yann-soubeyrand avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cobra-cli's Issues

The execute path of import is wrong after generated by cobra-cli command

  1. Create a demo
mkdir -p cobra
cd cobra
cobra-cli init --viper demo
  1. Check the generated main.go file
$ cat demo/main.go 
/*
Copyright © 2023 NAME HERE <EMAIL ADDRESS>
*/
package main

import "github.con/cuizhaoyue/go-demo/cobra/cmd"

func main() {
        cmd.Execute()
}
  1. the import in main.go is wrong
    The correct path should be
github.con/cuizhaoyue/go-demo/cobra/demo/cmd

rather than

github.con/cuizhaoyue/go-demo/cobra/cmd
  1. version info
    The cobra-cli version is the latest version as of 2023-03-04

Error: unknown flag: --pkg-name when cobra-cli init

Hi, noob here. I have been trying to learn to use cobra, all the tutorials uses --pkg-name flag. However when I use it like this
cobra-cli init --pkg-name=github.com/samozturk/randompackage it says Error: unknown flag: --pkg-name Usage: cobra-cli init [path] [flags]

Are these tutorials outdated or am I doing something wrong?

Create Template from Interface so users can define their own templates

Hi there!

I'm proposing a change to cobra-cli that would allow this command to find some way to make the tpl package more customizable.

Use case:

We have a CLI that our dozen+ person team all contributes to in order to be more effective at our jobs. This has made this cobra CLI to become incredibly complex through organic growth. The way we declare our arguments has deviated from the base template that's provided, and we have extended the Command interface to better suit our use case through inheritance. With those changes (which are slowly being rolled out to our codebase) I think it would be nice to be able to use this command utility with a custom template defined within our codebase for how a "new empty command" should look like, compared to our current workflow of copying a "simpler" command file, and trying to change all of the things to get it working.

Ideally - there would be some pre-defined directory or file within the root of a cobra-based project that would declare the templates, and then only if that file is present the cobra-cli tool would automatically default to using that template for new commands rather than the one defined within the tpl package inside this repo.

I'm more than happy to work on building out this feature, if you like the idea.

Thanks for your consideration,
Kirk

Enhancement: modification required in the "Long" description of add subcommand

It's currently `Add (cobra add) will create a new command, with a license and
the appropriate structure for a Cobra-based CLI application,
and register it to its parent (default rootCmd).

If you want your command to be public, pass in the command name
with an initial uppercase letter.

Example: cobra add server -> resulting in a new cmd/server.go`

This needs to be modified according to "cobra-cli" i.e. cobra add server -> cobra-cli add server
Similar changes are required everywhere.

-bash: cobra-cli: command not found

Hi,

I'm running on command not found when installing the cli.

Steps I did:

  1. Install cli by running: go install github.com/spf13/cobra-cli@latest
  2. Making sure my ~/.bashrc contains $GOPATH: exportPATH="$PATH:/Users/daniperez/.local/bin:$GOPATH/bin"
  3. source ~/.bashrc
  4. Try cobra-cli command

I double checked and cobra-cli is present under go/bin: cobra-cli controller-gen gopls
If it helps I'm running on a macOs Monterey v12.7.1

Am I doing something wrong?

Completion for zsh seems not working on macOS

Hi.

It seems the code completion is not working in zsh environment.

Environment

Apple M1 Pro with macOS Monterey 12.5.1

Steps to reproduce

mkdir myapp
cd myapp
go mod init myapp
cobra-cli init
cobra-cli add serve
go build .
./myapp completion zsh > /tmp/completion
source /tmp/completion

now, try to complete:

./myapp se[TAB]

nothing is completed after hitting TAB (even multiple hits), but it should complete the serve command.

Generated zsh code

% cat /tmp/completion
#compdef myapp

# zsh completion for myapp                                -*- shell-script -*-

__myapp_debug()
{
    local file="$BASH_COMP_DEBUG_FILE"
    if [[ -n ${file} ]]; then
        echo "$*" >> "${file}"
    fi
}

_myapp()
{
    local shellCompDirectiveError=1
    local shellCompDirectiveNoSpace=2
    local shellCompDirectiveNoFileComp=4
    local shellCompDirectiveFilterFileExt=8
    local shellCompDirectiveFilterDirs=16

    local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace
    local -a completions

    __myapp_debug "\n========= starting completion logic =========="
    __myapp_debug "CURRENT: ${CURRENT}, words[*]: ${words[*]}"

    # The user could have moved the cursor backwards on the command-line.
    # We need to trigger completion from the $CURRENT location, so we need
    # to truncate the command-line ($words) up to the $CURRENT location.
    # (We cannot use $CURSOR as its value does not work when a command is an alias.)
    words=("${=words[1,CURRENT]}")
    __myapp_debug "Truncated words[*]: ${words[*]},"

    lastParam=${words[-1]}
    lastChar=${lastParam[-1]}
    __myapp_debug "lastParam: ${lastParam}, lastChar: ${lastChar}"

    # For zsh, when completing a flag with an = (e.g., myapp -n=<TAB>)
    # completions must be prefixed with the flag
    setopt local_options BASH_REMATCH
    if [[ "${lastParam}" =~ '-.*=' ]]; then
        # We are dealing with a flag with an =
        flagPrefix="-P ${BASH_REMATCH}"
    fi

    # Prepare the command to obtain completions
    requestComp="${words[1]} __complete ${words[2,-1]}"
    if [ "${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 completion code.
        __myapp_debug "Adding extra empty parameter"
        requestComp="${requestComp} \"\""
    fi

    __myapp_debug "About to call: eval ${requestComp}"

    # Use eval to handle any environment variables and such
    out=$(eval ${requestComp} 2>/dev/null)
    __myapp_debug "completion output: ${out}"

    # Extract the directive integer following a : from the last line
    local lastLine
    while IFS='\n' read -r line; do
        lastLine=${line}
    done < <(printf "%s\n" "${out[@]}")
    __myapp_debug "last line: ${lastLine}"

    if [ "${lastLine[1]}" = : ]; then
        directive=${lastLine[2,-1]}
        # Remove the directive including the : and the newline
        local suffix
        (( suffix=${#lastLine}+2))
        out=${out[1,-$suffix]}
    else
        # There is no directive specified.  Leave $out as is.
        __myapp_debug "No directive found.  Setting do default"
        directive=0
    fi

    __myapp_debug "directive: ${directive}"
    __myapp_debug "completions: ${out}"
    __myapp_debug "flagPrefix: ${flagPrefix}"

    if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
        __myapp_debug "Completion received error. Ignoring completions."
        return
    fi

    local activeHelpMarker="_activeHelp_ "
    local endIndex=${#activeHelpMarker}
    local startIndex=$((${#activeHelpMarker}+1))
    local hasActiveHelp=0
    while IFS='\n' read -r comp; do
        # Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker)
        if [ "${comp[1,$endIndex]}" = "$activeHelpMarker" ];then
            __myapp_debug "ActiveHelp found: $comp"
            comp="${comp[$startIndex,-1]}"
            if [ -n "$comp" ]; then
                compadd -x "${comp}"
                __myapp_debug "ActiveHelp will need delimiter"
                hasActiveHelp=1
            fi

            continue
        fi

        if [ -n "$comp" ]; then
            # If requested, completions are returned with a description.
            # The description is preceded by a TAB character.
            # For zsh's _describe, we need to use a : instead of a TAB.
            # We first need to escape any : as part of the completion itself.
            comp=${comp//:/\\:}

            local tab="$(printf '\t')"
            comp=${comp//$tab/:}

            __myapp_debug "Adding completion: ${comp}"
            completions+=${comp}
            lastComp=$comp
        fi
    done < <(printf "%s\n" "${out[@]}")

    # Add a delimiter after the activeHelp statements, but only if:
    # - there are completions following the activeHelp statements, or
    # - file completion will be performed (so there will be choices after the activeHelp)
    if [ $hasActiveHelp -eq 1 ]; then
        if [ ${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then
            __myapp_debug "Adding activeHelp delimiter"
            compadd -x "--"
            hasActiveHelp=0
        fi
    fi

    if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then
        __myapp_debug "Activating nospace."
        noSpace="-S ''"
    fi

    if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
        # File extension filtering
        local filteringCmd
        filteringCmd='_files'
        for filter in ${completions[@]}; do
            if [ ${filter[1]} != '*' ]; then
                # zsh requires a glob pattern to do file filtering
                filter="\*.$filter"
            fi
            filteringCmd+=" -g $filter"
        done
        filteringCmd+=" ${flagPrefix}"

        __myapp_debug "File filtering command: $filteringCmd"
        _arguments '*:filename:'"$filteringCmd"
    elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
        # File completion for directories only
        local subdir
        subdir="${completions[1]}"
        if [ -n "$subdir" ]; then
            __myapp_debug "Listing directories in $subdir"
            pushd "${subdir}" >/dev/null 2>&1
        else
            __myapp_debug "Listing directories in ."
        fi

        local result
        _arguments '*:dirname:_files -/'" ${flagPrefix}"
        result=$?
        if [ -n "$subdir" ]; then
            popd >/dev/null 2>&1
        fi
        return $result
    else
        __myapp_debug "Calling _describe"
        if eval _describe "completions" completions $flagPrefix $noSpace; then
            __myapp_debug "_describe found some completions"

            # Return the success of having called _describe
            return 0
        else
            __myapp_debug "_describe did not find completions."
            __myapp_debug "Checking if we should do file completion."
            if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
                __myapp_debug "deactivating file completion"

                # We must return an error code here to let zsh know that there were no
                # completions found by _describe; this is what will trigger other
                # matching algorithms to attempt to find completions.
                # For example zsh can match letters in the middle of words.
                return 1
            else
                # Perform file completion
                __myapp_debug "Activating file completion"

                # We must return the result of this command, so it must be the
                # last command, or else we must store its result to return it.
                _arguments '*:filename:_files'" ${flagPrefix}"
            fi
        fi
    fi
}

# don't run the completion function when being source-ed or eval-ed
if [ "$funcstack[1]" = "_myapp" ]; then
    _myapp
fi

Is this a bug, or am I doing something wrong? 😕

TIA

Can the cobra CLI be changed to specify file name & variable name?

Moving from spf13/cobra#1381

For example:

cobra add foo--bar--baz --var-name=foo_bar_bazCmd -p 'parentCmd'
// generates cmd/foo--bar--baz.go
Similarly, it'd be nice if I can run the cobra command in the current directory instead of the root repo directory, for example like:

~/workspace/my-cli/cmd/subcommand $ cobra add -p 'subcommandCmd' .

coba-cli overwrites existing main.go with no warning

When run in an existing project, cobra-cli init will silently overwrite an existing main.go.

In this situation, cobra-cli should emit an error and exit without making changes rather than overwriting existing code.

Cobra-Cli init Error

Error using "cobra-cli ini" --> Error: invalid character '{' after top-level value

Go version : 1.18.1
VsCode : 1.66.1

Cannot run in docker img: busybox,scratch; output: . /bin: no such file or directory

my bin:

cobra-cli init --viper
Your Cobra application is ready at ...

sudo docker build -t bin . && sudo docker run -it --rm bin
Step 1/3 : FROM scratch
---> 
Step 2/3 : COPY ${PWD}/bin .
---> f18dcc8e0e25
Step 3/3 : ENTRYPOINT ["./bin"]
---> Running in dc5fd26d812f
Removing intermediate container dc5fd26d812f
---> ee78f634bd9f
Successfully built ee78f634bd9f
Successfully tagged bin:latest
exec ./bin: no such file or directory

my Dockerfile

FROM scratch
COPY ${PWD}/bin .
ENTRYPOINT ["./bin"]

About...

debian and local is fine
golang: 1.18.2
cobra: 1.4.0
viper: 1.11.0

discrepancy between DBTIMEZONE and SYSTIMESTAMP

How to make the following WARNING gone?

godror WARNING: discrepancy between DBTIMEZONE ("+00:00"=0) and SYSTIMESTAMP ("-05:00"=-500) - set connection timezone, see https://github.com/godror/godror/blob/master/doc/timezone.md

I tried to play with Timezone in CommonParms, don't know if this is right place to set up something and if so what correct value here

``
39 CommonParams: dsn.CommonParams{
40 Username: p_username,
41 Password: dsn.NewPassword(p_password),
42 ConnectString: connString,
43 // Timezone: time.FixedZone("UTC-5", -55050), // need to figure out what is the correct value

Regression: Unknown license with the `--license <my-file>.yaml` flag

Looks like a regression that was previously fixed has been reintroduced between 1.2.1 and 1.3.0 and effects 1.4.0 and then got migrated along to this new repository. I get an error when I try to specify a custom license.

spf13/cobra#321

Error: unknown license: /Users/paul/.my-license.yaml

I have a template that I use for my license, here is an example of what it looks like:

author: Me
license:
  header: Buy me a covfefe?
  text: |
    {{ .copyright }}

To recreate:

$ go install github.com/spf13/cobra-cli@latest
$ mkdir example
$ cd example
$ go mod init example
$ cobra-cli init --license ~/.my-license.yaml
> Error: unknown license: /Users/paul/.my-license.yaml

latest version cobra-cli: command not found

mkdir myapp
cd myapp
go mod init github.com/spf13/myapp

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

When I excute cobra-cli init , -bash: cobra-cli: command not found
windows system: 'cobra-cli' is not recognized as an internal or external command,
operable program or batch file.
why? A month ago is normal!

Does not contain package GitHub.com/spf13/cobra-cli

Just trying to install this on my M1 Mac, and it keeps giving me this error:

go: github.com/spf13/cobra-cli@latest: module github.com/spf13/cobra-cli@latest found (v1.3.0), but does not contain package github.com/spf13/cobra-cli

The command I'm running is a copy/paste from the readme: go install github.com/spf13/cobra-cli@latest

I'm running Sonoma 14.2, with iTerm Build 3.4.22 and Zsh 5.9 (x86_64-apple-darwin23.0). I checked the previous issues, followed what they said, but to no avail! So... what am I doing wrong?

Thanks!

About subcommand directory

This is transfer of @fanux's spf13/cobra#1059 as suggested there by @johnSchnake


➜  app cobra add create
create created at /Users/fanux/work/src/app/cmd/create.go
➜  app cobra add user -p create
user created at /Users/fanux/work/src/app/cmd/user.go
➜  app tree
.
├── LICENSE
├── cmd
│   ├── create.go
│   ├── root.go
│   └── user.go
└── main.go

cobra generates subcommand user in the same dir of its parent dir, it not very nice.

If I add a command user this user command is not create subcommand:

 cobra add user
Error: /Users/fanux/work/src/app/cmd/user.go already exists

So I think, create subcommand in a sub dir is better, like this:

.
├── LICENSE
├── cmd
│   ├── create.go
│   ├── root.go
|   |---create
│       └── user.go
└── main.go

This will not conflict

Allow users to use exact command name in 'add -p'

Enhancement

Currently, the user of the cli has to append 'Cmd' to the parent command name when adding a child command.
I believe it would be a small improvement in the user experience if the command name could be used directly, as the user does in other commands.

Current behaviour:

cobra-cli add config
cobra-cli add set -p 'configCmd'

Proposed behaviour:

cobra-cli add config
cobra-cli add set -p config

Solution

A possible solution is to have the add command append 'Cmd' to the given parent command name, similar to how commandName is validated.

Don't touch my licence

It'd be neat if cobra didn't touch an already existing LICENCE file. I have to revert changes every time I use cobra.

Go 1.18 workspace support in cobra-cli init

When attempting to use cobra-cli init in a project that uses Go 1.18's new workspace mode, I hit what looks like a JSON unmarshaling error (Error: invalid character '{' after top-level value) and initializing fails.

My apologies in advance if I'm misunderstanding any aspect of workspaces, modules, or cobra-cli here - I'm fairly new to Go, but expecting this might be a new edge case in 1.18 due to workspaces.

Steps to reproduce

mkdir cli-playground && cd cli-playground
go work init
mkdir project1 && cd project1 && go mod init project1 && cd ..
mkdir project2 && cd project2 && go mod init project2 && cd ..
go work use project1 project2
cd project2
cobra-cli init
#=> go: creating new go.mod: module project1
#=> go: creating new go.mod: module project2
#=> Error: invalid character '{' after top-level value

I believe this is because go list -json -m returns a stream of JSON objects with relevant modules, whereas this bit of code expects to consume a single JSON object.

I spiked out a test in investigating this behavior, which exposes the same behavior as above. But I’m guessing that approach only works for Go 1.18+, and cobra-cli probably wants to support earlier versions. As far as a fix (if we agree it's worth addressing), I was thinking that the parseModInfo operations could potentially allow using the current directory (from the output of go list -json -e) to decide which of the JSON objects to use. Thoughts?

Workaround

Removing all projects from the workspace except the one I want to cobra-cli init does let things work, and that's good enough to unblock me.

Additional potential gotcha

In experimenting with removing workspace items, there's another case that has surprising (to me) behavior: if we try running cobra-cli init on a module that's not yet included in the workspace.

mkdir cli-playground && cd cli-playground
go work init
mkdir project1 && cd project1 && go mod init project1 && cd ..
mkdir project2 && cd project2 && go mod init project2 && cd ..
go work use project1
cd project2
cobra-cli init

The above appears to succeed, but the contents of project2/main.go are now:

/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>

*/
package main

import "project1/tmp/cli-playground/project2/cmd"

func main() {
        cmd.Execute()
}

I'm honestly not sure what behavior I'd expect here, since the module isn't in the workspace. But the import path project1/tmp/cli-playground/project2/cmd looks pretty wrong to me (note both project1 and project2 in that path, despite them being peers). I can totally understand this scenario being unsupported / undefined behavior,

But I thought it could be useful to include it in this report, both because I think the existing behavior is kind of surprising (I might personally prefer an error), and more importantly because I imagine that the choice of which module to pick from the list in go list -json -m could potentially create better behavior here.

subcommand receives 2 args but report receives 0 when using MinimumNArgs(2) check args in the Args member of command.

......
Args: cobra.MatchAll(cobra.MinimumNArgs(2), cobra.OnlyValidArgs),
Run: cropCmdRun,
}
.....
func cropCmdRun(cmd *cobra.Command, args []string) {
fmt.Println("crop calling .....")

fmt.Printf("args :%v \n", spew.Sdump(args))

......

build the source and run like follow:
utils.exe crop -s=src.png -c=i.cvs
Error: requires at least 2 arg(s), only received 0
Usage:
utils crop [flags]
......

if remove the MinimumNArgs like this :
...
Args: cobra.MatchAll(cobra.OnlyValidArgs),
...

build and run like follow:
utils.exe crop -s=src.png -c=i.cvs
crop calling .....
args :([]string) (cap=2) {
}

Labels, Milestones, Triaging ⚡

Labels, Milestones, Triaging ⚡

The following is a living issue, pinned to the top of cobra-cli's GitHub issues for wide visibility, available for comment, that represents the current labeling, triaging, milestone, and maintenance state of cobra-cli. Maintainers, contributors, and users may refer to this in order to understand how bugs and features are being triaged and where their feature request may be in the maintenance cycle.

Inspired by projects like kubernetes-sigs/cluster-api, helm/helm and spf13/cobra

Labels 🏷️

kind/ - The type of issue

  • kind/bug: A bug in cobra-cli; unintended behavior
  • kind/feature: A feature request for cobra-cli; new or enhanced behavior
  • kind/documentation: Documentation of cobra-cli itself
  • kind/testing: CI/CD, testing, etc. for cobra-cli. Usually also gets the github label
  • kind/rel-eng: Related to tagging and releasing cobra-cli
  • kind/upstream: Go modules cobra-cli depends on
  • kind/security: Related to security of cobra-cli itself. Refer to the security policy before opening any public issue.
  • kind/cleanup: General cleanup of code, issues, etc.
  • kind/deprecation: Related to a feature or part of code being deprecated
  • kind/support: Questions, supporting users, etc.

area/ - The area of work that needs to be executed against

  • area/cobra-cli: Core functionality of cobra-cli
  • area/go: General Go, like go.mod or go.sum changes
  • area/github: For changes to Github specific things not shipped in the library (like maintainers files, actions, etc)
  • area/licenses: Changes to license functionality

triage/ - The state of an issue being triaged

  • triage/needs-triage: Needs to be placed into a milestone, or be closed by maintainers. This label is removed once placed into a milestone.
  • triage/blocked: Cannot move forward until some roadblock is lifted
  • triage/needs-info: An issue that needs more investigation from maintainers or more info from the issue provider
  • triage/duplicate: A duplicate issue. These issues are usually closed after receiving this label.

lifecycle/ - Where something is at in it's lifecycle

  • lifecycle/needs-cla: The CLA still needs to be signed by the PR author. This label is blocking until the CLA is signed.
  • lifecycle/active: Actively being worked on by a community member or maintainer. This label should generally also correspond with someone being assigned to an issue
  • lifecycle/needs-proposal: For large features / bugs that need a proposal and community buy in
  • lifecycle/approved: For large features / bugs that have a proposal and have community buy in
  • lifecycle/needs-pr: Ready for a PR from the community
  • lifecycle/stale: Labeled by GitHub actions after 30 days of inactivity
  • lifecycle/rotten: Labeled by GitHub actions after 30 days of having the lifecycle/stale label. Issues and PRs with this label will close after another 30 days of inactivity.
  • lifecycle/frozen: Prevents GitHub actions from labeling Issues and PRs with lifecycle/stale or lifecycle/rotten
  • lifecycle/wont-do: For issues and PRs the community has determined are not a priority and will not execute against

size/ - The size of the PR

Utilizes the pr-size-labeler to label PRs with a given size per number of lines changed

  • size/XS: Denotes a PR that changes 0-9 lines
  • size/S: Denotes a PR that changes 10-24 lines
  • size/M: Denotes a PR that changes 24-99 lines
  • size/L: Denotes a PR that changes 100-199 lines
  • size/XL: Denotes a PR that changes 200 or more lines. Note: An XL pull request exceeds the recommended size of changes in a single PR. This is fine, but needs special attention from maintainers and may be rejected due to it's size. Make sure you are not addressing multiple issues in a single PR.

Nice to have, catch all maintenance labels:

  • lgtm: Denotes "looks good to me" from maintainers and signals other collaborators that a PR is ready for additional review and merge
  • good-first-issue: A good issue for a new collaborator to tackle
  • help-wanted: An issue that the maintainers would like help on
  • admin: For general admin tasks to be done usually by maintainers

Milestones 🪨

Milestones are used to categorize work and contributions into specific releases.

  • The next milestone is used as a catch all for work that is being planned for some arbitrary upcoming release by the community
  • The icebox milestone is used to track things that may need to be executed against eventually but are blocked, have the lifecycle/frozen label, etc.
  • Other milestoens may be made to track large feature or bug fixes.

Release cadence 🚂

cobra-cli has no release cadence but attempts to release quarterly alongside when cobra itself is released.

This is a best effort.

Generally, a pinned release tracker issue is made that corresponds with the current release. On release, tags will be made on GitHub that than can be consumed by downstream Go modules.

Semver 🥇

The cobra-cli follows Semantic Versioning. This generally means that:

  • major bumps (i.e. v1.x.x to v2.x.x) have breaking changes (like deprecations, changing APIs, etc). Users of cobra will need to do some work to update their Go code to consume the latest major version
  • minor bumps (i.e v1.1.x to 1.2.x) have no breaking changes, but include new features. Users of cobra will not need to do work to update their Go code to consume the latest minor version, but may choose to use the new features.
  • patch bumps (i.e. v1.1.1 to v1.1.2) do not include new features or breaking changes but only backwards compatible bug fixes. Users of cobra will not need to do work to update their Go code to consume the latest patch version.

For more details, please refer to the Cobra User Contract

tests broken in 2023

running tests
=== RUN   TestGoldenAddCmd
    add_test.go:28: "/build/source/cmd/testproject/cmd/test.go" and "testdata/test.go.golden" are not equal!
        
        $ diff -u /build/source/cmd/testproject/cmd/test.go testdata/test.go.golden
        --- /build/source/cmd/testproject/cmd/test.go   2023-01-19 16:36:00.335867015 +0000
        +++ testdata/test.go.golden     1970-01-01 00:00:01.000000000 +0000
        @@ -1,5 +1,5 @@
         /*
        -Copyright © 2023 NAME HERE <EMAIL ADDRESS>
        +Copyright © 2022 NAME HERE <EMAIL ADDRESS>
         
         Licensed under the Apache License, Version 2.0 (the "License");
         you may not use this file except in compliance with the License.
        
        exit status 1
--- FAIL: TestGoldenAddCmd (0.00s)
=== RUN   TestValidateCmdName
--- PASS: TestValidateCmdName (0.00s)
=== RUN   TestGoldenInitCmd
=== RUN   TestGoldenInitCmd/successfully_creates_a_project_based_on_module
    init_test.go:77: "/build/source/cmd/testproject/main.go" and "testdata/main.go.golden" are not equal!
        
        $ diff -u /build/source/cmd/testproject/main.go testdata/main.go.golden
        --- /build/source/cmd/testproject/main.go       2023-01-19 16:36:00.515874546 +0000
        +++ testdata/main.go.golden     1970-01-01 00:00:01.000000000 +0000
        @@ -1,5 +1,5 @@
         /*
        -Copyright © 2023 NAME HERE <EMAIL ADDRESS>
        +Copyright © 2022 NAME HERE <EMAIL ADDRESS>
         
         Licensed under the Apache License, Version 2.0 (the "License");
         you may not use this file except in compliance with the License.
        
        exit status 1
--- FAIL: TestGoldenInitCmd (0.18s)
    --- FAIL: TestGoldenInitCmd/successfully_creates_a_project_based_on_module (0.18s)
FAIL
FAIL    github.com/spf13/cobra-cli/cmd  0.187s
FAIL

/cc nixpkgs maintainer @ivankovnatsky

[RFC] improve generated boilerplate

spf13/cobra#1614 (comment)

Multiple issues in the spf13/cobra repo were regarding the patterns of globals/init methods which made testing and growth difficult.

This linked issue properly points to the method (I think) most people eventually figure out for themselves.

Moved to this repo due to the CLI being split off.

Introduce new `version` sub command

It would better to provide a new version sub command to cobra-cli:

Actual:

$ cobra-cli version
Error: unknown command "version" for "cobra-cli"

$ cobra-cli --version
Error: unknown flag: --version

Wdyt?

can't create cmd and subcmd with same name, it will be overwrited?

e.g:
run cobra-cli add get, it will generate cmd/get.go
run cobra-cli add config, it will generate cmd/config.go
run cobra-cli add get -p 'configCmd', it will also generate cmd/get.go

the thrid command will overwrite cmd/get.go

finally, we can't have 'app get ' and 'app config get ' two commands at the same time.

How to call a command from another command with flags

Hey, I am trying to call a command with a specific flag from another command but I've been struggling to make it work. Here is what I am doing:

var startCmd = &cobra.Command{
	Use:   "start",
	Short: "The central command for the CLI.",
	Long: `start can execute any of the other commands in the CLI.`,
	Run: func(cmd *cobra.Command, args []string) {
		getCmd.SetArgs([]string{"--data", "price"})
		getCmd.Run(cmd, os.Args[1:])
               // getCmdRun(cmd, []string{"--data", "price"}) -> tried this as well but failed too
	},
}

func init() {
	rootCmd.AddCommand(startCmd)
	startCmd.AddCommand(getCmd)
}

Each time it raises a warning from the getCmd command saying my flag is not recognized. How do we do that?

Create `v1.3.0` tag

In support of spf13/cobra#1597, we want to tag this repository with the same "version" that was used before we migrated the code here. This still communicates the version of the cobra CLI but also represents the final tag that the two will correlate.

In otherwords, this tag is the split in the road that will enable use to seperate cobra from cobra-cli

The release note for v1.3.0 of this repo will note that all previous history and release markers can be tracked in the spf13/cobra repo.

If there are no objections, I will do this within the week 👀

Adding commands with hyphens (-) in the name

I understand the filename is being camel-cased due to some technical reasons, but can't the command name still have the hyphen in the name??

cobra-cli add hello-world, makes the file named helloWorld
Manually changing the Use parameter to hello-world does change the command name to hello-world and works as intended without creating any issues with the file names..
image

Can we modify the command add to include the hyphen in the Use parameter and camel-case it everywhere else as usual? That will prevent users from manually changing the Use parameter and the add command will work as intended!

If this issue will be entertained, I would love to contribute as well!

add path error for win

# cobra-cli init --viper cli 
# cobra-cli add genConf
Error: open C:\Users\xxx\cli/cmd/genConf.go: The system cannot find the path specified.

"Using config file" displays when doing completion command

Running

cobra-cli completion bash

Displays

Using config file: ~/.cobra.yaml

This isn't causing an issue, but it's a bit of a cosmetic annoyance, especially since I have source <(cobra-cli completion bash). This text displays every time I open a new terminal tab.

Is there a way to suppress it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.