コード例 #1
0
ファイル: bill.go プロジェクト: cjgk/bill
func (b *Bill) logAction(c *cli.Context) {
	var err error
	var comment string
	var date time.Time
	var hours int

	inpdate := c.String("date")
	customer := c.String("customer")
	project := c.String("project")

	hlog := new(Log)
	hlog.Customer = customer
	hlog.Project = project

	hlog.loadEntries(b.LogFile)

	if len(c.Args()) > 0 {
		inp_hours := c.Args().First()
		hours, err = strconv.Atoi(inp_hours)
		if err != nil {
			cli.ShowAppHelp(c)
			os.Exit(0)
		}
	} else {
		cli.ShowAppHelp(c)
		os.Exit(0)
	}

	if len(c.Args()) > 1 {
		comment = c.Args().Get(1)
	}

	date, err = b.getDate(inpdate)
	if err != nil {
		log.Fatalln(err)
	}

	if customer == "last" || project == "last" {
		le, err := hlog.getLastEntry()
		if err != nil {
			log.Fatalln(err)
		}

		if customer == "last" {
			customer = le.Customer
		}

		if project == "last" {
			project = le.Project
		}
	}

	entry := LogEntry{date, customer, project, hours, comment}

	if err := entry.write(b.LogFile); err != nil {
		log.Fatalln(err)
	}
}
コード例 #2
0
func Init(c *cli.Context, reg *harness.MetricRegistry) (harness.Collector, error) {
	args := c.Args()

	if len(args) < 2 {
		cli.ShowAppHelp(c)
		return nil, fmt.Errorf("not enough arguments")
	}

	var (
		endpoint   = args[0]
		configPath = args[1]
	)

	configs, err := loadConfig(configPath)
	if err != nil {
		return nil, err
	}

	scrapers := make([]JsonScraper, len(configs))
	for i, config := range configs {
		tpe := ScrapeTypes[config.Type]
		if tpe == nil {
			return nil, fmt.Errorf("unknown scrape type;type:<%s>", config.Type)
		}
		tpe.Configure(config, reg)
		scraper, err := tpe.NewScraper(config)
		if err != nil {
			return nil, fmt.Errorf("failed to create scraper;name:<%s>,err:<%s>", config.Name, err)
		}
		scrapers[i] = scraper
	}

	return NewCollector(endpoint, scrapers), nil
}
コード例 #3
0
ファイル: bill.go プロジェクト: cjgk/bill
func (b *Bill) reportAction(c *cli.Context) {

	startdate := c.String("start")
	enddate := c.String("end")
	customer := c.String("customer")
	project := c.String("project")

	start, err := b.getDate(startdate)
	if err != nil {
		cli.ShowAppHelp(c)
		os.Exit(0)
	}

	end, err := b.getDate(enddate)
	if err != nil {
		cli.ShowAppHelp(c)
		os.Exit(0)
	}

	hlog := new(Log)
	hlog.Start = start
	hlog.End = end
	hlog.Customer = customer
	hlog.Project = project

	hlog.loadEntries(b.LogFile)

	if c.Bool("invoice") {
		invoices := NewInvoices(hlog, b.CustPath)

		for _, invoice := range invoices {
			err = invoice.write(b.BillPath)
			if err != nil {
				log.Fatalln(err)
			}
		}

		return
	}

	report := hlog.summarize()
	for customer, projects := range report {
		for project, hours := range projects {
			fmt.Printf("%s,%s,%d\n", customer, project, hours)
		}
	}
}
コード例 #4
0
ファイル: cli.go プロジェクト: skycoin/skycoin
func main() {
	// get rpc address from env
	rpcAddr := os.Getenv("RPC_ADDR")
	if rpcAddr == "" {
		rpcAddr = "127.0.0.1:6430"
	}

	// get wallet dir from env
	wltDir := os.Getenv("WALLET_DIR")
	if wltDir == "" {
		home := util.UserHome()
		wltDir = home + "/.skycoin/wallets"
	}

	// get wallet name from env
	wltName := os.Getenv("WALLET_NAME")
	if wltName == "" {
		wltName = "skycoin_cli.wlt"
	} else {
		if !strings.HasSuffix(wltName, ".wlt") {
			fmt.Println("value of 'WALLET_NAME' env is not correct, must has .wlt extenstion")
			return
		}
	}

	// init the skycli
	skycli.Init(skycli.RPCAddr(rpcAddr),
		skycli.WalletDir(wltDir),
		skycli.DefaultWltName(wltName))

	cli.SubcommandHelpTemplate = commandHelpTemplate
	cli.CommandHelpTemplate = commandHelpTemplate
	cli.HelpFlag = cli.BoolFlag{
		Name:  "help,h",
		Usage: "show help, can also be used to show subcommand help",
	}

	app := cli.NewApp()
	app.Usage = "the skycoin command line interface"
	app.Version = "0.1"
	app.Commands = skycli.Commands()
	app.EnableBashCompletion = true
	app.OnUsageError = func(context *cli.Context, err error, isSubcommand bool) error {
		fmt.Fprintf(context.App.Writer, "Error: %v\n\n", err)
		cli.ShowAppHelp(context)
		return nil
	}
	app.CommandNotFound = func(ctx *cli.Context, command string) {
		tmp := fmt.Sprintf("{{.HelpName}}: '%s' is not a {{.HelpName}} command. See '{{.HelpName}} --help'.\n", command)
		cli.HelpPrinter(app.Writer, tmp, app)
	}

	if err := app.Run(os.Args); err != nil {
		fmt.Println(err)
	}
}
コード例 #5
0
ファイル: main.go プロジェクト: jfrazelle/netscan
func main() {
	app := cli.NewApp()
	app.Name = "netscan"
	app.Version = VERSION
	app.Author = "@jessfraz"
	app.Email = "*****@*****.**"
	app.Usage = "Scan network ips and ports."
	app.Before = preload
	app.Flags = []cli.Flag{
		cli.BoolFlag{
			Name:  "debug, d",
			Usage: "run in debug mode",
		},
		cli.StringFlag{
			Name:  "timeout, t",
			Value: "1s",
			Usage: "override timeout used for check",
		},
		cli.StringFlag{
			Name:  "port, p",
			Value: "1-1000",
			Usage: "port range to check",
		},
		cli.StringFlag{
			Name:  "proto",
			Value: "tcp,udp",
			Usage: "protocol/s to check",
		},
	}
	app.Action = func(c *cli.Context) {
		if len(c.Args()) == 0 {
			logrus.Errorf("Pass an ip or cidr, ex: 192.168.104.1/24")
			cli.ShowAppHelp(c)
			return
		}

		var err error
		timeout, err = time.ParseDuration(c.String("timeout"))
		if err != nil {
			logrus.Error(err)
			return
		}

		beginPort, endPort, err = parsePortRange(c.String("port"))
		if err != nil {
			logrus.Error(err)
			return
		}

		protos = strings.Split(c.String("proto"), ",")

		scan(c.Args().First())
	}
	app.Run(os.Args)
}
コード例 #6
0
ファイル: main.go プロジェクト: octoblu/go-go
func getOpts(context *cli.Context) string {
	name := context.Args().First()

	if name == "" {
		cli.ShowAppHelp(context)
		color.Red("  Missing required arg <project-name>")
		os.Exit(1)
	}

	return name
}
コード例 #7
0
ファイル: main.go プロジェクト: octoblu/go-go
func getOpts(context *cli.Context) string {
	example := context.String("example")

	if example == "" {
		cli.ShowAppHelp(context)

		if example == "" {
			color.Red("  Missing required flag --example or {{.PROJECTNAME}}_EXAMPLE")
		}
		os.Exit(1)
	}

	return example
}
コード例 #8
0
ファイル: telnet.go プロジェクト: RookieGameDevs/surviveler
/*
 * NewTelnetServer initializes a TelnetServer struct
 */
func NewTelnetServer(port string, registry *ClientRegistry) *TelnetServer {
	tns := TelnetServer{
		port:     port,
		registry: registry,
		CliApp:   cli.NewApp(),
	}
	tns.CliApp.Name = "Surviveler admin console"
	tns.CliApp.Usage = "Control a Surviveler game session from the comfort of your telnet console"
	tns.CliApp.HideVersion = true
	tns.CliApp.CommandNotFound = func(c *cli.Context, s string) {
		cli.ShowAppHelp(c)
	}
	cli.OsExiter = func(int) {}
	return &tns
}
コード例 #9
0
ファイル: cli.go プロジェクト: bitrise-io/bitrise
// Run ...
func Run() {
	// Parse cl
	cli.VersionPrinter = printVersion

	app := cli.NewApp()
	app.Name = path.Base(os.Args[0])
	app.Usage = "Bitrise Automations Workflow Runner"
	app.Version = version.VERSION

	app.Author = ""
	app.Email = ""

	app.Before = before

	app.Flags = flags
	app.Commands = commands

	app.Action = func(c *cli.Context) error {
		pluginName, pluginArgs, isPlugin := plugins.ParseArgs(c.Args())
		if isPlugin {
			log.Debugf("Try to run bitrise plugin: (%s) with args: (%v)", pluginName, pluginArgs)

			plugin, found, err := plugins.LoadPlugin(pluginName)
			if err != nil {
				return fmt.Errorf("Failed to get plugin (%s), error: %s", pluginName, err)
			}
			if !found {
				return fmt.Errorf("Plugin (%s) not installed", pluginName)
			}

			log.Debugf("Start plugin: (%s)", pluginName)
			if err := plugins.RunPluginByCommand(plugin, pluginArgs); err != nil {
				return fmt.Errorf("Failed to run plugin (%s), error: %s", pluginName, err)
			}
		} else {
			if err := cli.ShowAppHelp(c); err != nil {
				return fmt.Errorf("Failed to show help, error: %s", err)
			}
			return errors.New("")
		}

		return nil
	}

	if err := app.Run(os.Args); err != nil {
		log.Fatal(err)
	}
}
コード例 #10
0
ファイル: main.go プロジェクト: fritzing/fzp
func main() {
	app := cli.NewApp()
	app.Name = "fzp"
	app.Usage = "fzp tool (validator, encoder, formatter)"
	app.Version = "0.2.6"
	app.Email = "https://github.com/fritzing/fzp"
	app.Commands = []cli.Command{
		{
			Name:   "validate",
			Usage:  "validate fzp file/files",
			Flags:  commandValidateFlags,
			Action: commandValidateAction,
		},
		{
			Name:   "encode",
			Usage:  "read a fzp file and encode to json",
			Flags:  commandEncodeFlags,
			Action: commandEncodeAction,
		},
		{
			Name:   "format",
			Usage:  "read a fzp file and format it",
			Flags:  commandFormatFlags,
			Action: commandFormatAction,
		},
		{
			Name:   "get",
			Usage:  "get data from a fzp file",
			Flags:  commandGetFlags,
			Action: commandGetAction,
		},
		{
			Name:   "create",
			Usage:  "create a new fzp dataset",
			Flags:  commandCreateFlags,
			Action: commandCreateAction,
		},
	}
	// cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) {
	// 	fmt.Println("TODO: better main help")
	// }
	app.Action = func(c *cli.Context) {
		cli.ShowAppHelp(c)
		return
	}
	app.Run(os.Args)
}
コード例 #11
0
ファイル: main.go プロジェクト: kyokomi/excel-to-markdown
func doMain(c *cli.Context) error {
	inputDirPath := c.String("input-dir")
	outputDirPath := c.String("output-dir")

	if inputDirPath == "" || outputDirPath == "" {
		cli.ShowAppHelp(c)
		return nil
	}

	d, err := ioutil.ReadDir(inputDirPath)
	if err != nil {
		return err
	}

	var wg sync.WaitGroup
	for _, file := range d {
		if file.IsDir() {
			continue
		}
		inputFilePath := strings.Join([]string{inputDirPath, file.Name()}, "/")
		if !strings.HasSuffix(inputFilePath, ".xlsx") {
			fmt.Println("error don't xlsx file.")
			continue
		}

		outputDirPath := strings.Join([]string{outputDirPath, file.Name()}, "/")
		outputDirPath = strings.TrimSuffix(outputDirPath, ".xlsx")
		if _, err := ioutil.ReadDir(outputDirPath); err != nil {
			err := os.Mkdir(outputDirPath, 0755)
			if err != nil {
				return err
			}
		}

		wg.Add(1)
		go func(inputFilePath string) {
			readWriteSheet(inputFilePath, outputDirPath)
			wg.Done()
		}(inputFilePath)
	}
	wg.Wait()

	return nil
}
コード例 #12
0
ファイル: appFactory.go プロジェクト: echocat/caretakerd
func newAppFor(executableType ExecutableType) *cli.App {
	var configDescription string
	var configEnvVar string
	switch executableType {
	case Daemon:
		configDescription = "Configuration file for daemon."
		configEnvVar = "CTD_CONFIG"
	case Control:
		configDescription = "Configuration file for control."
		configEnvVar = "CTCTL_CONFIG"
	default:
		configDescription = "Configuration file for daemon and control."
		configEnvVar = "CT_CONFIG"
	}

	app := cli.NewApp()
	app.Version = caretakerd.Version
	app.Commands = []cli.Command{}
	app.OnUsageError = func(context *cli.Context, err error, isSubcommand bool) error {
		fmt.Fprintf(app.Writer, "Error: %v\n\n", err)
		if isSubcommand {
			cli.ShowSubcommandHelp(context)
		} else {
			cli.ShowAppHelp(context)
		}
		return err
	}
	app.Flags = []cli.Flag{
		cli.GenericFlag{
			Name:   "config,c",
			Value:  conf,
			Usage:  configDescription,
			EnvVar: configEnvVar,
		},
		cli.GenericFlag{
			Name:  "address,a",
			Value: listenAddress,
			Usage: "Listen address of the daemon.",
		},
	}

	if executableType != Daemon {
		app.Flags = append(app.Flags, cli.GenericFlag{
			Name:  "pem,p",
			Value: pemFile,
			Usage: "Location of PEM file which contains the private public key pair for access to the daemon.",
		})
	}

	switch executableType {
	case Daemon:
		app.Name = caretakerd.DaemonName
		app.Usage = "Simple control daemon for processes."
	case Control:
		app.Name = caretakerd.ControlName
		app.Usage = "Remote control for " + caretakerd.DaemonName
	default:
		app.Name = caretakerd.BaseName
		app.Usage = "Simple control daemon for processes including remote control for itself."
	}
	return app
}
コード例 #13
0
func main() {

	app := cli.NewApp()
	app.Name = ProjectName
	app.Usage = Usage
	app.Version = Version

	app.Flags = []cli.Flag{
		cli.BoolFlag{
			Name:  "verbose",
			Usage: "show more output",
		},
		cli.BoolFlag{
			Name:  "e, env",
			Usage: "load AWS credentials from environment",
		},
		cli.BoolFlag{
			Name:  "commit",
			Usage: "compiled git commit",
		},
	}

	app.Action = func(ctx *cli.Context) error {
		args := ctx.Args()
		if ctx.Bool("commit") {
			CommitMessage()
		} else if args.Present() {
			cli.ShowCommandHelp(ctx, args.First())
		} else {
			cli.ShowAppHelp(ctx)
		}
		return nil
	}

	// Commands
	app.Commands = []cli.Command{
		{
			Name: "plan",
			Flags: []cli.Flag{
				cli.BoolFlag{
					Name:  "destroy",
					Usage: "plan destroy",
				},
				cli.BoolFlag{
					Name:  "no-sync",
					Usage: "Don't perform initial s3 sync",
				},
				cli.StringFlag{
					Name:  "security",
					Usage: "security provider, current options <default>, <aws-internal>",
				},
				cli.StringFlag{
					Name:  "security-role",
					Usage: "security iam role if using -security=aws-internal security",
				},
				cli.StringFlag{
					Name:  "config-location",
					Usage: "config location, must be format <location>/<environment>.tfvars",
				},
			},
			Usage:  "terraform plan",
			Action: CmdPlan,
		},
		{
			Name: "apply",
			Flags: []cli.Flag{
				cli.BoolFlag{
					Name:  "no-sync",
					Usage: "Don't perform initial s3 sync",
				},
				cli.StringFlag{
					Name:  "security",
					Usage: "security provider, current options <default>, <aws-internal>",
				},
				cli.StringFlag{
					Name:  "security-role",
					Usage: "security iam role if using -security=aws-internal security",
				},
				cli.StringFlag{
					Name:  "config-location",
					Usage: "config location, must be format <location>/<environment>.tfvars",
				},
			},
			Usage:  "terraform apply",
			Action: CmdApply,
		},
		{
			Name: "destroy",
			Flags: []cli.Flag{
				cli.BoolFlag{
					Name:  "force",
					Usage: "Force destroy",
				},
				cli.BoolFlag{
					Name:  "no-sync",
					Usage: "Don't perform initial s3 sync",
				},
				cli.StringFlag{
					Name:  "security",
					Usage: "security provider, current options <default>, <aws-internal>",
				},
				cli.StringFlag{
					Name:  "security-role",
					Usage: "security iam role if using -security=aws-internal security",
				},
				cli.StringFlag{
					Name:  "config-location",
					Usage: "config location, must be format <location>/<environment>.tfvars",
				},
			},
			Usage:  "terraform destroy",
			Action: CmdDestroy,
		},
		{
			Name: "refresh",
			Flags: []cli.Flag{
				cli.BoolFlag{
					Name:  "no-sync",
					Usage: "Don't perform initial s3 sync",
				},
				cli.StringFlag{
					Name:  "security",
					Usage: "security provider, current options <default>, <aws-internal>",
				},
				cli.StringFlag{
					Name:  "security-role",
					Usage: "security iam role if using -security=aws-internal security",
				},
				cli.StringFlag{
					Name:  "config-location",
					Usage: "config location, must be format <location>/<environment>.tfvars",
				},
			},
			Usage:  "terraform refresh",
			Action: CmdRefresh,
		},
		{
			Name: "taint",
			Flags: []cli.Flag{
				cli.BoolFlag{
					Name:  "no-sync",
					Usage: "Don't perform initial s3 sync",
				},
				cli.StringFlag{
					Name:  "module",
					Usage: "tainted module path",
				},
				cli.StringFlag{
					Name:  "security",
					Usage: "security provider, current options <default>, <aws-internal>",
				},
				cli.StringFlag{
					Name:  "security-role",
					Usage: "security iam role if using -security=aws-internal security",
				},
				cli.StringFlag{
					Name:  "config-location",
					Usage: "config location, must be format <location>/<environment>.tfvars",
				},
			},
			Usage:  "terraform taint",
			Action: CmdTaint,
		},
		{
			Name: "untaint",
			Flags: []cli.Flag{
				cli.BoolFlag{
					Name:  "no-sync",
					Usage: "Don't perform initial s3 sync",
				},
				cli.StringFlag{
					Name:  "module",
					Usage: "tainted module path",
				},
				cli.StringFlag{
					Name:  "security",
					Usage: "security provider, current options <default>, <aws-internal>",
				},
				cli.StringFlag{
					Name:  "security-role",
					Usage: "security iam role if using -security=aws-internal security",
				},
				cli.StringFlag{
					Name:  "config-location",
					Usage: "config location, must be format <location>/<environment>.tfvars",
				},
			},
			Usage:  "terraform untaint",
			Action: CmdUntaint,
		},
		{
			Name: "download",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "config-location",
					Usage: "config location, must be format <location>/<environment>.tfvars",
				},
			},
			Usage:  "download existing state to s3",
			Action: CmdDownload,
		},
		{
			Name: "upload",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "config-location",
					Usage: "config location, must be format <location>/<environment>.tfvars",
				},
			},
			Usage:  "upload existing state to s3",
			Action: CmdUpload,
		},
	}
	app.Run(os.Args)
}
コード例 #14
0
ファイル: main.go プロジェクト: CodyGuo/Go-Cody
func main() {
	app := cli.NewApp()
	app.Name = "kənˈtrīv"
	app.Version = "19.99.0"
	app.Compiled = time.Now()
	app.Authors = []cli.Author{
		cli.Author{
			Name:  "Example Human",
			Email: "*****@*****.**",
		},
	}
	app.Copyright = "(c) 1999 Serious Enterprise"
	app.HelpName = "contrive"
	app.Usage = "demonstrate available API"
	app.UsageText = "contrive - demonstrating the available API"
	app.ArgsUsage = "[args and such]"
	app.Commands = []cli.Command{
		cli.Command{
			Name:        "doo",
			Aliases:     []string{"do"},
			Category:    "motion",
			Usage:       "do the doo",
			UsageText:   "doo - does the dooing",
			Description: "no really, there is a lot of dooing to be done",
			ArgsUsage:   "[arrgh]",
			Flags: []cli.Flag{
				cli.BoolFlag{Name: "forever, forevvarr"},
			},
			Subcommands: cli.Commands{
				cli.Command{
					Name:   "wop",
					Action: wopAction,
				},
			},
			SkipFlagParsing: false,
			HideHelp:        false,
			Hidden:          false,
			HelpName:        "doo!",
			BashComplete: func(c *cli.Context) {
				fmt.Fprintf(c.App.Writer, "--better\n")
			},
			Before: func(c *cli.Context) error {
				fmt.Fprintf(c.App.Writer, "brace for impact\n")
				return nil
			},
			After: func(c *cli.Context) error {
				fmt.Fprintf(c.App.Writer, "did we lose anyone?\n")
				return nil
			},
			Action: func(c *cli.Context) error {
				c.Command.FullName()
				c.Command.HasName("wop")
				c.Command.Names()
				c.Command.VisibleFlags()
				fmt.Fprintf(c.App.Writer, "dodododododoodododddooooododododooo\n")
				if c.Bool("forever") {
					c.Command.Run(c)
				}
				return nil
			},
			OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error {
				fmt.Fprintf(c.App.Writer, "for shame\n")
				return err
			},
		},
	}
	app.Flags = []cli.Flag{
		cli.BoolFlag{Name: "fancy"},
		cli.BoolTFlag{Name: "fancier"},
		cli.DurationFlag{Name: "howlong, H", Value: time.Second * 3},
		cli.Float64Flag{Name: "howmuch"},
		cli.GenericFlag{Name: "wat", Value: &genericType{}},
		cli.Int64Flag{Name: "longdistance"},
		cli.Int64SliceFlag{Name: "intervals"},
		cli.IntFlag{Name: "distance"},
		cli.IntSliceFlag{Name: "times"},
		cli.StringFlag{Name: "dance-move, d"},
		cli.StringSliceFlag{Name: "names, N"},
		cli.UintFlag{Name: "age"},
		cli.Uint64Flag{Name: "bigage"},
	}
	app.EnableBashCompletion = true
	app.HideHelp = false
	app.HideVersion = false
	app.BashComplete = func(c *cli.Context) {
		fmt.Fprintf(c.App.Writer, "lipstick\nkiss\nme\nlipstick\nringo\n")
	}
	app.Before = func(c *cli.Context) error {
		fmt.Fprintf(c.App.Writer, "HEEEERE GOES\n")
		return nil
	}
	app.After = func(c *cli.Context) error {
		fmt.Fprintf(c.App.Writer, "Phew!\n")
		return nil
	}
	app.CommandNotFound = func(c *cli.Context, command string) {
		fmt.Fprintf(c.App.Writer, "Thar be no %q here.\n", command)
	}
	app.OnUsageError = func(c *cli.Context, err error, isSubcommand bool) error {
		if isSubcommand {
			return err
		}

		fmt.Fprintf(c.App.Writer, "WRONG: %#v\n", err)
		return nil
	}
	app.Action = func(c *cli.Context) error {
		cli.DefaultAppComplete(c)
		cli.HandleExitCoder(errors.New("not an exit coder, though"))
		cli.ShowAppHelp(c)
		cli.ShowCommandCompletions(c, "nope")
		cli.ShowCommandHelp(c, "also-nope")
		cli.ShowCompletions(c)
		cli.ShowSubcommandHelp(c)
		cli.ShowVersion(c)

		categories := c.App.Categories()
		categories.AddCommand("sounds", cli.Command{
			Name: "bloop",
		})

		for _, category := range c.App.Categories() {
			fmt.Fprintf(c.App.Writer, "%s\n", category.Name)
			fmt.Fprintf(c.App.Writer, "%#v\n", category.Commands)
			fmt.Fprintf(c.App.Writer, "%#v\n", category.VisibleCommands())
		}

		fmt.Printf("%#v\n", c.App.Command("doo"))
		if c.Bool("infinite") {
			c.App.Run([]string{"app", "doo", "wop"})
		}

		if c.Bool("forevar") {
			c.App.RunAsSubcommand(c)
		}
		c.App.Setup()
		fmt.Printf("%#v\n", c.App.VisibleCategories())
		fmt.Printf("%#v\n", c.App.VisibleCommands())
		fmt.Printf("%#v\n", c.App.VisibleFlags())

		fmt.Printf("%#v\n", c.Args().First())
		if len(c.Args()) > 0 {
			fmt.Printf("%#v\n", c.Args()[1])
		}
		fmt.Printf("%#v\n", c.Args().Present())
		fmt.Printf("%#v\n", c.Args().Tail())

		set := flag.NewFlagSet("contrive", 0)
		nc := cli.NewContext(c.App, set, c)

		fmt.Printf("%#v\n", nc.Args())
		fmt.Printf("%#v\n", nc.Bool("nope"))
		fmt.Printf("%#v\n", nc.BoolT("nerp"))
		fmt.Printf("%#v\n", nc.Duration("howlong"))
		fmt.Printf("%#v\n", nc.Float64("hay"))
		fmt.Printf("%#v\n", nc.Generic("bloop"))
		fmt.Printf("%#v\n", nc.Int64("bonk"))
		fmt.Printf("%#v\n", nc.Int64Slice("burnks"))
		fmt.Printf("%#v\n", nc.Int("bips"))
		fmt.Printf("%#v\n", nc.IntSlice("blups"))
		fmt.Printf("%#v\n", nc.String("snurt"))
		fmt.Printf("%#v\n", nc.StringSlice("snurkles"))
		fmt.Printf("%#v\n", nc.Uint("flub"))
		fmt.Printf("%#v\n", nc.Uint64("florb"))
		fmt.Printf("%#v\n", nc.GlobalBool("global-nope"))
		fmt.Printf("%#v\n", nc.GlobalBoolT("global-nerp"))
		fmt.Printf("%#v\n", nc.GlobalDuration("global-howlong"))
		fmt.Printf("%#v\n", nc.GlobalFloat64("global-hay"))
		fmt.Printf("%#v\n", nc.GlobalGeneric("global-bloop"))
		fmt.Printf("%#v\n", nc.GlobalInt("global-bips"))
		fmt.Printf("%#v\n", nc.GlobalIntSlice("global-blups"))
		fmt.Printf("%#v\n", nc.GlobalString("global-snurt"))
		fmt.Printf("%#v\n", nc.GlobalStringSlice("global-snurkles"))

		fmt.Printf("%#v\n", nc.FlagNames())
		fmt.Printf("%#v\n", nc.GlobalFlagNames())
		fmt.Printf("%#v\n", nc.GlobalIsSet("wat"))
		fmt.Printf("%#v\n", nc.GlobalSet("wat", "nope"))
		fmt.Printf("%#v\n", nc.NArg())
		fmt.Printf("%#v\n", nc.NumFlags())
		fmt.Printf("%#v\n", nc.Parent())

		nc.Set("wat", "also-nope")

		ec := cli.NewExitError("ohwell", 86)
		fmt.Fprintf(c.App.Writer, "%d", ec.ExitCode())
		fmt.Printf("made it!\n")
		return ec
	}

	if os.Getenv("HEXY") != "" {
		app.Writer = &hexWriter{}
		app.ErrWriter = &hexWriter{}
	}

	app.Metadata = map[string]interface{}{
		"layers":          "many",
		"explicable":      false,
		"whatever-values": 19.99,
	}

	app.Run(os.Args)
}
コード例 #15
0
ファイル: cli.go プロジェクト: eldarion-gondor/cli
// Run is @@@
func (c *CLI) Run() {
	app := cli.NewApp()
	app.Name = c.Name
	app.Version = c.Version
	app.Author = c.Author
	app.Email = c.Email
	app.Usage = c.Usage
	app.EnableBashCompletion = true
	app.Flags = []cli.Flag{}
	if c.Config.Cloud == nil {
		app.Flags = append(app.Flags, cli.StringFlag{
			Name:   "cloud",
			Value:  "",
			Usage:  "cloud used for this invocation",
			EnvVar: fmt.Sprintf("%s_CLOUD", c.EnvVarPrefix),
		})
	}
	app.Flags = append(app.Flags,
		cli.StringFlag{
			Name:   "cluster",
			Value:  "",
			Usage:  "cluster used for this invocation",
			EnvVar: fmt.Sprintf("%s_CLUSTER", c.EnvVarPrefix),
		},
		cli.StringFlag{
			Name:   "resource-group",
			Value:  "",
			Usage:  "resource group used for this invocation",
			EnvVar: fmt.Sprintf("%s_RESOURCE_GROUP", c.EnvVarPrefix),
		},
		cli.StringFlag{
			Name:   "site",
			Value:  "",
			Usage:  "site used for this invocation",
			EnvVar: fmt.Sprintf("%s_SITE", c.EnvVarPrefix),
		},
		cli.BoolFlag{
			Name:  "log-http",
			Usage: "log HTTP interactions",
		},
	)
	app.Action = func(ctx *cli.Context) error {
		c.checkVersion()
		cli.ShowAppHelp(ctx)
		return nil
	}
	app.Commands = []cli.Command{
		{
			Name:   "login",
			Usage:  fmt.Sprintf("authenticate with the %s", c.LongName),
			Action: c.cmd(loginCmd),
		},
		{
			Name:   "logout",
			Usage:  fmt.Sprintf("invalidate any existing credentials with the %s", c.LongName),
			Action: c.cmd(logoutCmd),
		},
		{
			Name:   "upgrade",
			Usage:  fmt.Sprintf("upgrade the client to latest version supported by the %s", c.LongName),
			Action: c.cmd(upgradeCmd),
		},
		{
			Name:  "resource-groups",
			Usage: "manage resource groups",
			Action: c.cmd(func(c *CLI, ctx *cli.Context) {
				cli.ShowSubcommandHelp(ctx)
			}),
			Subcommands: []cli.Command{
				{
					Name:   "list",
					Usage:  "show resource groups to which you belong",
					Action: c.cmd(c.stdCmd(resourceGroupListCmd)),
				},
			},
		},
		{
			Name:  "keypairs",
			Usage: "manage keypairs",
			Action: c.cmd(func(c *CLI, ctx *cli.Context) {
				cli.ShowSubcommandHelp(ctx)
			}),
			Subcommands: []cli.Command{
				{
					Name:   "list",
					Usage:  "List keypairs",
					Action: c.cmd(c.stdCmd(keypairsListCmd)),
				},
				{
					Name:  "create",
					Usage: "create a keypair",
					Flags: []cli.Flag{
						cli.StringFlag{
							Name:  "name",
							Value: "",
							Usage: "name of keypair",
						},
					},
					Action: c.cmd(c.stdCmd(keypairsCreateCmd)),
				},
				{
					Name:  "attach",
					Usage: "attach keypair to service",
					Flags: []cli.Flag{
						cli.StringFlag{
							Name:  "instance",
							Value: "",
							Usage: "instance label",
						},
						cli.StringFlag{
							Name:  "keypair",
							Value: "",
							Usage: "name of keypair",
						},
						cli.StringFlag{
							Name:  "service",
							Value: "",
							Usage: "service path",
						},
					},
					Action: c.cmd(c.stdCmd(keypairsAttachCmd)),
				},
				{
					Name:  "detach",
					Usage: "detach keypair from service",
					Flags: []cli.Flag{
						cli.StringFlag{
							Name:  "instance",
							Value: "",
							Usage: "instance label",
						},
						cli.StringFlag{
							Name:  "service",
							Value: "",
							Usage: "service name",
						},
					},
					Action: c.cmd(c.stdCmd(keypairsDetachCmd)),
					BashComplete: func(ctx *cli.Context) {
					},
				},
				{
					Name:   "delete",
					Usage:  "delete a keypair by name",
					Action: c.cmd(c.stdCmd(keypairsDeleteCmd)),
					BashComplete: func(ctx *cli.Context) {
						if len(ctx.Args()) > 0 {
							return
						}
						api := c.GetAPIClient(ctx)
						resourceGroup := c.GetResourceGroup(ctx)
						keypairs, err := api.KeyPairs.List(&*resourceGroup.URL)
						if err != nil {
							return
						}
						for i := range keypairs {
							fmt.Println(*keypairs[i].Name)
						}
					},
				},
			},
		},
		{
			Name:  "sites",
			Usage: "manage sites",
			Action: c.cmd(func(c *CLI, ctx *cli.Context) {
				cli.ShowSubcommandHelp(ctx)
			}),
			Subcommands: []cli.Command{
				{
					Name:   "list",
					Usage:  "show sites in the resource group",
					Action: c.cmd(c.stdCmd(sitesListCmd)),
				},
				{
					Name:  "init",
					Usage: "create a site, production instance and write config",
					Flags: []cli.Flag{
						cli.StringFlag{
							Name:  "name",
							Value: "",
							Usage: "optional name for site",
						},
					},
					Action: c.cmd(c.stdCmd(sitesInitCmd)),
				},
				{
					Name:   "create",
					Usage:  "create a site in the resource group",
					Action: c.cmd(c.stdCmd(sitesCreateCmd)),
				},
				{
					Name:   "delete",
					Usage:  "delete a site in the resource group",
					Action: c.cmd(c.stdCmd(sitesDeleteCmd)),
					BashComplete: func(ctx *cli.Context) {
						if len(ctx.Args()) > 0 {
							return
						}
						api := c.GetAPIClient(ctx)
						resourceGroup := c.GetResourceGroup(ctx)
						sites, err := api.Sites.List(&*resourceGroup.URL)
						if err != nil {
							return
						}
						for i := range sites {
							fmt.Println(*sites[i].Name)
						}
					},
				},
				{
					Name:   "env",
					Usage:  "",
					Action: c.cmd(c.stdCmd(sitesEnvCmd)),
					BashComplete: func(ctx *cli.Context) {
						if len(ctx.Args()) > 0 {
							return
						}
						api := c.GetAPIClient(ctx)
						resourceGroup := c.GetResourceGroup(ctx)
						sites, err := api.Sites.List(&*resourceGroup.URL)
						if err != nil {
							return
						}
						for i := range sites {
							fmt.Println(*sites[i].Name)
						}
					},
				},
				{
					Name:  "users",
					Usage: "manage users",
					Action: c.cmd(func(c *CLI, ctx *cli.Context) {
						cli.ShowSubcommandHelp(ctx)
					}),
					Subcommands: []cli.Command{
						{
							Name:   "list",
							Usage:  "List users for the site",
							Action: c.cmd(c.stdCmd(sitesUsersListCmd)),
						},
						{
							Name:   "add",
							Usage:  "Add a user to site with a given role",
							Action: c.cmd(c.stdCmd(sitesUsersAddCmd)),
							Flags: []cli.Flag{
								cli.StringFlag{
									Name:  "role",
									Value: "dev",
									Usage: "desired role for user",
								},
							},
						},
					},
				},
			},
		},
		{
			Name:  "instances",
			Usage: "manage instances",
			Action: c.cmd(func(c *CLI, ctx *cli.Context) {
				cli.ShowSubcommandHelp(ctx)
			}),
			Subcommands: []cli.Command{
				{
					Name:  "create",
					Usage: "create new instance",
					Flags: []cli.Flag{
						cli.StringFlag{
							Name:  "kind",
							Value: "",
							Usage: "kind of instance",
						},
					},
					Action: c.cmd(c.stdCmd(instancesCreateCmd)),
				},
				{
					Name:   "list",
					Usage:  "",
					Action: c.cmd(c.stdCmd(instancesListCmd)),
				},
				{
					Name:   "delete",
					Usage:  "",
					Action: c.cmd(c.stdCmd(instancesDeleteCmd)),
					BashComplete: func(ctx *cli.Context) {
						if len(ctx.Args()) > 0 {
							return
						}
						api := c.GetAPIClient(ctx)
						site := c.GetSite(ctx)
						instances, err := api.Instances.List(&*site.URL)
						if err != nil {
							fatal(err.Error())
						}
						for i := range instances {
							fmt.Println(*instances[i].Label)
						}
					},
				},
				{
					Name:  "env",
					Usage: "",
					Flags: []cli.Flag{
						cli.StringFlag{
							Name:  "instance",
							Value: "",
							Usage: "instance label",
						},
					},
					Action: c.cmd(c.stdCmd(instancesEnvCmd)),
					BashComplete: func(ctx *cli.Context) {
						if len(ctx.Args()) > 0 {
							return
						}
						api := c.GetAPIClient(ctx)
						site := c.GetSite(ctx)
						instances, err := api.Instances.List(&*site.URL)
						if err != nil {
							fatal(err.Error())
						}
						for i := range instances {
							fmt.Println(*instances[i].Label)
						}
					},
				},
			},
		},
		{
			Name:  "services",
			Usage: "manage services",
			Action: c.cmd(func(c *CLI, ctx *cli.Context) {
				cli.ShowSubcommandHelp(ctx)
			}),
			Subcommands: []cli.Command{
				{
					Name:  "create",
					Usage: "create new service",
					Flags: []cli.Flag{
						cli.StringFlag{
							Name:  "name",
							Value: "",
							Usage: "name of the service",
						},
						cli.StringFlag{
							Name:  "version",
							Value: "",
							Usage: "version for the new service",
						},
						cli.StringFlag{
							Name:  "instance",
							Value: "",
							Usage: "instance label",
						},
					},
					Action: c.cmd(c.stdCmd(servicesCreateCmd)),
				},
				{
					Name:  "list",
					Usage: "",
					Flags: []cli.Flag{
						cli.StringFlag{
							Name:  "instance",
							Value: "",
							Usage: "instance label",
						},
					},
					Action: c.cmd(c.stdCmd(servicesListCmd)),
				},
				{
					Name:  "config",
					Usage: "",
					Flags: []cli.Flag{
						cli.StringFlag{
							Name:  "instance",
							Value: "",
							Usage: "instance label",
						},
					},
					Subcommands: []cli.Command{
						{
							Name:   "get",
							Usage:  "",
							Action: c.cmd(c.stdCmd(servicesConfigGetCmd)),
						},
						{
							Name:   "set",
							Usage:  "",
							Action: c.cmd(c.stdCmd(servicesConfigSetCmd)),
						},
					},
				},
				{
					Name:  "delete",
					Usage: "",
					Flags: []cli.Flag{
						cli.StringFlag{
							Name:  "instance",
							Value: "",
							Usage: "instance label",
						},
					},
					Action: c.cmd(c.stdCmd(servicesDeleteCmd)),
					BashComplete: func(ctx *cli.Context) {
						if len(ctx.Args()) > 0 {
							return
						}
						api := c.GetAPIClient(ctx)
						instance := c.GetInstance(ctx, nil)
						services, err := api.Services.List(&*instance.URL)
						if err != nil {
							fatal(err.Error())
						}
						for i := range services {
							fmt.Println(*services[i].Name)
						}
					},
				},
				{
					Name:  "env",
					Usage: "",
					Flags: []cli.Flag{
						cli.StringFlag{
							Name:  "instance",
							Value: "",
							Usage: "instance label",
						},
					},
					Action: c.cmd(c.stdCmd(servicesEnvCmd)),
					BashComplete: func(ctx *cli.Context) {
						if len(ctx.Args()) > 0 {
							return
						}
						api := c.GetAPIClient(ctx)
						instance := c.GetInstance(ctx, nil)
						services, err := api.Services.List(&*instance.URL)
						if err != nil {
							fatal(err.Error())
						}
						for i := range services {
							fmt.Println(*services[i].Name)
						}
					},
				},
				{
					Name:  "scale",
					Usage: "scale up/down a service on an instance",
					Flags: []cli.Flag{
						cli.IntFlag{
							Name:  "replicas",
							Usage: "desired number of replicas",
						},
						cli.StringFlag{
							Name:  "instance",
							Value: "",
							Usage: "instance label",
						},
					},
					Action: c.cmd(c.stdCmd(servicesScaleCmd)),
					BashComplete: func(ctx *cli.Context) {
						if len(ctx.Args()) > 0 {
							return
						}
						api := c.GetAPIClient(ctx)
						instance := c.GetInstance(ctx, nil)
						services, err := api.Services.List(&*instance.URL)
						if err != nil {
							fatal(err.Error())
						}
						for i := range services {
							fmt.Println(*services[i].Name)
						}
					},
				},
				{
					Name:  "restart",
					Usage: "restart a service on a given instance",
					Flags: []cli.Flag{
						cli.StringFlag{
							Name:  "instance",
							Value: "",
							Usage: "instance label",
						},
					},
					Action: c.cmd(c.stdCmd(servicesRestartCmd)),
					BashComplete: func(ctx *cli.Context) {
						if len(ctx.Args()) > 0 {
							return
						}
						api := c.GetAPIClient(ctx)
						instance := c.GetInstance(ctx, nil)
						services, err := api.Services.List(&*instance.URL)
						if err != nil {
							fatal(err.Error())
						}
						for i := range services {
							fmt.Println(*services[i].Name)
						}
					},
				},
			},
		},
		{
			Name:  "run",
			Usage: "run a one-off process",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "instance",
					Value: "",
					Usage: "instance label",
				},
			},
			Action: c.cmd(c.stdCmd(runCmd)),
			BashComplete: func(ctx *cli.Context) {
				if len(ctx.Args()) > 0 {
					return
				}
				api := c.GetAPIClient(ctx)
				instance := c.GetInstance(ctx, nil)
				services, err := api.Services.List(&*instance.URL)
				if err != nil {
					fatal(err.Error())
				}
				for i := range services {
					fmt.Println(*services[i].Name)
				}
			},
		},
		{
			Name:  "deploy",
			Usage: "create a new release and deploy",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "instance",
					Value: "",
					Usage: "instance label",
				},
			},
			Action: c.cmd(c.stdCmd(deployCmd)),
		},
		{
			Name:  "hosts",
			Usage: "manage hosts for an instance",
			Action: c.cmd(func(c *CLI, ctx *cli.Context) {
				cli.ShowSubcommandHelp(ctx)
			}),
			Subcommands: []cli.Command{
				{
					Name:  "list",
					Usage: "List hosts for an instance",
					Flags: []cli.Flag{
						cli.StringFlag{
							Name:  "instance",
							Value: "",
							Usage: "instance label",
						},
					},
					Action: c.cmd(c.stdCmd(hostsListCmd)),
				},
				{
					Name:  "create",
					Usage: "Create a host for an instance",
					Flags: []cli.Flag{
						cli.StringFlag{
							Name:  "instance",
							Value: "",
							Usage: "instance label",
						},
					},
					Action: c.cmd(c.stdCmd(hostsCreateCmd)),
				},
				{
					Name:  "delete",
					Usage: "Delete a host from an instance",
					Flags: []cli.Flag{
						cli.StringFlag{
							Name:  "instance",
							Value: "",
							Usage: "instance label",
						},
					},
					Action: c.cmd(c.stdCmd(hostsDeleteCmd)),
				},
			},
		},
		{
			Name:  "scheduled-tasks",
			Usage: "manage scheduled tasks for an instance",
			Action: c.cmd(func(c *CLI, ctx *cli.Context) {
				cli.ShowSubcommandHelp(ctx)
			}),
			Subcommands: []cli.Command{
				{
					Name:  "list",
					Usage: "List scheduled tasks for an instance",
					Flags: []cli.Flag{
						cli.StringFlag{
							Name:  "instance",
							Value: "",
							Usage: "instance label",
						},
					},
					Action: c.cmd(c.stdCmd(scheduledTasksListCmd)),
				},
				{
					Name:  "create",
					Usage: "Create a scheduled task for an instance",
					Flags: []cli.Flag{
						cli.StringFlag{
							Name:  "instance",
							Value: "",
							Usage: "instance label",
						},
						cli.StringFlag{
							Name:  "name",
							Value: "",
							Usage: "scheduled task name",
						},
						cli.StringFlag{
							Name:  "timezone",
							Value: "UTC",
							Usage: "scheduled task timezone (default: UTC)",
						},
						cli.StringFlag{
							Name:  "schedule",
							Value: "",
							Usage: "scheduled task schedule (cron syntax)",
						},
					},
					Action: c.cmd(c.stdCmd(scheduledTasksCreateCmd)),
				},
				{
					Name:  "delete",
					Usage: "Delete a scheduled task from an instance",
					Flags: []cli.Flag{
						cli.StringFlag{
							Name:  "instance",
							Value: "",
							Usage: "instance label",
						},
					},
					Action: c.cmd(c.stdCmd(scheduledTasksDeleteCmd)),
				},
			},
		},
		{
			Name:   "open",
			Usage:  "open instance URL in browser",
			Action: c.cmd(c.stdCmd(openCmd)),
			BashComplete: func(ctx *cli.Context) {
				if len(ctx.Args()) > 0 {
					return
				}
				api := c.GetAPIClient(ctx)
				instance := c.GetInstance(ctx, nil)
				services, err := api.Services.List(&*instance.URL)
				if err != nil {
					fatal(err.Error())
				}
				for i := range services {
					if *services[i].Kind == "web" {
						fmt.Println(*services[i].Name)
					}
				}
			},
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "instance",
					Value: "",
					Usage: "instance label",
				},
			},
		},
		{
			Name:  "logs",
			Usage: "view logs for an instance or service",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "instance",
					Value: "",
					Usage: "instance label",
				},
				cli.IntFlag{
					Name:  "lines",
					Value: 20,
					Usage: "number of lines to query",
				},
			},
			Action: c.cmd(c.stdCmd(logsCmd)),
			BashComplete: func(ctx *cli.Context) {
				if len(ctx.Args()) > 0 {
					return
				}
				api := c.GetAPIClient(ctx)
				instance := c.GetInstance(ctx, nil)
				services, err := api.Services.List(&*instance.URL)
				if err != nil {
					fatal(err.Error())
				}
				for i := range services {
					fmt.Println(*services[i].Name)
				}
			},
		},
		{
			Name:  "metrics",
			Usage: "view metrics for a given service",
			Action: c.cmd(func(c *CLI, ctx *cli.Context) {
				api := c.GetAPIClient(ctx)
				site := c.GetSite(ctx)
				if len(ctx.Args()) != 1 {
					fatal("missing service")
				}
				parts := strings.Split(ctx.Args()[0], "/")
				instanceLabel := parts[0]
				serviceName := parts[1]
				instance, err := api.Instances.Get(*site.URL, instanceLabel)
				if err != nil {
					fatal(err.Error())
				}
				service, err := api.Services.Get(*instance.URL, serviceName)
				if err != nil {
					fatal(err.Error())
				}
				series, err := api.Metrics.List(*service.URL)
				if err != nil {
					fatal(err.Error())
				}
				for i := range series {
					s := series[i]
					fmt.Printf("%s = ", s.Name)
					for j := range s.Points {
						value := s.Points[j][2]
						switch *s.Name {
						case "filesystem/limit_bytes_gauge", "filesystem/usage_bytes_gauge", "memory/usage_bytes_gauge", "memory/working_set_bytes_gauge":
							fmt.Printf("%s ", bytefmt.ByteSize(uint64(value)))
							break
						default:
							fmt.Printf("%d ", value)
						}
					}
					fmt.Println("")
				}
			}),
		},
	}
	app.Run(os.Args)
}