本文整理汇总了Golang中github.com/urfave/cli.Context类的典型用法代码示例。如果您正苦于以下问题:Golang Context类的具体用法?Golang Context怎么用?Golang Context使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Context类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: newCache
func newCache(c *cli.Context, client *doarama.Client) (doaramacache.ActivityCreator, error) {
dataSourceName := c.GlobalString("cache")
if dataSourceName == "" {
return client, nil
}
return doaramacache.NewSQLite3(dataSourceName, client)
}
示例2: 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
}
示例3: AutoAddResources
// Simple wrapper to add multiple resources
func AutoAddResources(fileName string, keys []string, c *cli.Context) error {
setStoreFormatFromFileName(fileName)
config := util.Config{
IgnoreList: c.GlobalStringSlice("exclude-attr"),
Timeout: int(c.Duration("timeout") / time.Millisecond),
}
var gossConfig GossConfig
if _, err := os.Stat(fileName); err == nil {
gossConfig = ReadJSON(fileName)
} else {
gossConfig = *NewGossConfig()
}
sys := system.New(c)
for _, key := range keys {
if err := AutoAddResource(fileName, gossConfig, key, c, config, sys); err != nil {
return err
}
}
WriteJSON(fileName, gossConfig)
return nil
}
示例4: printVersionCmd
func printVersionCmd(c *cli.Context) error {
fullVersion := c.Bool("full")
if err := output.ConfigureOutputFormat(c); err != nil {
log.Fatalf("Failed to configure output format, error: %s", err)
}
versionOutput := VersionOutputModel{
Version: version.VERSION,
}
if fullVersion {
versionOutput.FormatVersion = models.Version
versionOutput.BuildNumber = version.BuildNumber
versionOutput.Commit = version.Commit
}
if output.Format == output.FormatRaw {
if fullVersion {
fmt.Fprintf(c.App.Writer, "version: %v\nformat version: %v\nbuild number: %v\ncommit: %v\n", versionOutput.Version, versionOutput.FormatVersion, versionOutput.BuildNumber, versionOutput.Commit)
} else {
fmt.Fprintf(c.App.Writer, "%v\n", versionOutput.Version)
}
} else {
output.Print(versionOutput, output.Format)
}
return nil
}
示例5: 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
}
示例6: startContainer
func startContainer(context *cli.Context, spec *specs.Spec, create bool) (int, error) {
id := context.Args().First()
if id == "" {
return -1, errEmptyID
}
container, err := createContainer(context, id, spec)
if err != nil {
return -1, err
}
// Support on-demand socket activation by passing file descriptors into the container init process.
listenFDs := []*os.File{}
if os.Getenv("LISTEN_FDS") != "" {
listenFDs = activation.Files(false)
}
r := &runner{
enableSubreaper: !context.Bool("no-subreaper"),
shouldDestroy: true,
container: container,
listenFDs: listenFDs,
console: context.String("console"),
detach: context.Bool("detach"),
pidFile: context.String("pid-file"),
create: create,
}
return r.run(&spec.Process)
}
示例7: deleteStepLib
func deleteStepLib(c *cli.Context) error {
// Input validation
collectionURI := c.String(CollectionKey)
if collectionURI == "" {
return fmt.Errorf("Missing required input: collection")
}
log.Infof("Delete StepLib: %s", collectionURI)
route, found := stepman.ReadRoute(collectionURI)
if !found {
log.Warnf("No route found for collection: %s, cleaning up routing..", collectionURI)
if err := stepman.CleanupDanglingLib(collectionURI); err != nil {
log.Errorf("Error cleaning up lib: %s", collectionURI)
}
log.Infof("Call 'stepman setup -c %s' for a clean setup", collectionURI)
return nil
}
if err := stepman.CleanupRoute(route); err != nil {
return fmt.Errorf("Failed to cleanup route for StepLib: %s", collectionURI)
}
return nil
}
示例8: deleteAllGCPPrinterJobs
// deleteAllGCPPrinterJobs finds all GCP printer jobs associated with a
// a given printer id and deletes them.
func deleteAllGCPPrinterJobs(context *cli.Context) {
config := getConfig(context)
gcp := getGCP(config)
jobs, err := gcp.Fetch(context.String("printer-id"))
if err != nil {
log.Fatalln(err)
}
if len(jobs) == 0 {
fmt.Printf("No queued jobs\n")
}
ch := make(chan bool)
for _, job := range jobs {
go func(gcpJobID string) {
err := gcp.DeleteJob(gcpJobID)
if err != nil {
fmt.Printf("Failed to delete GCP job %s: %s\n", gcpJobID, err)
} else {
fmt.Printf("Deleted GCP job %s\n", gcpJobID)
}
ch <- true
}(job.GCPJobID)
}
for _ = range jobs {
<-ch
}
}
示例9: getGossConfig
func getGossConfig(c *cli.Context) GossConfig {
// handle stdin
var fh *os.File
var err error
var path, source string
specFile := c.GlobalString("gossfile")
if specFile == "-" {
source = "STDIN"
fh = os.Stdin
} else {
source = specFile
path = filepath.Dir(specFile)
fh, err = os.Open(specFile)
if err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(1)
}
}
data, err := ioutil.ReadAll(fh)
if err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(1)
}
gossConfig := mergeJSONData(ReadJSONData(data), 0, path)
if len(gossConfig.Resources()) == 0 {
fmt.Printf("Error: found 0 tests, source: %v\n", source)
os.Exit(1)
}
return gossConfig
}
示例10: startNATSServer
func startNATSServer(context *cli.Context) (e *stand.StanServer, err error) {
eventsURL, err := url.Parse(context.GlobalString("events-address"))
if err != nil {
return nil, err
}
no := stand.DefaultNatsServerOptions
nOpts := &no
nOpts.NoSigs = true
parts := strings.Split(eventsURL.Host, ":")
nOpts.Host = parts[0]
if len(parts) == 2 {
nOpts.Port, err = strconv.Atoi(parts[1])
} else {
nOpts.Port = nats.DefaultPort
}
defer func() {
if r := recover(); r != nil {
e = nil
if _, ok := r.(error); !ok {
err = fmt.Errorf("failed to start NATS server: %v", r)
} else {
err = r.(error)
}
}
}()
s := stand.RunServerWithOpts(nil, nOpts)
return s, nil
}
示例11: 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)
}
示例12: 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
}
示例13: 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
}
示例14: activityCreate
func activityCreate(c *cli.Context) error {
ctx := context.Background()
client, err := doaramacli.NewAuthenticatedDoaramaClient(c)
if err != nil {
return err
}
defer client.Close()
activityType, err := doarama.DefaultActivityTypes.Find(doaramacli.ActivityType(c))
if err != nil {
return err
}
activityInfo := &doarama.ActivityInfo{
TypeID: activityType.ID,
}
cache, err := newCache(c, client)
if err != nil {
return err
}
defer cache.Close()
for _, arg := range c.Args() {
a, err := activityCreateOne(ctx, cache, arg, activityInfo)
if err != nil {
log.Print(err)
continue
}
fmt.Printf("ActivityId: %d\n", a.ID)
}
return nil
}
示例15: doGroupMemberList
func doGroupMemberList(c *cli.Context) error {
srv, err := NewService()
if err != nil {
return nil
}
groupKey := c.String("key")
r, err := srv.directory.Members.List(groupKey).Do()
if err != nil {
log.Fatalf("Unable to retrieve group members in domain. %v", err)
return nil
}
count := len(r.Members)
if count == 0 {
fmt.Print("No group members found.\n")
} else {
for _, m := range r.Members {
fmt.Printf("%v, %v\n", m.Email, m.Role)
}
}
return nil
}