Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

License

NotificationsYou must be signed in to change notification settings

go-clix/cli

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Cli-X is a command line library for Go, inspired byspf13/cobra.

  • 📦struct based API: Similar tocobra,go-clix/cli features astruct basedAPI for easy composition and discovery of available options.
  • 🚸Subcommands:cli.Command can be nested for agitlike experience.
  • 📌Flags: Every command has it's own set of flags. POSIX compliantusingspf13/pflag.
  • 👥Aliases: Commands can have multiple names, sobreaking changes can easily be mitigated.
  • 🎯Go based completion:<TAB> completion is supported forbash,zsh andfish. But you can generate suggestions usingGo code!

Getting started

Add the library to your project:

$ go get github.com/go-clix/cli

Then set up your root command:

package mainimport ("fmt""github.com/go-clix/cli")funcmain() {// create the root commandrootCmd:= cli.Command{Use:"greet",Short:"print a message",Run:func(cmd*cli.Command,args []string)error {fmt.Println("Hello from Cli-X!")        },    }// run and check for errorsiferr:=rootCmd.Execute();err!=nil {fmt.Println(err)os.Exit(1)    }}

Subcommands

Every command may have children:

// use a func to return a Command instead of// a global variable and `init()`funcapplyCmd()*cli.Command {cmd:=&cli.Command{Use:"apply",Short:"apply the changes"    }cmd.Run=func(cmd*cli.Command,args []string)error {fmt.Println("applied",args[0])    }returncmd}funcmain() {rootCmd:=&cli.Comand{Use:"kubectl",Short:"Kubernetes management tool",    }// add the child commandrootCmd.AddChildren(applyCmd(),    )// run and check for errorsiferr:=rootCmd.Execute();err!=nil {fmt.Println(err)os.Exit(1)    }}

Note: Do not use theinit() function for setting up your commands.Create constructors as shown above!

Flags

Apflag.FlagSet can be accessed per command using*Command.Flags():

funcapplyCmd()*cli.Command {cmd:=&cli.Command{Use:"apply",Short:"apply the changes"    }force:=cmd.Flags().BoolP("force","f",false,"skip checks")cmd.Run=func(cmd*cli.Command,args []string)error {fmt.Println("applied",args[0])if*force {fmt.Println("The force was with us.")        }    }returncmd}

Aliases

To make theapply subcommand also available asmake anddo:

funcapplyCmd()*cli.Command {cmd:=&cli.Command{Use:"apply",Aliases: []string{"make","do"},Short:"apply the changes"    }}

Keep in mind that in--help outputs the command will still be calledapply.

Completion

Cli-X has a very powerful cli completion system, based onposener/complete.

It is powerful, because suggestions come directly from the Go application, notfrom abash script or similar.

Command and Flag names are automatically suggested, custom suggestions can beimplemented forpositional arguments andflagvalues:

Flag Values

Custom suggestions for flag values can be set up usingCommand.Predictors.

To do so, you need to add acomplete.Predictor for that flag. Cli-X has anumber of predefined ones:

  • PredictAny(): Predicts available files and directories, likebash does whenhaving no better idea
  • PredictNone(): Predicts literally nothing. No suggestions will be shown.
  • PredictSet(...string): Suggests from a predefined slice of options

If that's not sufficient, usePredictFunc(func(complete.Args) []string) tocreate your own.

import ("github.com/posener/complete""github.com/go-clix/cli")funclogsCmd()*cli.Command {cmd:=&cli.Command{Use:"logs",Short:"show logs of a pod",Predictors:map[string]complete.Predictor{"output":cli.PredictSet("lines","json","logfmt"),        },    }output:=cmd.Flags().StringP("output","o","lines","one of [lines, json, logfmt]")}

Positional Arguments

For positional arguments, Cli-X uses a slightly differentinterface, to allowvalidation as well:

interface {Validate(args []string)errorPredict(Args) []string}

Predefined options are also available:

  • ArgsAny(): accepts any number args, predicts files and directories
  • ArgsExact(n): acceptsexactlyn arguments. Predicts files and directories.
  • ArgsRange(n, m): accepts betweenn andm arguments (inclusive). Predicts files and directories.
  • ArgsNone(): acceptsno args and predicts nothing.
  • ArgsSet(...string): Acceptsone argument, which MUST be included in thegiven set. Predicts the values from the set.
import ("github.com/posener/complete""github.com/go-clix/cli")funcapplyCmd()*cli.Command {cmd:=&cli.Command{Use:"logs",Short:"show logs of a pod",// we expect one argument which can be anythingArgs:cli.ArgsExact(1),    }}

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp