本文整理汇总了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.")
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}