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


Golang Context.String方法代码示例

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


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

示例1: keypairsCreateCmd

func keypairsCreateCmd(c *CLI, ctx *cli.Context) {
	usage := func(msg string) {
		fmt.Printf("Usage: %s keypairs create --name=<keypair-name> <private-key-path> <certificate-path>\n", c.Name)
		fatal(msg)
	}
	if len(ctx.Args()) < 2 {
		usage("too few arguments")
	}
	if !ctx.IsSet("name") || ctx.String("name") == "" {
		usage("--name is required")
	}
	api := c.GetAPIClient(ctx)
	resourceGroup := c.GetResourceGroup(ctx)
	name := ctx.String("name")
	privateKeyPath := ctx.Args()[0]
	certPath := ctx.Args()[1]
	privateKey, err := ioutil.ReadFile(privateKeyPath)
	if err != nil {
		fatal(err.Error())
	}
	cert, err := ioutil.ReadFile(certPath)
	if err != nil {
		fatal(err.Error())
	}
	keypair := gondor.KeyPair{
		ResourceGroup: resourceGroup.URL,
		Name:          &name,
		Key:           privateKey,
		Certificate:   cert,
	}
	if err := api.KeyPairs.Create(&keypair); err != nil {
		fatal(err.Error())
	}
	success("keypair created.")
}
开发者ID:eldarion-gondor,项目名称:cli,代码行数:35,代码来源:keypairs.go

示例2: cmdTripDelete

func cmdTripDelete(c *cli.Context) error {
	// Get loggers
	printUserMsg, printError := getLoggers()

	// Check obligatory flags
	if c.String("file") == NotSetStringValue {
		printError.Fatalln(errMissingFileFlag)
	}
	id := c.Int("id")
	if id == NotSetIntValue {
		printError.Fatalln(errMissingIdFlag)
	}

	// Open data file
	f := gsqlitehandler.New(c.String("file"), dataFileProperties)
	if err := f.Open(); err != nil {
		printError.Fatalln(err)
	}
	defer f.Close()

	// Delete bicycle type
	sqlDeleteTrip := fmt.Sprintf("DELETE FROM trips WHERE id=%d;", id)
	r, err := f.Handler.Exec(sqlDeleteTrip)
	if err != nil {
		printError.Fatalln(errWritingToFile)
	}
	if i, _ := r.RowsAffected(); i == 0 {
		printError.Fatalln(errNoTripWithID)
	}

	// Show summary
	printUserMsg.Printf("deleted tirp with id = %d\n", id)

	return nil
}
开发者ID:zbroju,项目名称:biclog,代码行数:35,代码来源:commands.go

示例3: 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

示例4: initRobotAccount

// initRobotAccount creates a GCP robot account for this connector.
func initRobotAccount(context *cli.Context, userClient *http.Client) (string, string) {
	params := url.Values{}
	params.Set("oauth_client_id", context.String("gcp-oauth-client-id"))

	url := fmt.Sprintf("%s%s?%s", lib.DefaultConfig.GCPBaseURL, "createrobot", params.Encode())
	response, err := userClient.Get(url)
	if err != nil {
		log.Fatalln(err)
	}
	if response.StatusCode != http.StatusOK {
		log.Fatalf("Failed to initialize robot account: %s\n", response.Status)
	}

	var robotInit struct {
		Success  bool   `json:"success"`
		Message  string `json:"message"`
		XMPPJID  string `json:"xmpp_jid"`
		AuthCode string `json:"authorization_code"`
	}

	if err = json.NewDecoder(response.Body).Decode(&robotInit); err != nil {
		log.Fatalln(err)
	}
	if !robotInit.Success {
		log.Fatalf("Failed to initialize robot account: %s\n", robotInit.Message)
	}

	return robotInit.XMPPJID, robotInit.AuthCode
}
开发者ID:jacobmarble,项目名称:cloud-print-connector,代码行数:30,代码来源:init.go

示例5: execLastseenCommand

// Executes the "lastseen" command
func execLastseenCommand(c *cli.Context) error {
	client := newEtcdMinionClientFromFlags(c)

	cFlag := c.String("with-classifier")
	minions, err := parseClassifierPattern(client, cFlag)

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

	table := uitable.New()
	table.MaxColWidth = 80
	table.AddRow("MINION", "LASTSEEN")
	for _, minion := range minions {
		lastseen, err := client.MinionLastseen(minion)
		if err != nil {
			return cli.NewExitError(err.Error(), 1)
		}

		table.AddRow(minion, time.Unix(lastseen, 0))
	}

	fmt.Println(table)

	return nil
}
开发者ID:dnaeon,项目名称:gru,代码行数:27,代码来源:lastseen.go

示例6: ProjectKill

// ProjectKill forces stop service containers.
func ProjectKill(p project.APIProject, c *cli.Context) error {
	err := p.Kill(context.Background(), c.String("signal"), c.Args()...)
	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}
	return nil
}
开发者ID:vdemeester,项目名称:rancher-compose,代码行数:8,代码来源:app.go

示例7: stepList

func stepList(c *cli.Context) error {
	// Input validation
	stepLibURIs := []string{}
	stepLibURI := c.String(CollectionKey)
	if stepLibURI == "" {
		stepLibURIs = stepman.GetAllStepCollectionPath()
	} else {
		stepLibURIs = []string{stepLibURI}
	}

	format := c.String(FormatKey)
	if format == "" {
		format = OutputFormatRaw
	} else if !(format == OutputFormatRaw || format == OutputFormatJSON) {
		log.Fatalf("Invalid format: %s", format)
	}

	for _, URI := range stepLibURIs {
		if err := listSteps(URI, format); err != nil {
			log.Errorf("Failed to list steps in StepLib (%s), err: %s", URI, err)
		}
	}

	return nil
}
开发者ID:bitrise-io,项目名称:stepman,代码行数:25,代码来源:step_list.go

示例8: 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

示例9: update

func update(c *cli.Context) error {
	collectionURIs := []string{}

	// StepSpec collection path
	collectionURI := c.String(CollectionKey)
	if collectionURI == "" {
		log.Info("No StepLib specified, update all...")
		collectionURIs = stepman.GetAllStepCollectionPath()
	} else {
		collectionURIs = []string{collectionURI}
	}

	if len(collectionURIs) == 0 {
		log.Info("No local StepLib found, nothing to update...")
	}

	for _, URI := range collectionURIs {
		log.Infof("Update StepLib (%s)...", URI)
		if _, err := updateCollection(URI); err != nil {
			return fmt.Errorf("Failed to update StepLib (%s), error: %s", URI, err)
		}
	}

	return nil
}
开发者ID:godrei,项目名称:stepman,代码行数:25,代码来源:update.go

示例10: commandEncodeAction

func commandEncodeAction(c *cli.Context) error {
	flagInput := c.String("input")
	flagOutput := c.String("output")
	fmt.Println("in", flagInput, "out", flagOutput)

	if flagInput == "" {
		fmt.Println("missing -input flag")
		os.Exit(1)
	}
	if flagOutput == "" {
		fmt.Println("missing -output flag")
		os.Exit(1)
	}

	encodeDirHandler := func() {
		if err := encodeDir(flagInput, flagOutput); err != nil {
			fmt.Println("Error", err)
			os.Exit(127)
		}
	}

	encodeFileHandler := func() {
		if err := encodeFile(flagInput, flagOutput); err != nil {
			fmt.Println("Error", err)
			os.Exit(127)
		}
	}

	dataHandler(flagInput, encodeDirHandler, encodeFileHandler)
	return nil
}
开发者ID:fritzing,项目名称:fzp,代码行数:31,代码来源:command-encode.go

示例11: updateGOCDHost

func updateGOCDHost(c *cli.Context, config *config.Config) (gocdServer *gocd.Server) {
	if c.String("host") != "" {
		config.SetGoCDHost(c.String("host"))
	}
	gocdServer = gocd.NewServerConfig(config.GOCDHost, config.GOCDPort, config.GOCDUser, config.GOCDPassword, config.GOCDTimeout)
	return
}
开发者ID:cfpb,项目名称:rhobot,代码行数:7,代码来源:rhobot.go

示例12: Apply

// REQUEST: curl http://169.254.169.254/latest/meta-data/iam/security-credentials/ROLE
func (a *AwsInternalProvider) Apply(c *cli.Context) error {

	role := c.String("aws-role")
	if len(role) == 0 {
		return errors.New("flag aws-role not set")
	}

	resp, err := http.Get(fmt.Sprintf("%s%s", a.ServerAddress, role))
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	var responseJson map[string]interface{}
	fmt.Println(body)
	responseBytes := []byte(body)

	if err := json.Unmarshal(responseBytes, &responseJson); err != nil {
		return err
	}

	SetEnvironmentVariable("AWS_ACCESS_KEY_ID", responseJson["AccessKeyId"])
	SetEnvironmentVariable("AWS_SECRET_ACCESS_KEY", responseJson["SecretAccessKey"])
	SetEnvironmentVariable("AWS_SESSION_TOKEN", responseJson["Token"])

	return nil
}
开发者ID:nadnerb,项目名称:terraform_exec,代码行数:31,代码来源:aws_internal.go

示例13: getChangeAddress

func getChangeAddress(wltFile string, a string, c *gcli.Context) (string, error) {
	chgAddr := c.String("c")
	for {
		if chgAddr == "" {
			// get the default wallet's coin base address
			if a != "" {
				// use the from address as change address
				chgAddr = a
				break
			}

			if wltFile != "" {
				wlt, err := wallet.Load(wltFile)
				if err != nil {
					return "", err
				}
				if len(wlt.Entries) > 0 {
					chgAddr = wlt.Entries[0].Address.String()
					break
				}
				return "", errors.New("no change address was found")
			}
			return "", errors.New("both wallet file, from address and change address are empty")
		}
		break
	}

	// validate the address
	_, err := cipher.DecodeBase58Address(chgAddr)
	if err != nil {
		return "", fmt.Errorf("invalid change address: %s", chgAddr)
	}

	return chgAddr, nil
}
开发者ID:skycoin,项目名称:skycoin,代码行数:35,代码来源:create_rawtx.go

示例14: seccompSet

func seccompSet(context *cli.Context, seccompFlag string, g *generate.Generator) error {
	flagInput := context.String("seccomp-" + seccompFlag)
	flagArgs := strings.Split(flagInput, ",")
	setSyscallArgsSlice := []seccomp.SyscallOpts{}
	for _, flagArg := range flagArgs {
		comparisonArgs := strings.Split(flagArg, ":")
		if len(comparisonArgs) == 5 {
			setSyscallArgs := seccomp.SyscallOpts{
				Action:   seccompFlag,
				Syscall:  comparisonArgs[0],
				Index:    comparisonArgs[1],
				Value:    comparisonArgs[2],
				ValueTwo: comparisonArgs[3],
				Operator: comparisonArgs[4],
			}
			setSyscallArgsSlice = append(setSyscallArgsSlice, setSyscallArgs)
		} else if len(comparisonArgs) == 1 {
			setSyscallArgs := seccomp.SyscallOpts{
				Action:  seccompFlag,
				Syscall: comparisonArgs[0],
			}
			setSyscallArgsSlice = append(setSyscallArgsSlice, setSyscallArgs)
		} else {
			return fmt.Errorf("invalid syscall argument formatting %v", comparisonArgs)
		}

		for _, r := range setSyscallArgsSlice {
			err := g.SetSyscallAction(r)
			if err != nil {
				return err
			}
		}
	}
	return nil
}
开发者ID:hqhq,项目名称:ocitools,代码行数:35,代码来源:generate.go

示例15: cmdTypeAdd

func cmdTypeAdd(c *cli.Context) error {
	// Get loggers
	printUserMsg, printError := getLoggers()

	// Check obligatory flags (file, name)
	if c.String("file") == NotSetStringValue {
		printError.Fatalln(errMissingFileFlag)

	}
	if c.String("type") == NotSetStringValue {
		printError.Fatalln(errMissingTypeFlag)
	}

	// Open data file
	f := gsqlitehandler.New(c.String("file"), dataFileProperties)
	if err := f.Open(); err != nil {
		printError.Fatalln(err)
	}
	defer f.Close()

	// Add new type
	sqlAddType := fmt.Sprintf("INSERT INTO bicycle_types VALUES (NULL, '%s');", c.String("type"))
	if _, err := f.Handler.Exec(sqlAddType); err != nil {
		printError.Fatalln(errWritingToFile)
	}

	// Show summary
	printUserMsg.Printf("added new bicycle type: %s\n", c.String("type"))

	return nil
}
开发者ID:zbroju,项目名称:biclog,代码行数:31,代码来源:commands.go


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