当前位置: 首页>>代码示例>>Golang>>正文


Golang Context.Args方法代码示例

本文整理汇总了Golang中github.com/urfave/cli.Context.Args方法的典型用法代码示例。如果您正苦于以下问题:Golang Context.Args方法的具体用法?Golang Context.Args怎么用?Golang Context.Args使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在github.com/urfave/cli.Context的用法示例。


在下文中一共展示了Context.Args方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: NoteName

// NoteName returns name of note and error if note isnt present
func NoteName(c *cli.Context) (n string, err error) {
	if c.Args().Present() != true {
		return "", errors.New("Missing argument: name")
	}

	return strings.Join(c.Args(), " "), nil
}
开发者ID:gummiboll,项目名称:forgetful,代码行数:8,代码来源:commands.go

示例2: Init

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
}
开发者ID:kawamuray,项目名称:prometheus-json-exporter,代码行数:34,代码来源:init.go

示例3: connectPeer

func connectPeer(ctx *cli.Context) error {
	ctxb := context.Background()
	client := getClient(ctx)

	targetAddress := ctx.Args().Get(0)
	splitAddr := strings.Split(targetAddress, "@")
	if len(splitAddr) != 2 {
		return fmt.Errorf("target address expected in format: " +
			"[email protected]:port")
	}

	addr := &lnrpc.LightningAddress{
		Pubkey: splitAddr[0],
		Host:   splitAddr[1],
	}
	req := &lnrpc.ConnectPeerRequest{addr}

	lnid, err := client.ConnectPeer(ctxb, req)
	if err != nil {
		return err
	}

	printRespJson(lnid)
	return nil
}
开发者ID:lightningnetwork,项目名称:lnd,代码行数:25,代码来源:commands.go

示例4: CmdUntaint

func CmdUntaint(c *cli.Context) error {
	operation := initialize(c, "untaint")
	operation.extraArgs = strings.Join(c.Args()[1:], " ")
	run(operation)
	resync(operation)
	return nil
}
开发者ID:nadnerb,项目名称:terraform_exec,代码行数:7,代码来源:terraform_exec.go

示例5: Generate

//Generate generates a migration on the migrations folder
func Generate(c *cli.Context) {
	setupTestingEnv()
	base := os.Getenv("TRANS_TESTING_FOLDER")

	name := "migration"
	if c.App != nil && len(c.Args()) > 0 {
		name = c.Args().First()
	}

	name = snaker.CamelToSnake(name)
	identifier := time.Now().UnixNano()

	migration := MigrationData{
		Identifier: identifier,
		Name:       name,
	}

	buff := bytes.NewBufferString("")
	tmpl, _ := template.New("migration").Parse(utils.MigrationTemplate)
	_ = tmpl.Execute(buff, migration)

	fileName := strconv.FormatInt(identifier, 10) + "_" + name + ".go"
	path := filepath.Join(base, "db", "migrations", fileName)

	err := ioutil.WriteFile(path, buff.Bytes(), generatedFilePermissions)
	if err != nil {
		log.Println(err)
		log.Println("| Could not write migration file, please check db/migrations folder exists")
	}
}
开发者ID:wawandco,项目名称:transporter,代码行数:31,代码来源:generate.go

示例6: execProcess

func execProcess(context *cli.Context) (int, error) {
	container, err := getContainer(context)
	if err != nil {
		return -1, err
	}
	path := context.String("process")
	if path == "" && len(context.Args()) == 1 {
		return -1, fmt.Errorf("process args cannot be empty")
	}
	detach := context.Bool("detach")
	state, err := container.State()
	if err != nil {
		return -1, err
	}
	bundle := utils.SearchLabels(state.Config.Labels, "bundle")
	p, err := getProcess(context, bundle)
	if err != nil {
		return -1, err
	}
	r := &runner{
		enableSubreaper: false,
		shouldDestroy:   false,
		container:       container,
		console:         context.String("console"),
		detach:          detach,
		pidFile:         context.String("pid-file"),
	}
	return r.run(p)
}
开发者ID:x1022as,项目名称:runc,代码行数:29,代码来源:exec.go

示例7: show

func (cmd *CatalogShow) show(c *cli.Context) error {
	if len(c.Args()) != 2 {
		return errors.New(c.App.Name + " " + showCommandName + catalogItemTypesUsage + " ITEM[:VERSION]")
	}
	catalogType, err := GetCatalogType(c)
	if err != nil {
		return err
	}
	item := c.Args().Get(1)
	var version string
	if strings.Contains(item, ":") {
		itemVersion := strings.Split(item, ":")
		item = itemVersion[0]
		version = itemVersion[1]
	}
	switch catalogType {
	case ApplicationsItemType:
		return cmd.showCatalogApplication(c, item, version)
	case EntitiesItemType:
		return cmd.showCatalogEntity(c, item, version)
	case LocationsItemType:
		return cmd.showCatalogLocation(c, item, version)
	case PoliciesItemType:
		return cmd.showPolicy(c, item, version)
	}
	return errors.New("Unrecognised argument")
}
开发者ID:m4rkmckenna,项目名称:brooklyn-client,代码行数:27,代码来源:catalog-show.go

示例8: ProjectDelete

// ProjectDelete deletes services.
func ProjectDelete(p project.APIProject, c *cli.Context) error {
	options := options.Delete{
		RemoveVolume: c.Bool("v"),
	}
	if !c.Bool("force") {
		stoppedContainers, err := p.Containers(context.Background(), project.Filter{
			State: project.Stopped,
		}, c.Args()...)
		if err != nil {
			return cli.NewExitError(err.Error(), 1)
		}
		if len(stoppedContainers) == 0 {
			fmt.Println("No stopped containers")
			return nil
		}
		fmt.Printf("Going to remove %v\nAre you sure? [yN]\n", strings.Join(stoppedContainers, ", "))
		var answer string
		_, err = fmt.Scanln(&answer)
		if err != nil {
			return cli.NewExitError(err.Error(), 1)
		}
		if answer != "y" && answer != "Y" {
			return nil
		}
	}
	err := p.Delete(context.Background(), options, c.Args()...)
	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}
	return nil
}
开发者ID:vdemeester,项目名称:libcompose,代码行数:32,代码来源:app.go

示例9: servicesCreateCmd

func servicesCreateCmd(c *CLI, ctx *cli.Context) {
	usage := func(msg string) {
		fmt.Printf("Usage: %s services create [--name,--version,--instance] <service-kind>\n", c.Name)
		fatal(msg)
	}
	if len(ctx.Args()) == 0 {
		usage("too few arguments")
	}
	api := c.GetAPIClient(ctx)
	instance := c.GetInstance(ctx, nil)
	name := ctx.String("name")
	service := gondor.Service{
		Instance: instance.URL,
		Name:     &name,
		Kind:     &ctx.Args()[0],
	}
	if ctx.String("version") != "" {
		version := ctx.String("version")
		service.Version = &version
	}
	if err := api.Services.Create(&service); err != nil {
		fatal(err.Error())
	}
	success(fmt.Sprintf("%s service has been created.", *service.Kind))
}
开发者ID:eldarion-gondor,项目名称:cli,代码行数:25,代码来源:services.go

示例10: cmdSearch

func cmdSearch(c *cli.Context) error {
	conf, err := config.Open(c.GlobalString("config"))
	if err != nil {
		Logger.Fatalf("Cannot load configuration: %v", err)
		return nil
	}

	needle := c.Args()[0]

	found := []*config.Host{}
	for _, host := range conf.Hosts.SortedList() {
		if host.Matches(needle) {
			found = append(found, host)
		}
	}

	if len(found) == 0 {
		fmt.Println("no results found.")
		return nil
	}

	fmt.Printf("Listing results for %s:\n", needle)
	for _, host := range found {
		fmt.Printf("    %s -> %s\n", host.Name(), host.Prototype())
	}

	return nil
}
开发者ID:moul,项目名称:advanced-ssh-config,代码行数:28,代码来源:search.go

示例11: execApplyCommand

// Executes the "apply" command
func execApplyCommand(c *cli.Context) error {
	if len(c.Args()) < 1 {
		return cli.NewExitError(errNoModuleName.Error(), 64)
	}

	L := lua.NewState()
	defer L.Close()
	config := &catalog.Config{
		Module:   c.Args()[0],
		DryRun:   c.Bool("dry-run"),
		Logger:   resource.DefaultLogger,
		SiteRepo: c.String("siterepo"),
		L:        L,
	}

	katalog := catalog.New(config)
	if err := katalog.Load(); err != nil {
		if err != nil {
			return cli.NewExitError(err.Error(), 1)
		}
	}

	if err := katalog.Run(); err != nil {
		return cli.NewExitError(err.Error(), 1)
	}

	return nil
}
开发者ID:ycaille,项目名称:gru,代码行数:29,代码来源:apply.go

示例12: commandFormatAction

// the format action is similar to the gofmt command.
// it can be used to format the source of a fzp file.
func commandFormatAction(c *cli.Context) error {
	tmpArgs := c.Args()
	if len(tmpArgs) == 0 {
		fmt.Println("missing source to format. try run")
		fmt.Println("  fzp format part.fzp")
		os.Exit(127)
	}

	source := tmpArgs[0]

	formatDirHandler := func() {
		err := formatFile(source, c.Bool("write"), c.Bool("diff"))
		if err != nil {
			fmt.Println("Error", err)
			os.Exit(127)
		}
	}

	formatFileHandler := func() {
		err := formatDir(source, c.Bool("write"), c.Bool("diff"))
		if err != nil {
			fmt.Println("Error", err)
			os.Exit(127)
		}
	}

	dataHandler(source, formatFileHandler, formatDirHandler)
	return nil
}
开发者ID:fritzing,项目名称:fzp,代码行数:31,代码来源:command-format.go

示例13: actionMemberList

func actionMemberList(c *cli.Context) error {
	if len(c.Args()) != 0 {
		fmt.Fprintln(os.Stderr, "No arguments accepted")
		os.Exit(1)
	}
	mAPI := mustNewMembersAPI(c)
	ctx, cancel := contextWithTotalTimeout(c)
	defer cancel()

	members, err := mAPI.List(ctx)
	if err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(1)
	}
	leader, err := mAPI.Leader(ctx)
	if err != nil {
		fmt.Fprintln(os.Stderr, "Failed to get leader: ", err)
		os.Exit(1)
	}

	for _, m := range members {
		isLeader := false
		if m.ID == leader.ID {
			isLeader = true
		}
		if len(m.Name) == 0 {
			fmt.Printf("%s[unstarted]: peerURLs=%s\n", m.ID, strings.Join(m.PeerURLs, ","))
		} else {
			fmt.Printf("%s: name=%s peerURLs=%s clientURLs=%s isLeader=%v\n", m.ID, m.Name, strings.Join(m.PeerURLs, ","), strings.Join(m.ClientURLs, ","), isLeader)
		}
	}

	return nil
}
开发者ID:CliffYuan,项目名称:etcd,代码行数:34,代码来源:member_commands.go

示例14: run

func run(c *cli.Context) error {
	args := c.Args()
	if len(args) < 3 {
		return errors.New("a directory, log file and command is required")
	}
	workingDir := os.ExpandEnv(args[0])
	logFile := os.ExpandEnv(args[1])
	fullCommand := os.ExpandEnv(args[2])

	command, cmdArgs, err := parseCommand(fullCommand)
	if err != nil {
		return errors.WithStack(err)
	}

	log, err := os.Create(logFile)
	if err != nil {
		return errors.WithStack(err)
	}

	cmd := exec.Command(command, cmdArgs...)
	fmt.Println(cmd.Path)
	cmd.Dir = workingDir
	cmd.Stdout = log
	cmd.Stderr = log
	return cmd.Run()
}
开发者ID:yext,项目名称:edward,代码行数:26,代码来源:runner.go

示例15: deleteFile

//
// deleteFile removes a file from the bucket
//
func deleteFile(o *formatter, cx *cli.Context, cmd *cliCommand) error {
	if len(cx.Args()) <= 0 {
		return fmt.Errorf("you have not specified any files to delete")
	}

	bucket := cx.String("bucket")
	// step: ensure the bucket exists
	if found, err := cmd.hasBucket(bucket); err != nil {
		return err
	} else if !found {
		return fmt.Errorf("the bucket: %s does not exist", bucket)
	}

	for _, path := range getPaths(cx) {
		if err := cmd.removeFile(bucket, path); err != nil {
			o.fields(map[string]interface{}{
				"action": "delete",
				"bucket": bucket,
				"path":   path,
				"error":  err.Error(),
			}).log("failed to remove s3://%s/%s, error: %s", bucket, path, err)
			continue
		}
		o.fields(map[string]interface{}{
			"action": "delete",
			"bucket": bucket,
			"path":   path,
		}).log("successfully deleted the file s3://%s/%s\n", bucket, path)
	}

	return nil
}
开发者ID:UKHomeOffice,项目名称:s3secrets,代码行数:35,代码来源:delete.go


注:本文中的github.com/urfave/cli.Context.Args方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。