func TestCheckServerSyntax(t *testing.T) { app := cli.NewApp() app.Commands = []cli.Command{serverCmd} serverFlagSet := flag.NewFlagSet("server", 0) cli.NewContext(app, serverFlagSet, nil) disksGen := func(n int) []string { disks, err := getRandomDisks(n) if err != nil { t.Fatalf("Unable to initialie disks %s", err) } return disks } testCases := [][]string{ disksGen(1), disksGen(4), disksGen(8), disksGen(16), } for i, disks := range testCases { err := serverFlagSet.Parse(disks) if err != nil { t.Errorf("Test %d failed to parse arguments %s", i+1, disks) } defer removeRoots(disks) endpoints, err := parseStorageEndpoints(disks) if err != nil { t.Fatalf("Test %d : Unexpected error %s", i+1, err) } checkEndpointsSyntax(endpoints, disks) _, err = initStorageDisks(endpoints) if err != nil { t.Errorf("Test %d : disk init failed : %s", i+1, err) } } }
func registerApp() *cli.App { // register all commands registerCommand(donutCmd) registerCommand(serverCmd) registerCommand(controllerCmd) registerCommand(versionCmd) // register all flags registerFlag(addressFlag) registerFlag(addressControllerFlag) registerFlag(addressServerRPCFlag) registerFlag(ratelimitFlag) registerFlag(anonymousFlag) registerFlag(certFlag) registerFlag(keyFlag) registerFlag(jsonFlag) // set up app app := cli.NewApp() app.Name = "minio" // hide --version flag, version is a command app.HideVersion = true app.Author = "Minio.io" app.Usage = "Minio Cloud Storage" app.Flags = flags app.Commands = commands app.CustomAppHelpTemplate = `NAME: {{.Name}} - {{.Usage}} USAGE: {{.Name}} {{if .Flags}}[global flags] {{end}}command{{if .Flags}} [command flags]{{end}} [arguments...] COMMANDS: {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} {{end}}{{if .Flags}} GLOBAL FLAGS: {{range .Flags}}{{.}} {{end}}{{end}} VERSION: ` + minioVersion + `{{range $key, $value := ExtraInfo}} {{$key}}: {{$value}} {{end}} ` app.CommandNotFound = func(ctx *cli.Context, command string) { msg := fmt.Sprintf("‘%s’ is not a minio sub-command. See ‘minio help’.", command) closestCommands := findClosestCommands(command) if len(closestCommands) > 0 { msg += fmt.Sprintf("\n\nDid you mean one of these?\n") for _, cmd := range closestCommands { msg += fmt.Sprintf(" ‘%s’\n", cmd) } } Fatalln(msg) } return app }
func ExampleAppHelp() { // set args for examples sake os.Args = []string{"greet", "h", "describeit"} app := cli.NewApp() app.Name = "greet" app.Flags = []cli.Flag{ cli.StringFlag{Name: "name", Value: "bob", Usage: "a name to say"}, } app.Commands = []cli.Command{ { Name: "describeit", Aliases: []string{"d"}, Usage: "use it to see a description", Description: "This is how we describe describeit the function", Action: func(c *cli.Context) { fmt.Printf("i like to describe things") }, }, } app.Run(os.Args) // Output: // NAME: // describeit - use it to see a description // // USAGE: // command describeit [arguments...] // // DESCRIPTION: // This is how we describe describeit the function }
func TestApp_DefaultStdout(t *testing.T) { app := cli.NewApp() if app.Writer != os.Stdout { t.Error("Default output writer not set.") } }
func TestApp_RunAsSubcommandParseFlags(t *testing.T) { var context *cli.Context a := cli.NewApp() a.Commands = []cli.Command{ { Name: "foo", Action: func(c *cli.Context) { context = c }, Flags: []cli.Flag{ cli.StringFlag{ Name: "lang", Value: "english", Usage: "language for the greeting", }, }, Before: func(_ *cli.Context) error { return nil }, }, } a.Run([]string{"", "foo", "--lang", "spanish", "abcd"}) expect(t, context.Args().Get(0), "abcd") expect(t, context.String("lang"), "spanish") }
func TestGlobalFlagsInSubcommands(t *testing.T) { subcommandRun := false app := cli.NewApp() app.Flags = []cli.Flag{ cli.BoolFlag{Name: "debug, d", Usage: "Enable debugging"}, } app.Commands = []cli.Command{ { Name: "foo", Subcommands: []cli.Command{ { Name: "bar", Action: func(c *cli.Context) { if c.GlobalBool("debug") { subcommandRun = true } }, }, }, }, } app.Run([]string{"command", "-d", "foo", "bar"}) expect(t, subcommandRun, true) }
func registerApp() *cli.App { // Register all the commands (refer flags.go) registerCmd(lsCmd) // List contents of a bucket. registerCmd(mbCmd) // Make a bucket. registerCmd(catCmd) // Display contents of a file. registerCmd(pipeCmd) // Write contents of stdin to a file. registerCmd(shareCmd) // Share documents via URL. registerCmd(cpCmd) // Copy objects and files from multiple sources to single destination. registerCmd(mirrorCmd) // Mirror objects and files from single source to multiple destinations. registerCmd(diffCmd) // Computer differences between two files or folders. registerCmd(rmCmd) // Remove a file or bucket registerCmd(accessCmd) // Set access permissions. registerCmd(sessionCmd) // Manage sessions for copy and mirror. registerCmd(configCmd) // Configure minio client. registerCmd(updateCmd) // Check for new software updates. registerCmd(versionCmd) // Print version. app := cli.NewApp() app.Usage = "Minio Client for cloud storage and filesystems." app.Commands = commands app.Author = "Minio.io" app.Flags = append(mcFlags, globalFlags...) app.CustomAppHelpTemplate = mcHelpTemplate app.CommandNotFound = commandNotFound // handler function declared above. return app }
func registerApp() *cli.App { // Register all commands. registerCommand(serverCmd) registerCommand(versionCmd) registerCommand(updateCmd) registerCommand(controlCmd) // Set up app. app := cli.NewApp() app.Name = "Minio" app.Author = "Minio.io" app.Usage = "Cloud Storage Server." app.Description = `Minio is an Amazon S3 compatible object storage server. Use it to store photos, videos, VMs, containers, log files, or any blob of data as objects.` app.Flags = globalFlags app.Commands = commands app.CustomAppHelpTemplate = minioHelpTemplate app.CommandNotFound = func(ctx *cli.Context, command string) { msg := fmt.Sprintf("‘%s’ is not a minio sub-command. See ‘minio --help’.", command) closestCommands := findClosestCommands(command) if len(closestCommands) > 0 { msg += fmt.Sprintf("\n\nDid you mean one of these?\n") for _, cmd := range closestCommands { msg += fmt.Sprintf(" ‘%s’\n", cmd) } } console.Fatalln(msg) } return app }
// Tests check server syntax. func TestCheckServerSyntax(t *testing.T) { app := cli.NewApp() app.Commands = []cli.Command{serverCmd} serverFlagSet := flag.NewFlagSet("server", 0) serverFlagSet.String("address", ":9000", "") ctx := cli.NewContext(app, serverFlagSet, serverFlagSet) disksGen := func(n int) []string { disks, err := getRandomDisks(n) if err != nil { t.Fatalf("Unable to initialie disks %s", err) } return disks } testCases := [][]string{ disksGen(1), disksGen(4), disksGen(8), disksGen(16), } for i, disks := range testCases { err := serverFlagSet.Parse(disks) if err != nil { t.Errorf("Test %d failed to parse arguments %s", i+1, disks) } defer removeRoots(disks) checkServerSyntax(ctx) } }
func Example() { app := cli.NewApp() app.Name = "todo" app.Usage = "task list on the command line" app.Commands = []cli.Command{ { Name: "add", Aliases: []string{"a"}, Usage: "add a task to the list", Action: func(c *cli.Context) { println("added task: ", c.Args().First()) }, }, { Name: "complete", Aliases: []string{"c"}, Usage: "complete a task on the list", Action: func(c *cli.Context) { println("completed task: ", c.Args().First()) }, }, } app.Run(os.Args) }
func TestApp_ParseSliceFlags(t *testing.T) { var parsedOption, firstArg string var parsedIntSlice []int var parsedStringSlice []string app := cli.NewApp() command := cli.Command{ Name: "cmd", Flags: []cli.Flag{ cli.IntSliceFlag{Name: "p", Value: &cli.IntSlice{}, Usage: "set one or more ip addr"}, cli.StringSliceFlag{Name: "ip", Value: &cli.StringSlice{}, Usage: "set one or more ports to open"}, }, Action: func(c *cli.Context) { parsedIntSlice = c.IntSlice("p") parsedStringSlice = c.StringSlice("ip") parsedOption = c.String("option") firstArg = c.Args().First() }, } app.Commands = []cli.Command{command} app.Run([]string{"", "cmd", "my-arg", "-p", "22", "-p", "80", "-ip", "8.8.8.8", "-ip", "8.8.4.4"}) IntsEquals := func(a, b []int) bool { if len(a) != len(b) { return false } for i, v := range a { if v != b[i] { return false } } return true } StrsEquals := func(a, b []string) bool { if len(a) != len(b) { return false } for i, v := range a { if v != b[i] { return false } } return true } var expectedIntSlice = []int{22, 80} var expectedStringSlice = []string{"8.8.8.8", "8.8.4.4"} if !IntsEquals(parsedIntSlice, expectedIntSlice) { t.Errorf("%v does not match %v", parsedIntSlice, expectedIntSlice) } if !StrsEquals(parsedStringSlice, expectedStringSlice) { t.Errorf("%v does not match %v", parsedStringSlice, expectedStringSlice) } }
func main() { app := cli.NewApp() app.Usage = "A miner for your minio access logs" app.Version = "0.0.1" app.Commands = commands app.Flags = flags app.Author = "Minio.io" app.RunAndExitOnError() }
func registerApp() *cli.App { // Register all the commands registerCmd(lsCmd) // List contents of a bucket registerCmd(mbCmd) // make a bucket registerCmd(catCmd) // concantenate an object to standard output registerCmd(cpCmd) // copy objects and files from multiple sources to single destination registerCmd(castCmd) // cast objects and files from single source to multiple destinations registerCmd(sessionCmd) // session handling for resuming copy and cast operations registerCmd(diffCmd) // compare two objects registerCmd(accessCmd) // set permissions [public, private, readonly, authenticated] for buckets and folders. registerCmd(configCmd) // generate configuration "/home/harsha/.mc/config.json" file. registerCmd(updateCmd) // update Check for new software updates // register all the flags registerFlag(configFlag) // path to config folder registerFlag(quietFlag) // suppress console output registerFlag(forceFlag) // force copying data registerFlag(aliasFlag) // OS toolchain mimic registerFlag(themeFlag) // console theme flag registerFlag(jsonFlag) // json formatted output registerFlag(debugFlag) // enable debugging output app := cli.NewApp() app.Usage = "Minio Client for cloud storage and filesystems" app.Version = getVersion() app.Commands = commands app.Compiled = getVersion() app.Flags = flags app.Author = "Minio.io" app.CustomAppHelpTemplate = `NAME: {{.Name}} - {{.Usage}} USAGE: {{.Name}} {{if .Flags}}[global flags] {{end}}command{{if .Flags}} [command flags]{{end}} [arguments...] COMMANDS: {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} {{end}}{{if .Flags}} GLOBAL FLAGS: {{range .Flags}}{{.}} {{end}}{{end}} VERSION: {{if .Compiled}} {{.Compiled}}{{end}} {{range $key, $value := ExtraInfo}} {{$key}}: {{$value}} {{end}} ` app.CommandNotFound = func(ctx *cli.Context, command string) { console.Fatalf("Command not found: ‘%s’\n", command) } return app }
func registerApp() *cli.App { // Register all the commands registerCmd(lsCmd) // List contents of a bucket. registerCmd(mbCmd) // Make a bucket. registerCmd(catCmd) // Display contents of a file. registerCmd(cpCmd) // Copy objects and files from multiple sources to single destination. registerCmd(mirrorCmd) // Mirror objects and files from single source to multiple destinations. registerCmd(sessionCmd) // Manage sessions for copy and mirror. registerCmd(shareCmd) // Share documents via URL. registerCmd(diffCmd) // Computer differences between two files or folders. registerCmd(accessCmd) // Set access permissions. registerCmd(configCmd) // Configure minio client. registerCmd(updateCmd) // Check for new software updates. registerCmd(versionCmd) // Print version. // register all the flags registerFlag(configFlag) // Path to configuration folder. registerFlag(quietFlag) // Suppress chatty console output. registerFlag(mimicFlag) // Behave like operating system tools. Use with shell aliases. registerFlag(jsonFlag) // Enable json formatted output. registerFlag(debugFlag) // Enable debugging output. registerFlag(noColorFlag) // Disable console coloring. app := cli.NewApp() app.Usage = "Minio Client for cloud storage and filesystems." // hide --version flag, version is a command app.HideVersion = true app.Commands = commands app.Flags = flags app.Author = "Minio.io" app.CustomAppHelpTemplate = `NAME: {{.Name}} - {{.Usage}} USAGE: {{.Name}} {{if .Flags}}[global flags] {{end}}command{{if .Flags}} [command flags]{{end}} [arguments...] COMMANDS: {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} {{end}}{{if .Flags}} GLOBAL FLAGS: {{range .Flags}}{{.}} {{end}}{{end}} VERSION: ` + getFormattedVersion() + `{{ "\n"}} {{range $key, $value := ExtraInfo}} {{$key}}: {{$value}} {{end}}` app.CommandNotFound = func(ctx *cli.Context, command string) { fatalIf(errDummy().Trace(), fmt.Sprintf("Command ‘%s’ not found.", command)) } return app }
func TestApp_Command(t *testing.T) { app := cli.NewApp() fooCommand := cli.Command{Name: "foobar", Aliases: []string{"f"}} batCommand := cli.Command{Name: "batbaz", Aliases: []string{"b"}} app.Commands = []cli.Command{ fooCommand, batCommand, } for _, test := range commandAppTests { expect(t, app.Command(test.name) != nil, test.expected) } }
func main() { // set up go max processes runtime.GOMAXPROCS(runtime.NumCPU()) // set up app app := cli.NewApp() app.Name = "minio" app.Version = getVersion() app.Compiled = getVersion() app.Author = "Minio.io" app.Usage = "Minio Cloud Storage" app.Flags = flags app.Commands = commands app.Before = func(c *cli.Context) error { globalDebugFlag = c.GlobalBool("debug") return nil } app.ExtraInfo = func() map[string]string { if globalDebugFlag { return getSystemData() } return make(map[string]string) } app.CustomAppHelpTemplate = `NAME: {{.Name}} - {{.Usage}} USAGE: {{.Name}} {{if .Flags}}[global flags] {{end}}command{{if .Flags}} [command flags]{{end}} [arguments...] COMMANDS: {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} {{end}}{{if .Flags}} GLOBAL FLAGS: {{range .Flags}}{{.}} {{end}}{{end}} VERSION: {{if .Compiled}} {{.Compiled}}{{end}} {{range $key, $value := ExtraInfo}} {{$key}}: {{$value}} {{end}} ` app.CommandNotFound = func(ctx *cli.Context, command string) { Fatalf("Command not found: ‘%s’\n", command) } app.RunAndExitOnError() }
func main() { // set up iodine iodine.SetGlobalState("mkdonut.version", Version) iodine.SetGlobalState("mkdonut.starttime", time.Now().Format(time.RFC3339)) // set up go max processes runtime.GOMAXPROCS(runtime.NumCPU()) // set up app app := cli.NewApp() app.Action = runMkdonut app.Name = "mkdonut" app.Version = Version app.Compiled = getVersion() app.Author = "Minio.io" app.Usage = "Make a donut" app.Flags = flags app.Before = func(c *cli.Context) error { if c.GlobalBool("debug") { app.ExtraInfo = getSystemData() } return nil } app.CustomAppHelpTemplate = `NAME: {{.Name}} - {{.Usage}} USAGE: {{.Name}} {{if .Flags}}[global flags] {{end}}command{{if .Flags}} [command flags]{{end}} [arguments...] EXAMPLES: 1. Create a donut with four disks $ {{.Name}} donuttest /mnt/export1 /mnt/export2 /mnt/export3 /mnt/export4 2. Create a donut with sixteen disks $ {{.Name}} donut-16 /mnt/export1 /mnt/export2 /mnt/export3 /mnt/export4 /mnt/export5 \ /mnt/export6 /mnt/export7 /mnt/export8 /mnt/export9 /mnt/export10 /mnt/export11 \ /mnt/export12 /mnt/export13 /mnt/export14 /mnt/export15 /mnt/export16 {{if .Flags}} GLOBAL FLAGS: {{range .Flags}}{{.}} {{end}}{{end}} VERSION: {{if .Compiled}} {{.Compiled}}{{end}} {{range $key, $value := .ExtraInfo}} {{$key}}: {{$value}} {{end}} ` app.RunAndExitOnError() }
func TestApp_Run(t *testing.T) { s := "" app := cli.NewApp() app.Action = func(c *cli.Context) { s = s + c.Args().First() } err := app.Run([]string{"command", "foo"}) expect(t, err, nil) err = app.Run([]string{"command", "bar"}) expect(t, err, nil) expect(t, s, "foobar") }
func TestApp_Float64Flag(t *testing.T) { var meters float64 app := cli.NewApp() app.Flags = []cli.Flag{ cli.Float64Flag{Name: "height", Value: 1.5, Usage: "Set the height, in meters"}, } app.Action = func(c *cli.Context) { meters = c.Float64("height") } app.Run([]string{"", "--height", "1.93"}) expect(t, meters, 1.93) }
func main() { app := cli.NewApp() app.Commands = []cli.Command{ { Name: "release", Action: runMinioRelease, }, { Name: "install", Action: runMinioInstall, }, } app.Author = "Minio.io" app.RunAndExitOnError() }
func TestAppNoHelpFlag(t *testing.T) { oldFlag := cli.HelpFlag defer func() { cli.HelpFlag = oldFlag }() cli.HelpFlag = cli.BoolFlag{} app := cli.NewApp() err := app.Run([]string{"test", "-h"}) if err != flag.ErrHelp { t.Errorf("expected error about missing help flag, but got: %s (%T)", err, err) } }
func main() { app := cli.NewApp() app.Usage = "Minio Client for object storage and filesystems" app.Commands = []cli.Command{ { Name: "release", Action: runMcRelease, }, { Name: "install", Action: runMcInstall, }, } app.Author = "Minio.io" app.RunAndExitOnError() }
func TestApp_SetStdout(t *testing.T) { w := &mockWriter{} app := cli.NewApp() app.Name = "test" app.Writer = w err := app.Run([]string{"help"}) if err != nil { t.Fatalf("Run error: %s", err) } if len(w.written) == 0 { t.Error("App did not write output to desired writer.") } }
func main() { // set up iodine iodine.SetGlobalState("minio.version", Version) iodine.SetGlobalState("minio.starttime", time.Now().Format(time.RFC3339)) // set up go max processes runtime.GOMAXPROCS(runtime.NumCPU()) // set up app app := cli.NewApp() app.Name = "minio" app.Version = Version app.Compiled = getVersion() app.Author = "Minio.io" app.Usage = "Minimalist Object Storage" app.Flags = flags app.Commands = commands app.Before = func(c *cli.Context) error { if c.GlobalBool("debug") { app.ExtraInfo = getSystemData() } return nil } app.CustomAppHelpTemplate = `NAME: {{.Name}} - {{.Usage}} USAGE: {{.Name}} {{if .Flags}}[global flags] {{end}}command{{if .Flags}} [command flags]{{end}} [arguments...] COMMANDS: {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} {{end}}{{if .Flags}} GLOBAL FLAGS: {{range .Flags}}{{.}} {{end}}{{end}} VERSION: {{if .Compiled}} {{.Compiled}}{{end}} {{range $key, $value := .ExtraInfo}} {{$key}}: {{$value}} {{end}} ` app.RunAndExitOnError() }
func TestAppHelpPrinter(t *testing.T) { oldPrinter := cli.HelpPrinter defer func() { cli.HelpPrinter = oldPrinter }() var wasCalled = false cli.HelpPrinter = func(template string, data interface{}) { wasCalled = true } app := cli.NewApp() app.Run([]string{"-h"}) if wasCalled == false { t.Errorf("Help printer expected to be called, but was not") } }
func TestApp_CommandWithNoFlagBeforeTerminator(t *testing.T) { var args []string app := cli.NewApp() command := cli.Command{ Name: "cmd", Action: func(c *cli.Context) { args = c.Args() }, } app.Commands = []cli.Command{command} app.Run([]string{"", "cmd", "my-arg", "--", "notAFlagAtAll"}) expect(t, args[0], "my-arg") expect(t, args[1], "--") expect(t, args[2], "notAFlagAtAll") }
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", Aliases: []string{"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") }
func TestAppVersionPrinter(t *testing.T) { oldPrinter := cli.VersionPrinter defer func() { cli.VersionPrinter = oldPrinter }() var wasCalled = false cli.VersionPrinter = func(c *cli.Context) { wasCalled = true } app := cli.NewApp() ctx := cli.NewContext(app, nil, nil) cli.ShowVersion(ctx) if wasCalled == false { t.Errorf("Version printer expected to be called, but was not") } }
func ExampleApp() { // set args for examples sake os.Args = []string{"greet", "--name", "Jeremy"} app := cli.NewApp() app.Name = "greet" app.Flags = []cli.Flag{ cli.StringFlag{Name: "name", Value: "bob", Usage: "a name to say"}, } app.Action = func(c *cli.Context) { fmt.Printf("Hello %v\n", c.String("name")) } app.Author = "Harrison" app.Email = "*****@*****.**" app.Authors = []cli.Author{{Name: "Oliver Allen", Email: "*****@*****.**"}} app.Run(os.Args) // Output: // Hello Jeremy }
func registerApp() *cli.App { // Register all the commands (refer flags.go) registerCmd(lsCmd) // List contents of a bucket. registerCmd(mbCmd) // Make a bucket. registerCmd(catCmd) // Display contents of a file. registerCmd(pipeCmd) // Write contents of stdin to a file. registerCmd(shareCmd) // Share documents via URL. registerCmd(cpCmd) // Copy objects and files from multiple sources to single destination. registerCmd(mirrorCmd) // Mirror objects and files from single source to multiple destinations. registerCmd(diffCmd) // Computer differences between two files or folders. registerCmd(rmCmd) // Remove a file or bucket registerCmd(eventsCmd) // Add events cmd registerCmd(watchCmd) // Add watch cmd registerCmd(policyCmd) // Set policy permissions. registerCmd(sessionCmd) // Manage sessions for copy and mirror. registerCmd(configCmd) // Configure minio client. registerCmd(updateCmd) // Check for new software updates. registerCmd(versionCmd) // Print version. app := cli.NewApp() app.Action = func(ctx *cli.Context) { if strings.HasPrefix(Version, "RELEASE.") { updateMsg, _, err := getReleaseUpdate(mcUpdateStableURL) if err != nil { // Ignore any errors during getReleaseUpdate() because // the internet might not be available. return } if updateMsg.Update { printMsg(updateMsg) } } cli.ShowAppHelp(ctx) } app.Usage = "Minio Client for cloud storage and filesystems." app.Commands = commands app.Author = "Minio.io" app.Flags = append(mcFlags, globalFlags...) app.CustomAppHelpTemplate = mcHelpTemplate app.CommandNotFound = commandNotFound // handler function declared above. return app }