func callCoreCommand(args []string, theApp *cli.App) { err := theApp.Run(args) if err != nil { os.Exit(1) } gateways := gatewaySliceFromMap(deps.gateways) warningsCollector := net.NewWarningsCollector(deps.termUI, gateways...) warningsCollector.PrintWarnings() }
// so we can catch panics func run(app *cli.App) { defer func() { if r := recover(); r != nil { trace := make([]byte, 2048) count := runtime.Stack(trace, true) fmt.Println("Panic: ", r) fmt.Printf("Stack of %d bytes: %s", count, trace) } }() app.Run(os.Args) }
func main() { var app *cli.App app = cli.NewApp() app.Name = APP_NAME app.Version = APP_VER app.Usage = "email for mail sending, or web or none for run web interface!" app.Commands = []cli.Command{ task.CmdWeb, task.CmdEmail, } app.Flags = append(app.Flags, []cli.Flag{}...) app.Run(os.Args) }
func Run(app *cli.App) { app.Before = func(c *cli.Context) error { if c.GlobalString("key") == "" { log.Fatal("No aio key provided. Use --key KEY_HERE or export AIO_KEY=KEY_HERE") } if c.GlobalBool("debug") { log.SetLevel(log.DebugLevel) log.Debug("Debug Mode ON") log.Debug("AIO_KEY: ", c.GlobalString("key")) } return nil } app.Run(os.Args) }
func TestParseGenericFromEnvCascade(t *testing.T) { os.Clearenv() os.Setenv("APP_FOO", "99,2000") a := cli.App{ Flags: []cli.Flag{ cli.GenericFlag{Name: "foos", Value: &Parser{}, EnvVar: "COMPAT_FOO,APP_FOO"}, }, Action: func(ctx *cli.Context) { if !reflect.DeepEqual(ctx.Generic("foos"), &Parser{"99", "2000"}) { t.Errorf("value not set from env") } }, } a.Run([]string{"run"}) }
func TestParseGeneric(t *testing.T) { a := cli.App{ Flags: []cli.Flag{ cli.GenericFlag{Name: "serve, s", Value: &Parser{}}, }, Action: func(ctx *cli.Context) { if !reflect.DeepEqual(ctx.Generic("serve"), &Parser{"10", "20"}) { t.Errorf("main name not set") } if !reflect.DeepEqual(ctx.Generic("s"), &Parser{"10", "20"}) { t.Errorf("short name not set") } }, } a.Run([]string{"run", "-s", "10,20"}) }
func cmdConsole(app *cli.App, c *cli.Context) { for { fmt.Printf("> ") bufReader := bufio.NewReader(os.Stdin) line, more, err := bufReader.ReadLine() if more { Exit("input is too long") } else if err != nil { Exit(err.Error()) } args := []string{"tmsp"} args = append(args, strings.Split(string(line), " ")...) app.Run(args) } }
func TestParseMultiBoolT(t *testing.T) { a := cli.App{ Flags: []cli.Flag{ cli.BoolTFlag{Name: "serve, s"}, }, Action: func(ctx *cli.Context) { if ctx.BoolT("serve") != true { t.Errorf("main name not set") } if ctx.BoolT("s") != true { t.Errorf("short name not set") } }, } a.Run([]string{"run", "--serve"}) }
func TestParseMultiFloat64(t *testing.T) { a := cli.App{ Flags: []cli.Flag{ cli.Float64Flag{Name: "serve, s"}, }, Action: func(ctx *cli.Context) { if ctx.Float64("serve") != 10.2 { t.Errorf("main name not set") } if ctx.Float64("s") != 10.2 { t.Errorf("short name not set") } }, } a.Run([]string{"run", "-s", "10.2"}) }
func TestParseMultiFloat64FromEnv(t *testing.T) { os.Setenv("APP_TIMEOUT_SECONDS", "15.5") a := cli.App{ Flags: []cli.Flag{ cli.Float64Flag{Name: "timeout, t", EnvVar: "APP_TIMEOUT_SECONDS"}, }, Action: func(ctx *cli.Context) { if ctx.Float64("timeout") != 15.5 { t.Errorf("main name not set") } if ctx.Float64("t") != 15.5 { t.Errorf("short name not set") } }, } a.Run([]string{"run"}) }
func TestParseGenericFromEnv(t *testing.T) { os.Setenv("APP_SERVE", "20,30") a := cli.App{ Flags: []cli.Flag{ cli.GenericFlag{Name: "serve, s", Value: &Parser{}, EnvVar: "APP_SERVE"}, }, Action: func(ctx *cli.Context) { if !reflect.DeepEqual(ctx.Generic("serve"), &Parser{"20", "30"}) { t.Errorf("main name not set from env") } if !reflect.DeepEqual(ctx.Generic("s"), &Parser{"20", "30"}) { t.Errorf("short name not set from env") } }, } a.Run([]string{"run"}) }
func TestParseMultiInt(t *testing.T) { a := cli.App{ Flags: []cli.Flag{ cli.IntFlag{Name: "serve, s"}, }, Action: func(ctx *cli.Context) int { if ctx.Int("serve") != 10 { t.Errorf("main name not set") } if ctx.Int("s") != 10 { t.Errorf("short name not set") } return 0 }, } a.Run([]string{"run", "-s", "10"}) }
func TestParseMultiBoolTFromEnv(t *testing.T) { os.Setenv("APP_DEBUG", "0") a := cli.App{ Flags: []cli.Flag{ cli.BoolTFlag{Name: "debug, d", EnvVar: "APP_DEBUG"}, }, Action: func(ctx *cli.Context) { if ctx.BoolT("debug") != false { t.Errorf("main name not set from env") } if ctx.BoolT("d") != false { t.Errorf("short name not set from env") } }, } a.Run([]string{"run"}) }
func TestParseMultiBoolFromEnvCascade(t *testing.T) { os.Clearenv() os.Setenv("APP_DEBUG", "1") a := cli.App{ Flags: []cli.Flag{ cli.BoolFlag{Name: "debug, d", EnvVar: "COMPAT_DEBUG,APP_DEBUG"}, }, Action: func(ctx *cli.Context) { if ctx.Bool("debug") != true { t.Errorf("main name not set from env") } if ctx.Bool("d") != true { t.Errorf("short name not set from env") } }, } a.Run([]string{"run"}) }
func cmdBatch(app *cli.App, c *cli.Context) { bufReader := bufio.NewReader(os.Stdin) for { line, more, err := bufReader.ReadLine() if more { Exit("input line is too long") } else if err == io.EOF { break } else if len(line) == 0 { continue } else if err != nil { Exit(err.Error()) } args := []string{"tmsp"} args = append(args, strings.Split(string(line), " ")...) app.Run(args) } }
func TestParseMultiIntFromEnvCascade(t *testing.T) { os.Clearenv() os.Setenv("APP_TIMEOUT_SECONDS", "10") a := cli.App{ Flags: []cli.Flag{ cli.IntFlag{Name: "timeout, t", EnvVar: "COMPAT_TIMEOUT_SECONDS,APP_TIMEOUT_SECONDS"}, }, Action: func(ctx *cli.Context) { if ctx.Int("timeout") != 10 { t.Errorf("main name not set") } if ctx.Int("t") != 10 { t.Errorf("short name not set") } }, } a.Run([]string{"run"}) }
It("does not verify the current target", func() { cliConfig.SetTarget("my-lattice.example.com") Expect(cliConfig.Save()).To(Succeed()) commandRan := false cliApp.Commands = []cli.Command{ cli.Command{ Name: "target", Action: func(ctx *cli.Context) { commandRan = true }, }, } Expect(cliApp.Run([]string{"ltc", "target"})).To(Succeed()) Expect(commandRan).To(BeTrue()) Expect(fakeTargetVerifier.VerifyTargetCallCount()).To(Equal(0)) }) }) Context("when running the help command", func() { It("does not verify the current target", func() { cliConfig.SetTarget("my-lattice.example.com") Expect(cliConfig.Save()).To(Succeed()) commandRan := false cliApp.Commands = []cli.Command{ cli.Command{ Name: "help",
cliConfig.Save() commandRan := false cliApp.Commands = []cli.Command{ cli.Command{ Name: config_command_factory.TargetCommandName, Action: func(ctx *cli.Context) { commandRan = true }, }, } cliAppArgs := []string{"ltc", config_command_factory.TargetCommandName} err := cliApp.Run(cliAppArgs) Expect(err).ToNot(HaveOccurred()) Expect(fakeTargetVerifier.VerifyTargetCallCount()).To(BeZero()) Expect(commandRan).To(BeTrue()) }) }) Context("when running the help command", func() { It("does not verify the current target", func() { cliConfig.SetTarget("my-lattice.example.com") cliConfig.Save() commandRan := false cliApp.Commands = []cli.Command{
trace.SetStdout(output) trace.EnableTrace() }) It("prints its version number to the trace output when constructed", func() { Expect(strings.Split(output.String(), "\n")).To(ContainSubstrings( []string{"VERSION:"}, []string{cf.Version}, )) }) }) Context("when given a command name to run", func() { It("runs the command with that name", func() { for _, cmdName := range expectedCommandNames { app.Run([]string{"", cmdName}) Expect(cmdRunner.cmdName).To(Equal(cmdName)) } }) }) It("includes the built on date in its version string", func() { Expect(app.Version).To(Equal(cf.Version + "-" + cf.BuiltOnDate)) }) }) type FakeRunner struct { cmdFactory command_factory.Factory cmdName string }
func main() { var app *cli.App app = cli.NewApp() app.Name = "awsutils" app.Usage = "automation of Amazon Web Services configurations through their API" app.EnableBashCompletion = true app.Commands = []cli.Command{ { Name: "iam", Usage: "use the AWS iam API", Subcommands: []cli.Command{ { Name: "certs", Usage: "summarise certificate configurations available in your AWS account", Action: func(c *cli.Context) { out, err := exec.Command("aws", "iam", "list-server-certificates").Output() if err != nil { fmt.Println(err.Error()) return } var r ListServerCertificatesResponse err = json.Unmarshal(out, &r) if err != nil { fmt.Println(err.Error()) return } w := tabwriter.NewWriter(os.Stdout, 0, 4, 3, ' ', 0) fmt.Fprint(w, "ID\tName\tStatus\n") for _, cm := range r.ServerCertificateMetadataList { fmt.Fprintf(w, "%s\t%s\t%s\n", cm.ServerCertificateID, cm.ServerCertificateName, ResolveStatus(cm.Expiration)) } w.Flush() // fmt.Printf("%+v\n", r) }, }, }, }, { Name: "cloudfront", Aliases: []string{"cf"}, Usage: "use the AWS cloudfront API", Subcommands: []cli.Command{ { Name: "export-configs", Usage: "export the cloudfront distribution configurations", Action: func(c *cli.Context) { out, err := exec.Command("aws", "cloudfront", "list-distributions").Output() if err != nil { fmt.Println(err.Error()) return } var r CloudFrontListDistributionsResponse err = json.Unmarshal(out, &r) if err != nil { fmt.Println(err.Error()) return } w := tabwriter.NewWriter(os.Stdout, 0, 4, 3, ' ', 0) fmt.Fprint(w, "DomainName\n") for _, d := range r.Distributionlist.Items { fmt.Fprintf(w, "%+v\n", d.Origins.Items[0]["DomainName"]) json, _ := json.MarshalIndent(d, "", " ") fn := fmt.Sprintf("%s.json", d.Origins.Items[0]["Id"]) f, err := os.Create(fn) if err != nil { cwd, _ := os.Getwd() fmt.Printf("Unable to create file '%s' in '%s'", fn, cwd) continue } f.Write(json) f.Close() } w.Flush() }, }, { Name: "dists", Usage: "summarize the cloudfront distribution configurations", Flags: []cli.Flag{ cli.StringFlag{ Name: "order-by", Value: "alias", Usage: "sort results on alias|origin|status", }, cli.BoolFlag{ Name: "csv", Usage: "output as csv", }, }, Action: func(c *cli.Context) { out, err := exec.Command("aws", "cloudfront", "list-distributions").Output() if err != nil { fmt.Println(err.Error()) return } var r CloudFrontListDistributionsResponse err = json.Unmarshal(out, &r) if err != nil { fmt.Println(err.Error()) return } var list []DistSummary for _, d := range r.Distributionlist.Items { id := d.ID distDomain := d.DomainName status := d.Status origin := "" alias := "" if len(d.Origins.Items) > 0 { for _, o := range d.Origins.Items { if op, ok := o["OriginPath"].(string); ok && op == "" { origin = o["DomainName"].(string) } } } if len(d.Aliases.Items) > 0 { alias = strings.Join(d.Aliases.Items, ",") } list = append(list, DistSummary{ID: id, Domain: distDomain, Alias: alias, Origin: origin, Status: status}) } switch c.String("order-by") { case "origin": sort.Sort(ByOrigin(list)) case "status": sort.Sort(ByStatus(list)) case "alias": sort.Sort(ByAlias(list)) default: fmt.Println("Unrecognised value for", c.String("order-by"), ". Sorting by alias instead.") sort.Sort(ByAlias(list)) } if c.Bool("csv") { fmt.Println("ID;Domain;Alias;Origin;Status") for _, s := range list { fmt.Printf(`"%s";"%s";"%s";"%s";"%s"`, s.ID, s.Domain, s.Alias, s.Origin, s.Status) fmt.Println() } } else { w := tabwriter.NewWriter(os.Stdout, 0, 4, 3, ' ', 0) fmt.Fprint(w, "ID\tDomain\tAlias\tOrigin\tStatus\n") for _, s := range list { fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", s.ID, s.Domain, s.Alias, s.Origin, s.Status) } w.Flush() } }, }, }, }, } app.Run(os.Args) }
func CallCoreCommand(args []string, cliApp *cli.App) { err := cliApp.Run(args) if err != nil { os.Exit(1) } }
expectedUrl = "" expectedMessage = "" actualUrl = "" actualMessage = "" app = nil }) var assertUrlAndMessageMatches = func() { Expect(actualUrl).To(Equal(expectedUrl)) Expect(actualMessage).To(Equal(expectedMessage)) } It("opens the api docs on #HelpApi", func() { expectedUrl = "http://www.imgix.com/docs/reference" expectedMessage = "Failed to open the API help docs" app.Run([]string{"imgix", "help", "api"}) assertUrlAndMessageMatches() }) It("Opens the help docs on #HelpDocs", func() { expectedUrl = "http://imgix.com/faq" expectedMessage = "Failed to open the help docs" app.Run([]string{"imgix", "help", "docs"}) assertUrlAndMessageMatches() }) It("Opens a support email on #HelpSupport", func() { expectedUrl = "mailto:[email protected]" expectedMessage = "Failed to create a message to the support team" app.Run([]string{"imgix", "help", "support"}) assertUrlAndMessageMatches()
trace.SetStdout(output) trace.EnableTrace() }) It("prints its version number to the trace output when constructed", func() { Expect(strings.Split(output.String(), "\n")).To(ContainSubstrings( []string{"VERSION:"}, []string{cf.Version}, )) }) }) Context("when given a command name to run", func() { It("runs the command with that name", func() { for _, cmdName := range expectedCommandNames { app.Run([]string{"", cmdName}) Expect(cmdRunner.cmdName).To(Equal(cmdName)) } }) }) Context("when running 'cf --help'", func() { It("should output the help in our custom format", func() { output := io_helpers.CaptureOutput(func() { app.Run([]string{"", "--help"}) }) mergedOutput := strings.Join(output, "\n") Expect(mergedOutput).To(ContainSubstring("CF_TRACE=true"), "CF_TRACE=true not in help") Expect(mergedOutput).To(ContainSubstring("CF_PLUGIN_HOME=path/to/dir/"))
app *cli.App buffer *bytes.Buffer errBuffer *bytes.Buffer ) BeforeEach(func() { app = NewCLIApp() buffer = new(bytes.Buffer) app.Writer = buffer errBuffer = new(bytes.Buffer) app.ErrWriter = errBuffer cli.ErrWriter = errBuffer cli.OsExiter = func(code int) {} }) Describe("Running the diff command", func() { It("should return an exit error of 1 when running without certification argument.", func() { err := app.Run([]string{app.Name, "diff"}) assert.NotNil(GinkgoT(), err) if assert.IsType(GinkgoT(), new(cli.ExitError), err) { exitErr, _ := err.(*cli.ExitError) assert.Equal(GinkgoT(), 1, exitErr.ExitCode()) assert.Contains(GinkgoT(), errBuffer.String(), "Error: Missing Certification Argument") } }) It("should return return the number a missing controls when given a certification", func() { err := app.Run([]string{app.Name, "diff", "LATO", "-o", filepath.Join("fixtures", "opencontrol_fixtures")}) assert.Nil(GinkgoT(), err) assert.Contains(GinkgoT(), buffer.String(), "Number of missing controls:") }) }) })