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