本文整理汇总了Golang中github.com/urfave/cli.Context类的典型用法代码示例。如果您正苦于以下问题:Golang Context类的具体用法?Golang Context怎么用?Golang Context使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Context类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
}
开发者ID:twpayne,项目名称:go-doarama,代码行数:7,代码来源:doarama.go
示例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
}
开发者ID:lightningnetwork,项目名称:lnd,代码行数:25,代码来源:commands.go
示例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
}
开发者ID:aelsabbahy,项目名称:goss,代码行数:26,代码来源:add.go
示例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
}
开发者ID:godrei,项目名称:bitrise,代码行数:29,代码来源:version.go
示例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
}
开发者ID:kawamuray,项目名称:prometheus-json-exporter,代码行数:34,代码来源:init.go
示例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)
}
开发者ID:curtiszimmerman,项目名称:runc,代码行数:26,代码来源:utils_linux.go
示例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
}
开发者ID:godrei,项目名称:stepman,代码行数:25,代码来源:delete_steplib.go
示例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
}
}
开发者ID:jacobmarble,项目名称:cloud-print-connector,代码行数:32,代码来源:gcp-cups-connector-util.go
示例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
}
开发者ID:aelsabbahy,项目名称:goss,代码行数:30,代码来源:validate.go
示例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
}
开发者ID:docker,项目名称:containerd,代码行数:30,代码来源:main.go
示例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)
}
开发者ID:x1022as,项目名称:runc,代码行数:29,代码来源:exec.go
示例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
}
开发者ID:zbroju,项目名称:biclog,代码行数:31,代码来源:commands.go
示例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
}
开发者ID:jacobmarble,项目名称:cloud-print-connector,代码行数:30,代码来源:init.go
示例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
}
开发者ID:twpayne,项目名称:go-doarama,代码行数:29,代码来源:doarama.go
示例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
}
开发者ID:yagihiro,项目名称:google-apps-utils,代码行数:25,代码来源:groups.go
示例16: Version
// Version prints the libcompose version number and additionnal informations.
func Version(c *cli.Context) error {
if c.Bool("short") {
fmt.Println(version.VERSION)
return nil
}
tmpl, err := template.New("").Parse(versionTemplate)
if err != nil {
logrus.Fatal(err)
}
v := struct {
Version string
GitCommit string
GoVersion string
BuildTime string
Os string
Arch string
}{
Version: version.VERSION,
GitCommit: version.GITCOMMIT,
GoVersion: runtime.Version(),
BuildTime: version.BUILDTIME,
Os: runtime.GOOS,
Arch: runtime.GOARCH,
}
if err := tmpl.Execute(os.Stdout, v); err != nil {
logrus.Fatal(err)
}
fmt.Printf("\n")
return nil
}
开发者ID:vdemeester,项目名称:rancher-compose,代码行数:34,代码来源:version.go
示例17: 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")
}
}
开发者ID:wawandco,项目名称:transporter,代码行数:31,代码来源:generate.go
示例18: 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")
}
开发者ID:m4rkmckenna,项目名称:brooklyn-client,代码行数:27,代码来源:catalog-show.go
示例19: pluginInstall
func pluginInstall(c *cli.Context) error {
// Input validation
pluginSource := c.String("source")
if pluginSource == "" {
log.Fatal("Missing required input: source")
}
pluginVersionTag := c.String("version")
// Install
if pluginVersionTag == "" {
log.Infof("=> Installing plugin from (%s) with latest version...", pluginSource)
} else {
log.Infof("=> Installing plugin (%s) with version (%s)...", pluginSource, pluginVersionTag)
}
plugin, version, err := plugins.InstallPlugin(pluginSource, pluginVersionTag)
if err != nil {
log.Fatalf("Failed to install plugin from (%s), error: %s", pluginSource, err)
}
fmt.Println()
log.Infoln(colorstring.Greenf("Plugin (%s) with version (%s) installed ", plugin.Name, version))
if len(plugin.Description) > 0 {
fmt.Println()
fmt.Println(plugin.Description)
fmt.Println()
}
return nil
}
开发者ID:bitrise-io,项目名称:bitrise,代码行数:32,代码来源:plugin.go
示例20: Run
func (cmd *Config) Run(scope scope.Scope, c *cli.Context) {
if err := net.VerifyLoginURL(cmd.network); err != nil {
error_handler.ErrorExit(err)
}
if c.Args().Present() {
configValue, err := entity_config.ConfigValue(cmd.network, scope.Application, scope.Entity, c.Args().First())
if nil != err {
error_handler.ErrorExit(err)
}
displayValue, err := stringRepresentation(configValue)
if nil != err {
error_handler.ErrorExit(err)
}
fmt.Println(displayValue)
} else {
config, err := entity_config.ConfigCurrentState(cmd.network, scope.Application, scope.Entity)
if nil != err {
error_handler.ErrorExit(err)
}
table := terminal.NewTable([]string{"Key", "Value"})
for key, value := range config {
table.Add(key, fmt.Sprintf("%v", value))
}
table.Print()
}
}
开发者ID:m4rkmckenna,项目名称:brooklyn-client,代码行数:28,代码来源:config.go
注:本文中的github.com/urfave/cli.Context类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论