func addDriverFlagsToCommand(cliFlags []cli.Flag, cmd *cli.Command) *cli.Command { cmd.Flags = append(SharedCreateFlags, cliFlags...) cmd.SkipFlagParsing = false cmd.Action = runCommand(cmdCreateInner) sort.Sort(ByFlagName(cmd.Flags)) return cmd }
func getRunCommand() cli.Command { actionRun := func(c *cli.Context) { cliApplicationAction(c) if !c.IsSet("db-host") { cli.ShowCommandHelp(c, "run") return } goAuthApp := app.NewApplication(c.String("db-user"), c.String("db-password"), c.String("database"), c.String("db-host"), c.Int("db-port"), c.Int("port")) goAuthApp.Run() } cmdRun := cli.Command{ Name: "run", Usage: "Run the authentication service", Action: actionRun, } cmdRun.Flags = []cli.Flag{ cli.StringFlag{ Name: "db-host", Usage: "The Database Hostname", }, cli.IntFlag{ Name: "db-port", Usage: "The Database port", Value: 3306, }, cli.StringFlag{ Name: "db-user", Usage: "The Database Username", Value: "messenger", }, cli.StringFlag{ Name: "db-password", Usage: "The Database Password", Value: "messenger", }, cli.StringFlag{ Name: "database", Usage: "The Database name", Value: "messenger", }, cli.IntFlag{ Name: "port, p", Usage: "The port on which this app will serve requests", Value: 8080, }, } return cmdRun }
func getCommands(config Config) []cli.Command { exportCmds := []cli.Command{} var keys []string for k := range config.Commands { keys = append(keys, k) } sort.Strings(keys) for _, name := range keys { cmd := config.Commands[name] cmdName := name subCommands := []cli.Command{} // Handle the import of subcommands. if cmd.Import != "" { // If the first character isn't "/" or "~" we assume a relative path. subSource := cmd.Import if cmd.Import[0] != "/"[0] || cmd.Import[0] != "~"[0] { subSource = filepath.Join(sourcedir, cmd.Import) } logger("info", "Importing commands into '"+name+"' command from "+subSource) subConfig, _ := getConfig(subSource) subCommands = getCommands(subConfig) } newCmd := cli.Command{ Name: name, SkipFlagParsing: true, HideHelp: cmd.Hide, } if cmd.Usage != "" { newCmd.Usage = cmd.Usage } if cmd.Cmd != "" { newCmd.Action = func(c *cli.Context) { args = c.Args() runCommand(cmdName, cmd.Cmd) } } if subCommands != nil { newCmd.Subcommands = subCommands } //log.Println("found command: ", name, " > ", cmd.Cmd ) exportCmds = append(exportCmds, newCmd) } return exportCmds }
func (yat *YandexTranslator) GetCli() *cli.Command { c := cli.Command{ Name: "yandex", Aliases: []string{"ya"}, Usage: "Yandex translator", Flags: []cli.Flag{ cli.StringFlag{ Name: "api-key-file, f", Value: ".yandex_api_key", Usage: "yandex api key file", EnvVar: "YANDEX_API_KEY_FILE", }, }, Subcommands: []cli.Command{ { Name: "translate", Aliases: []string{"tr"}, Usage: "Translate with yandex translator", Action: func(c *cli.Context) { key, err := utilits.ReadFile(c.Parent().String("api-key-file")) if err != nil { fmt.Println(err) return } yat.Key = key langs := utilits.ParseLang(c.Args()[0]) tr, err := yat.Translate(c.Args()[1], langs[0], langs[1]) if err != nil { fmt.Println(err) return } fmt.Println(tr) }, }, { Name: "langs", Usage: "Get supported languages", Aliases: []string{"l"}, Action: func(c *cli.Context) { key, err := utilits.ReadFile(c.Parent().String("api-key-file")) if err != nil { fmt.Println(err) } yat.Key = key langs, err := yat.GetLangs() if err != nil { fmt.Println(err) } fmt.Println(langs) }, }, }, } return &c }
func selinuxCommand() cli.Command { app := cli.Command{} app.Name = "selinux" app.Usage = "Launch SELinux tools container." app.Action = func(c *cli.Context) error { argv := []string{"system-docker", "run", "-it", "--privileged", "--rm", "--net", "host", "--pid", "host", "--ipc", "host", "-v", "/usr/bin/docker:/usr/bin/docker.dist:ro", "-v", "/usr/bin/ros:/usr/bin/dockerlaunch:ro", "-v", "/usr/bin/ros:/usr/bin/user-docker:ro", "-v", "/usr/bin/ros:/usr/bin/system-docker:ro", "-v", "/usr/bin/ros:/sbin/poweroff:ro", "-v", "/usr/bin/ros:/sbin/reboot:ro", "-v", "/usr/bin/ros:/sbin/halt:ro", "-v", "/usr/bin/ros:/sbin/shutdown:ro", "-v", "/usr/bin/ros:/usr/bin/respawn:ro", "-v", "/usr/bin/ros:/usr/bin/ros:ro", "-v", "/usr/bin/ros:/usr/bin/cloud-init:ro", "-v", "/usr/bin/ros:/usr/sbin/netconf:ro", "-v", "/usr/bin/ros:/usr/sbin/wait-for-network:ro", "-v", "/usr/bin/ros:/usr/sbin/wait-for-docker:ro", "-v", "/var/lib/docker:/var/lib/docker", "-v", "/var/lib/rkt:/var/lib/rkt", "-v", "/dev:/host/dev", "-v", "/etc/docker:/etc/docker", "-v", "/etc/hosts:/etc/hosts", "-v", "/etc/resolv.conf:/etc/resolv.conf", "-v", "/etc/rkt:/etc/rkt", "-v", "/etc/ssl/certs/ca-certificates.crt:/etc/ssl/certs/ca-certificates.crt.rancher", "-v", "/lib/firmware:/lib/firmware", "-v", "/lib/modules:/lib/modules", "-v", "/run:/run", "-v", "/usr/share/ros:/usr/share/ros", "-v", "/var/lib/rancher/conf:/var/lib/rancher/conf", "-v", "/var/lib/rancher:/var/lib/rancher", "-v", "/var/log:/var/log", "-v", "/var/run:/var/run", "-v", "/home:/home", "-v", "/opt:/opt", "-v", "/etc/selinux:/etc/selinux", "-v", "/var/lib/selinux:/var/lib/selinux", "-v", "/usr/share/selinux:/usr/share/selinux", fmt.Sprintf("rancher/os-selinuxtools:%s", config.VERSION+config.SUFFIX), "bash"} syscall.Exec("/bin/system-docker", argv, []string{}) return nil } return app }
func (w *crashHandler) Wrap(cmd cli.Command) cli.Command { oldAction := cmd.Action cmd.Action = func(c *cli.Context) { oldAction(c) } return cmd }
func wrap_cmd(cfg *watch.Config, c cli.Command) cli.Command { a := c.Action.(func(*cli.Context)) c.Action = func(c *cli.Context) { setup_action(cfg, c) a(c) } return c }
func serviceCommand() cli.Command { factory := &projectFactory{} app := cli.Command{} app.Name = "service" app.ShortName = "s" app.Usage = "Command line interface for services and compose." app.Before = beforeApp app.Flags = append(command.CommonFlags(), dockerApp.DockerClientFlags()...) app.Subcommands = append(serviceSubCommands(), command.BuildCommand(factory), command.CreateCommand(factory), command.UpCommand(factory), command.StartCommand(factory), command.LogsCommand(factory), command.RestartCommand(factory), command.StopCommand(factory), command.ScaleCommand(factory), command.RmCommand(factory), command.PullCommand(factory), command.KillCommand(factory), command.PortCommand(factory), command.PsCommand(factory), ) return app }
func (w *YAMLConfigLoader) Wrap(cmd cli.Command) cli.Command { cmd.Flags = append(cmd.Flags, []cli.Flag{ cli.StringFlag{"config", w.DefaultPath, "path to YAML config file", ""}, }...) oldAction := cmd.Action cmd.Action = func(c *cli.Context) { configFile := c.String("config") if configFile != "" { err := w.LoadFromFile(configFile) if err != nil { fmt.Println(err) os.Exit(1) } } oldAction(c) } return cmd }
func TestCommandDoNotIgnoreFlags(t *testing.T) { app := cli.NewApp() set := flag.NewFlagSet("test", 0) test := []string{"blah", "blah", "-break"} set.Parse(test) c := cli.NewContext(app, set, set) command := cli.Command{ Name: "test-cmd", ShortName: "tc", Usage: "this is for testing", Description: "testing", Action: func(_ *cli.Context) {}, } err := command.Run(c) expect(t, err.Error(), "flag provided but not defined: -break") }
// MakeCLI creates the CLI tree for a Host info func (h HostInfo) MakeCLI() []cli.Command { sc := make([]cli.Command, 0, len(h.Types)) for _, key := range h.Types.List() { cat := h.Types[key] cc := cli.Command{ // cc = category command Name: key, Usage: cat.Summary, HideHelp: true, Subcommands: make([]cli.Command, 0, len(cat.Hosts)), Action: func(c *cli.Context) { cat.PrimaryHost().Execute("") }, } for _, host := range cat.Hosts { hc := cli.Command{ // hc = host command Name: host.FQDN, Usage: host.Summary, HideHelp: true, Action: func(c *cli.Context) { var host *Host args := c.Args() if len(args) == 0 { // No extra arguments - go to the primary host host = cat.PrimaryHost() } else { // Arguments were defined - go to the fqdn specified // TODO(thiderman): Error handling, integer index handling host = cat.GetHost(args[0]) } host.Execute("") }, } cc.Subcommands = append(cc.Subcommands, hc) } sc = append(sc, cc) } return sc }
func TestCommandIgnoreFlags(t *testing.T) { app := cli.NewApp() set := flag.NewFlagSet("test", 0) test := []string{"blah", "blah"} set.Parse(test) c := cli.NewContext(app, set, set) command := cli.Command{ Name: "test-cmd", ShortName: "tc", Usage: "this is for testing", Description: "testing", Action: func(_ *cli.Context) {}, SkipFlagParsing: true, } err := command.Run(c) expect(t, err, nil) }
func (w *Logged) Wrap(cmd cli.Command) cli.Command { cmd.Flags = append(cmd.Flags, []cli.Flag{ cli.StringFlag{"log", w.DefaultTarget, "path to log file, 'stdout', 'stderr' or 'false'", ""}, cli.StringFlag{"log-level", w.DefaultLevel, "logging level", ""}, cli.StringFlag{"log-format", w.DefaultFormat, "log record format: 'term', 'logfmt', 'json'", ""}, }...) oldAction := cmd.Action cmd.Action = func(c *cli.Context) { handler, err := w.HandlerFor(c.String("log"), c.String("log-level"), c.String("log-format")) if err != nil { fmt.Println(err) os.Exit(1) } for _, l := range w.Loggers { l.SetHandler(handler) } oldAction(c) } return cmd }
func getCommands(config Config) []cli.Command { exportCmds := []cli.Command{} var keys []string for k := range config.Commands { keys = append(keys, k) } sort.Strings(keys) for _, name := range keys { cmd := config.Commands[name] cmdName := name newCmd := cli.Command{ Name: name, SkipFlagParsing: true, HideHelp: cmd.Hide, } if cmd.Usage != "" { newCmd.Usage = cmd.Usage } if cmd.Cmd != "" { newCmd.Action = func(c *cli.Context) { args = c.Args() runCommand(cmdName, cmd.Cmd) } } subCommands := getSubCommands(cmd.Imports) if subCommands != nil { newCmd.Subcommands = subCommands } //log.Println("found command: ", name, " > ", cmd.Cmd ) exportCmds = append(exportCmds, newCmd) } return exportCmds }
func init() { cmd := &ExecCommand{} flags := clihelpers.GetFlagsFromStruct(cmd) cliCmd := cli.Command{ Name: "exec", Usage: "execute a build locally", } for _, executor := range common.GetExecutors() { subCmd := cli.Command{ Name: executor, Usage: "use " + executor + " executor", Action: cmd.Execute, Flags: flags, } cliCmd.Subcommands = append(cliCmd.Subcommands, subCmd) } common.RegisterCommand(cliCmd) }
func init() { catalogCmd := cli.Command{ Name: "catalog", Usage: "Manage Otsimo catalogs", } catalogCmd.Subcommands = []cli.Command{ { Name: "push", Usage: "push catalog", Action: catalogPush, }, { Name: "validate", Usage: "validate catalog file", Action: catalogValidate, }, { Name: "current", Usage: "get current accessible catalog", Action: catalogCurrent, }, { Name: "approve", Usage: "approve a catalog", Action: catalogApprove, }, { Name: "list", Usage: "list catalogs", Action: catalogList, Flags: []cli.Flag{ cli.BoolFlag{Name: "hide-expired"}, cli.IntFlag{Name: "limit", Value: 100}, cli.StringFlag{Name: "status", Value: "both", Usage: "catalog status: both, draft, approved"}, }, }, } commands = append(commands, catalogCmd) }
func getCommand(baseName string, metadata command_metadata.CommandMetadata, runner command_runner.Runner) cli.Command { command := cli.Command{ Name: metadata.Name, Aliases: metadata.Aliases, ShortName: metadata.ShortName, Description: metadata.Description, Usage: strings.Replace(metadata.Usage, "BROOKLYN_NAME", baseName, -1), Action: func(context *cli.Context) { err := runner.RunCmdByName(metadata.Name, context) if err != nil { error_handler.ErrorExit(err) } }, Flags: metadata.Flags, SkipFlagParsing: metadata.SkipFlagParsing, } if nil != metadata.Operands { command.Subcommands = make([]cli.Command, 0) for _, operand := range metadata.Operands { command.Subcommands = append(command.Subcommands, cli.Command{ Name: operand.Name, Aliases: operand.Aliases, ShortName: operand.ShortName, Description: operand.Description, Usage: operand.Usage, Flags: operand.Flags, SkipFlagParsing: operand.SkipFlagParsing, Action: subCommandAction(command.Name, operand.Name, runner), }) command.Usage = strings.Join([]string{ command.Usage, "\n... ", operand.Usage, "\t", operand.Description, }, "") } } return command }
func init() { gameCmd := cli.Command{ Name: "game", Usage: "Manage games", } gameCmd.Subcommands = []cli.Command{{ Name: "init", Action: gameInit, Usage: "Creates a new empty game", }, { Name: "list", Action: gameList, Usage: "Shows list of games", Flags: []cli.Flag{ cli.StringFlag{Name: "state", Value: "any", Usage: "available values are: any, created, dev, waiting, validated, production"}, cli.IntFlag{Name: "limit", Value: 100, Usage: "limit return results"}, }, }, { Name: "publish", Action: gamePublish, Usage: "Upload the game at current directory", }, { Name: "change-state", Action: gameChangeState, Usage: "Changes a game's state", Description: "ex: 'otsimoctl change-state sample-game 0.1.2 validated'", }, { Name: "info", Action: gameEnv, Usage: "Info of the game at current directory", Flags: []cli.Flag{ cli.BoolFlag{Name: "env"}, }, }} commands = append(commands, gameCmd) }
func (mt *MultitranTranslator) GetCli() *cli.Command { c := cli.Command{ Name: "multitran", Aliases: []string{"mt"}, Usage: "Multitran translator", Subcommands: []cli.Command{ { Name: "translate", Aliases: []string{"tr"}, Usage: "Translate with multitran translator", Action: func(c *cli.Context) { langs := utilits.ParseLang(c.Args()[0]) tr, err := mt.Translate(c.Args()[1], langs[0], langs[1]) if err != nil { fmt.Println(err) return } fmt.Println(tr) }, }, { Name: "langs", Usage: "Get supported languages", Aliases: []string{"l"}, Action: func(c *cli.Context) { langs, err := mt.GetLangs() if err != nil { fmt.Println(err) } fmt.Println(langs) }, }, }, } return &c }
// MakeCLI generates a cli.Command chain based on the repository structure func (r *Repo) MakeCLI() (c cli.Command) { c = cli.Command{ Name: r.Key, Usage: r.Summary, HideHelp: true, } // Make a list of subcommands to add into the Command. subcommands := make([]cli.Command, 0, len(r.Items)+len(r.Subrepos)) // Loop over the subrepositories first, making sure that they are on top. for _, key := range r.SubrepoKeys() { subrepo := r.Subrepos[key] subcommands = append(subcommands, subrepo.MakeCLI()) } // Then loop the item files. for _, key := range r.Keys() { item := r.Items[key] sc := cli.Command{ Name: item.ID(), Usage: item.Summary(), HideHelp: true, Action: item.Execute, } sc.Subcommands = append(sc.Subcommands, item.MakeCLI()...) subcommands = append(subcommands, sc) } c.Subcommands = subcommands return }
func main() { app := cli.NewApp() app.Name = "upx" app.Usage = "a tool for managing files in UPYUN" app.Author = "Hongbo.Mo" app.Email = "*****@*****.**" app.Version = fmt.Sprintf("%s %s/%s %s", version, runtime.GOOS, runtime.GOARCH, runtime.Version()) app.Commands = make([]cli.Command, 0) sort.Strings(cmds) for _, cmd := range cmds { cm, exist := CmdMap[cmd] if exist { Cmd := cli.Command{ Name: cmd, Usage: cm.Desc, Action: func(c *cli.Context) error { if c.Command.FullName() != "login" && driver == nil { fmt.Println("Log in first.") os.Exit(-1) } opts := make(map[string]interface{}) for k, v := range cm.Flags { if c.IsSet(k) { switch v.typ { case "bool": opts[k] = c.Bool(k) case "string": opts[k] = c.String(k) case "int": opts[k] = c.Int(k) } } } cm.Func(c.Args(), opts) return nil }, } if cm.Alias != "" { Cmd.Aliases = []string{cm.Alias} } if cm.Flags != nil { Cmd.Flags = []cli.Flag{} for k, v := range cm.Flags { var flag cli.Flag switch v.typ { case "bool": flag = cli.BoolFlag{Name: k, Usage: v.usage} case "int": flag = cli.StringFlag{Name: k, Usage: v.usage} case "string": flag = cli.IntFlag{Name: k, Usage: v.usage} } Cmd.Flags = append(Cmd.Flags, flag) } } app.Commands = append(app.Commands, Cmd) } } app.Run(os.Args) }
func presentCmdName(cmd cli.Command) (name string) { name = strings.Join(cmd.Names(), ", ") return }
func testTileAction(actionName string) { var ( controlErrorHandler = new(ErrorHandler) ) Context(fmt.Sprintf("when called with the %s command name", actionName), func() { controlName := actionName controlUsage := "something about the usage here" It("Then it should return a cli.Command with required values", func() { cmd := CreateBURACliCommand(controlName, controlUsage, controlErrorHandler) Ω(cmd.Name).Should(Equal(controlName)) Ω(cmd.Usage).Should(Equal(controlUsage)) Ω(cmd.Action).ShouldNot(BeNil()) }) Describe(fmt.Sprintf("given a %s command with an Action value", actionName), func() { var ( controlExit = 0 controlCliContext *cli.Context controlCmd cli.Command ) BeforeEach(func() { controlErrorHandler = new(ErrorHandler) controlErrorHandler.ExitCode = controlExit }) Context("when the action is called with all proper flags on a registered tile", func() { var ( controlTileName = "fake-tile" controlTileGenerator *fake.TileGenerator controlTile *fake.Tile ) BeforeEach(func() { controlTile = new(fake.Tile) controlTileGenerator = new(fake.TileGenerator) controlTileGenerator.TileSpy = controlTile tileregistry.Register(controlTileName, controlTileGenerator) set := flag.NewFlagSet("", 0) set.String("tile", controlTileName, "") set.String("opsmanagerhost", "*****", "") set.String("adminuser", "*****", "") set.String("adminpass", "*****", "") set.String("opsmanageruser", "*****", "") set.String("opsmanagerpass", "*****", "") set.String("destination", "*****", "") controlCliContext = cli.NewContext(cli.NewApp(), set, nil) controlCmd = CreateBURACliCommand(controlName, controlUsage, controlErrorHandler) controlCliContext.Command = controlCmd }) It("then it should execute a call on the tiles Action func()", func() { controlCmd.Action(controlCliContext) Ω(controlErrorHandler.ExitCode).Should(Equal(controlExit)) Ω(controlErrorHandler.Error).ShouldNot(HaveOccurred()) switch controlName { case "backup": Ω(controlTile.BackupCallCount).ShouldNot(Equal(0)) case "restore": Ω(controlTile.RestoreCallCount).ShouldNot(Equal(0)) default: panic("this should never happen") } }) }) Context("when the action is called w/o a matching registered tile", func() { BeforeEach(func() { set := flag.NewFlagSet(controlName, 0) set.Bool("myflag", false, "doc") set.String("otherflag", "hello world", "doc") controlCliContext = cli.NewContext(cli.NewApp(), set, nil) controlCmd = CreateBURACliCommand(controlName, controlUsage, controlErrorHandler) controlCliContext.Command = controlCmd }) It("then it should set an error and failure exit code", func() { controlCmd.Action(controlCliContext) Ω(controlErrorHandler.ExitCode).ShouldNot(Equal(controlExit)) Ω(controlErrorHandler.Error).Should(HaveOccurred()) Ω(controlErrorHandler.Error).Should(Equal(ErrInvalidTileSelection)) }) }) Context("when the action is called w/o proper flags but with a registered tile", func() { var controlTileName = "fake-tile" BeforeEach(func() { tileregistry.Register(controlTileName, new(fake.TileGenerator)) set := flag.NewFlagSet("", 0) set.String("tile", controlTileName, "doc") set.Bool("myflag", false, "doc") set.String("otherflag", "hello world", "doc") controlCliContext = cli.NewContext(cli.NewApp(), set, nil) controlCmd = CreateBURACliCommand(controlName, controlUsage, controlErrorHandler) controlCliContext.Command = controlCmd }) It("then it should set an error and failure exit code", func() { controlCmd.Action(controlCliContext) Ω(controlErrorHandler.ExitCode).ShouldNot(Equal(controlExit)) Ω(controlErrorHandler.Error).Should(HaveOccurred()) Ω(controlErrorHandler.Error).Should(Equal(ErrInvalidFlagArgs)) }) }) }) }) }