本文整理汇总了Golang中github.com/urfave/cli.Context.Int方法的典型用法代码示例。如果您正苦于以下问题:Golang Context.Int方法的具体用法?Golang Context.Int怎么用?Golang Context.Int使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/urfave/cli.Context
的用法示例。
在下文中一共展示了Context.Int方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Validate
func Validate(c *cli.Context, startTime time.Time) {
gossConfig := getGossConfig(c)
sys := system.New(c)
outputer := getOutputer(c)
sleep := c.Duration("sleep")
retryTimeout := c.Duration("retry-timeout")
i := 1
for {
iStartTime := time.Now()
out := validate(sys, gossConfig, c.Int("max-concurrent"))
exitCode := outputer.Output(os.Stdout, out, iStartTime)
if retryTimeout == 0 || exitCode == 0 {
os.Exit(exitCode)
}
elapsed := time.Since(startTime)
if elapsed+sleep > retryTimeout {
color.Red("\nERROR: Timeout of %s reached before tests entered a passing state", retryTimeout)
os.Exit(3)
}
color.Red("Retrying in %s (elapsed/timeout time: %.3fs/%s)\n\n\n", sleep, elapsed.Seconds(), retryTimeout)
// Reset cache
sys = system.New(c)
time.Sleep(sleep)
i++
fmt.Printf("Attempt #%d:\n", i)
}
}
示例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: ProjectStop
// ProjectStop stops all services.
func ProjectStop(p project.APIProject, c *cli.Context) error {
err := p.Stop(context.Background(), c.Int("timeout"), c.Args()...)
if err != nil {
return cli.NewExitError(err.Error(), 1)
}
return nil
}
示例4: main
func (exp *exporter) main(c *cli.Context) {
setupLogging(c)
registry := newRegistry()
collector, err := exp.Init(c, registry)
if err != nil {
log.Fatal(err)
}
if exp.Tick {
collector.Collect(registry)
interval := c.Int("interval")
go func() {
for _ = range time.Tick(time.Duration(interval) * time.Second) {
if exp.ResetOnTick {
registry.Reset()
}
collector.Collect(registry)
}
}()
}
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
w.Header().Add("Location", exp.MetricsPath)
w.WriteHeader(http.StatusFound)
})
http.Handle(exp.MetricsPath, prometheus.Handler())
if err := http.ListenAndServe(fmt.Sprintf(":%d", c.Int("port")), nil); err != nil {
log.Fatal(err)
}
}
示例5: createCloudConfig
// createCloudConfig creates a config object that supports cloud and (optionally) local mode.
func createCloudConfig(context *cli.Context, xmppJID, robotRefreshToken, userRefreshToken, shareScope, proxyName string, localEnable bool) *lib.Config {
return &lib.Config{
LocalPrintingEnable: localEnable,
CloudPrintingEnable: true,
XMPPJID: xmppJID,
RobotRefreshToken: robotRefreshToken,
UserRefreshToken: userRefreshToken,
ShareScope: shareScope,
ProxyName: proxyName,
XMPPServer: lib.DefaultConfig.XMPPServer,
XMPPPort: uint16(context.Int("xmpp-port")),
XMPPPingTimeout: context.String("xmpp-ping-timeout"),
XMPPPingInterval: context.String("xmpp-ping-interval"),
GCPBaseURL: lib.DefaultConfig.GCPBaseURL,
GCPOAuthClientID: context.String("gcp-oauth-client-id"),
GCPOAuthClientSecret: context.String("gcp-oauth-client-secret"),
GCPOAuthAuthURL: lib.DefaultConfig.GCPOAuthAuthURL,
GCPOAuthTokenURL: lib.DefaultConfig.GCPOAuthTokenURL,
GCPMaxConcurrentDownloads: uint(context.Int("gcp-max-concurrent-downloads")),
NativeJobQueueSize: uint(context.Int("native-job-queue-size")),
NativePrinterPollInterval: context.String("native-printer-poll-interval"),
CUPSJobFullUsername: lib.PointerToBool(context.Bool("cups-job-full-username")),
PrefixJobIDToJobTitle: lib.PointerToBool(context.Bool("prefix-job-id-to-job-title")),
DisplayNamePrefix: context.String("display-name-prefix"),
PrinterBlacklist: lib.DefaultConfig.PrinterBlacklist,
PrinterWhitelist: lib.DefaultConfig.PrinterWhitelist,
LogLevel: context.String("log-level"),
LocalPortLow: uint16(context.Int("local-port-low")),
LocalPortHigh: uint16(context.Int("local-port-high")),
}
}
示例6: mkCommandFunc
// mkCommandFunc executes the "mk" command.
func mkCommandFunc(c *cli.Context, ki client.KeysAPI) {
if len(c.Args()) == 0 {
handleError(c, ExitBadArgs, errors.New("key required"))
}
key := c.Args()[0]
value, err := argOrStdin(c.Args(), os.Stdin, 1)
if err != nil {
handleError(c, ExitBadArgs, errors.New("value required"))
}
ttl := c.Int("ttl")
inorder := c.Bool("in-order")
var resp *client.Response
ctx, cancel := contextWithTotalTimeout(c)
if !inorder {
// Since PrevNoExist means that the Node must not exist previously,
// this Set method always creates a new key. Therefore, mk command
// succeeds only if the key did not previously exist, and the command
// prevents one from overwriting values accidentally.
resp, err = ki.Set(ctx, key, value, &client.SetOptions{TTL: time.Duration(ttl) * time.Second, PrevExist: client.PrevNoExist})
} else {
// If in-order flag is specified then create an inorder key under
// the directory identified by the key argument.
resp, err = ki.CreateInOrder(ctx, key, value, &client.CreateInOrderOptions{TTL: time.Duration(ttl) * time.Second})
}
cancel()
if err != nil {
handleError(c, ExitServerError, err)
}
printResponseKey(resp, c.GlobalString("output"))
}
示例7: addInvoice
func addInvoice(ctx *cli.Context) error {
client := getClient(ctx)
preimage, err := hex.DecodeString(ctx.String("preimage"))
if err != nil {
return fmt.Errorf("unable to parse preimage: %v", err)
}
receipt, err := hex.DecodeString(ctx.String("receipt"))
if err != nil {
return fmt.Errorf("unable to parse receipt: %v", err)
}
invoice := &lnrpc.Invoice{
Memo: ctx.String("memo"),
Receipt: receipt,
RPreimage: preimage,
Value: int64(ctx.Int("value")),
}
resp, err := client.AddInvoice(context.Background(), invoice)
if err != nil {
return err
}
printRespJson(struct {
RHash string `json:"r_hash"`
}{
RHash: hex.EncodeToString(resp.RHash),
})
return nil
}
示例8: updateGCPPrinter
// updateGCPPrinter updates settings for a GCP printer.
func updateGCPPrinter(context *cli.Context) {
config := getConfig(context)
gcpConn := getGCP(config)
var diff lib.PrinterDiff
diff.Printer = lib.Printer{GCPID: context.String("printer-id")}
if context.Bool("enable-quota") {
diff.Printer.QuotaEnabled = true
diff.QuotaEnabledChanged = true
} else if context.Bool("disable-quota") {
diff.Printer.QuotaEnabled = false
diff.QuotaEnabledChanged = true
}
if context.Int("daily-quota") > 0 {
diff.Printer.DailyQuota = context.Int("daily-quota")
diff.DailyQuotaChanged = true
}
err := gcpConn.Update(&diff)
if err != nil {
fmt.Printf("Failed to update GCP printer %s: %s", context.String("printer-id"), err)
} else {
fmt.Printf("Updated GCP printer %s", context.String("printer-id"))
}
}
示例9: run
func run(c *cli.Context) error {
if c.String("env-file") != "" {
_ = godotenv.Load(c.String("env-file"))
}
plugin := Plugin{
Repo: Repo{
Owner: c.String("repo.owner"),
Name: c.String("repo.name"),
},
Commit: Commit{
Sha: c.String("commit.sha"),
Ref: c.String("commit.ref"),
Branch: c.String("commit.branch"),
Author: c.String("commit.author"),
Link: c.String("commit.link"),
},
Build: Build{
Number: c.Int("build.number"),
Event: c.String("build.event"),
Status: c.String("build.status"),
Deploy: c.String("build.deploy"),
Link: c.String("build.link"),
},
Config: Config{
Webhook: c.StringSlice("webhook"),
},
}
return plugin.Exec()
}
示例10: FromContext
func (req *TnDestroy) FromContext(c *cli.Context) error {
fmt.Println("In TnDestroy")
Id := c.Int("id")
if Id < 0 {
return fmt.Errorf("invalid id")
} else {
req.Id = uint32(Id)
}
return nil
}
示例11: closeChannel
func closeChannel(ctx *cli.Context) error {
ctxb := context.Background()
client := getClient(ctx)
txid, err := wire.NewShaHashFromStr(ctx.String("funding_txid"))
if err != nil {
return err
}
// TODO(roasbeef): implement time deadline within server
req := &lnrpc.CloseChannelRequest{
ChannelPoint: &lnrpc.ChannelPoint{
FundingTxid: txid[:],
OutputIndex: uint32(ctx.Int("output_index")),
},
Force: ctx.Bool("force"),
}
stream, err := client.CloseChannel(ctxb, req)
if err != nil {
return err
}
if !ctx.Bool("block") {
return nil
}
for {
resp, err := stream.Recv()
if err == io.EOF {
return nil
} else if err != nil {
return err
}
switch update := resp.Update.(type) {
case *lnrpc.CloseStatusUpdate_ChanClose:
closingHash := update.ChanClose.ClosingTxid
txid, err := wire.NewShaHash(closingHash)
if err != nil {
return err
}
printRespJson(struct {
ClosingTXID string `json:"closing_txid"`
}{
ClosingTXID: txid.String(),
})
}
}
return nil
}
示例12: run
func run(c *cli.Context) error {
if c.String("env-file") != "" {
_ = godotenv.Load(c.String("env-file"))
}
plugin := Plugin{
Repo: Repo{
FullName: c.String("repo.fullname"),
Owner: c.String("repo.owner"),
Name: c.String("repo.name"),
Link: c.String("repo.link"),
},
Build: Build{
Commit: c.String("commit.sha"),
Branch: c.String("commit.branch"),
Ref: c.String("commit.ref"),
Link: c.String("commit.link"),
Message: c.String("commit.message"),
Author: c.String("commit.author.name"),
Email: c.String("commit.author.email"),
Number: c.Int("build.number"),
Status: c.String("build.status"),
Event: c.String("build.event"),
Deploy: c.String("build.deploy"),
BuildLink: c.String("build.link"),
},
BuildLast: Build{
Number: c.Int("prev.build.number"),
Status: c.String("prev.build.status"),
Commit: c.String("prev.commit.sha"),
},
Config: Config{
Token: c.String("token"),
Channel: c.String("channel"),
Mapping: c.String("mapping"),
Success: MessageOptions{
Username: c.String("success_username"),
Icon: c.String("success_icon"),
Template: c.String("success_template"),
ImageAttachments: c.StringSlice("success_image_attachments"),
},
Failure: MessageOptions{
Username: c.String("failure_username"),
Icon: c.String("failure_icon"),
Template: c.String("failure_template"),
ImageAttachments: c.StringSlice("failure_image_attachments"),
},
},
}
return plugin.Exec()
}
示例13: logsCmd
func logsCmd(c *CLI, ctx *cli.Context) {
var err error
var instance *gondor.Instance
var service *gondor.Service
api := c.GetAPIClient(ctx)
instance = c.GetInstance(ctx, nil)
if len(ctx.Args()) == 1 {
service, err = api.Services.Get(*instance.URL, ctx.Args()[0])
if err != nil {
fatal(err.Error())
}
}
var records []*gondor.LogRecord
if instance != nil && service == nil {
records, err = api.Logs.ListByInstance(*instance.URL, ctx.Int("lines"))
if err != nil {
fatal(err.Error())
}
} else if service != nil {
records, err = api.Logs.ListByService(*service.URL, ctx.Int("lines"))
if err != nil {
fatal(err.Error())
}
}
var color func(string) string
for i := range records {
record := records[i]
switch *record.Stream {
case "stdout":
color = blue
break
case "stderr":
color = red
break
}
fmt.Printf(
"%s %s\n",
color(fmt.Sprintf(
"[%s; %s]",
*record.Timestamp,
*record.Tag,
)),
strings.TrimSpace(*record.Message),
)
}
}
示例14: updatedirCommandFunc
// updatedirCommandFunc executes the "updatedir" command.
func updatedirCommandFunc(c *cli.Context, ki client.KeysAPI) {
if len(c.Args()) == 0 {
handleError(ExitBadArgs, errors.New("key required"))
}
key := c.Args()[0]
ttl := c.Int("ttl")
ctx, cancel := contextWithTotalTimeout(c)
_, err := ki.Set(ctx, key, "", &client.SetOptions{TTL: time.Duration(ttl) * time.Second, Dir: true, PrevExist: client.PrevExist})
cancel()
if err != nil {
handleError(ExitServerError, err)
}
}
示例15: IonblogServerAction
func IonblogServerAction(c *cli.Context) error {
if c.String("secret") == "" {
log.Print("A secret value is required!")
return errors.New("A secret value is required!")
}
PublishBlog()
go ServeHook(c.Int("port"), c.String("secret"))
go ServeSite(c.Int("webport"))
Listen()
return nil
}