• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang cli.Context类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/codegangsta/cli.Context的典型用法代码示例。如果您正苦于以下问题:Golang Context类的具体用法?Golang Context怎么用?Golang Context使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Context类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: startDirectory

func startDirectory(c *cli.Context) {
	fmt.Println("Starting full-blown service-directory")

	// var apiReg = svcreg.NewGenericAPIVersionRegistry()
	// var svcReg = svcreg.NewGenericServiceRegistry()
	// var hostReg = svcreg.NewGenericHostRegistry(svcReg)
	//
	// var outboundEvents = make(chan evntsrc.Event)
	// var handler = evntsrc.NewEventHandler()
	// var dirSvc = svcreg.NewServiceRegistryWebService(outboundEvents, apiReg, svcReg, hostReg)
	// var nsqSink, err = utils.NewNsqSink()
	// if err != nil {
	// 	fmt.Println("Failed to initialize the NSQ communications")
	// 	return
	// }
	// handler.Use("ADD_ServiceDefinition", nsqSink.Publish)
	// var nsqCancelChan = keepProcessing(outboundEvents, handler.Handle)
	//
	// var m = martini.Classic()
	// m.Use(render.Renderer())
	// m.Action(dirSvc.Route().Handle)
	// http.HandleFunc("/service-directory/", func(w http.ResponseWriter, r *http.Request) {
	// 	r.URL, _ = url.Parse(strings.TrimPrefix(r.URL.String(), "/service-directory"))
	// 	m.ServeHTTP(w, r)
	// })

	// TODO (enzian) gracefully stop the service.
	log.Fatal(http.ListenAndServe(c.String("u"), nil))
	// nsqCancelChan <- true
}
开发者ID:enzian,项目名称:msf-tools,代码行数:30,代码来源:msf-tools.go


示例2: upload

func upload(c *cli.Context) {
	if c.NArg() < 2 || c.NArg() > 3 {
		cliutils.Exit(cliutils.ExitCodeError, "Wrong number of arguments. "+cliutils.GetDocumentationMessage())
	}
	localPath := c.Args().Get(0)
	versionDetails, err := utils.CreateVersionDetails(c.Args().Get(1))
	if err != nil {
		cliutils.Exit(cliutils.ExitCodeError, err.Error())
	}
	uploadPath := c.Args().Get(2)
	if strings.HasPrefix(uploadPath, "/") {
		uploadPath = uploadPath[1:]
	}

	uploadFlags, err := createUploadFlags(c)
	if err != nil {
		cliutils.Exit(cliutils.ExitCodeError, err.Error())
	}
	uploaded, failed, err := commands.Upload(versionDetails, localPath, uploadPath, uploadFlags)
	cliutils.ExitOnErr(err)
	if failed > 0 {
		if uploaded > 0 {
			cliutils.Exit(cliutils.ExitCodeWarning, "")
		}
		cliutils.Exit(cliutils.ExitCodeError, "")
	}
}
开发者ID:JFrogDev,项目名称:jfrog-cli-go,代码行数:27,代码来源:cli.go


示例3: GetRequirements

func (cmd ListServiceBrokers) GetRequirements(requirementsFactory requirements.Factory, c *cli.Context) (reqs []requirements.Requirement, err error) {
	if len(c.Args()) != 0 {
		cmd.ui.FailWithUsage(c)
	}
	reqs = append(reqs, requirementsFactory.NewLoginRequirement())
	return
}
开发者ID:tools-alexuser01,项目名称:cli,代码行数:7,代码来源:service_brokers.go


示例4: GetChain

func GetChain(ctx *cli.Context) (*core.ChainManager, common.Database, common.Database) {
	dataDir := ctx.GlobalString(DataDirFlag.Name)

	blockDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "blockchain"))
	if err != nil {
		Fatalf("Could not open database: %v", err)
	}

	stateDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "state"))
	if err != nil {
		Fatalf("Could not open database: %v", err)
	}

	extraDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "extra"))
	if err != nil {
		Fatalf("Could not open database: %v", err)
	}

	eventMux := new(event.TypeMux)
	chainManager := core.NewChainManager(blockDb, stateDb, eventMux)
	pow := ethash.New()
	txPool := core.NewTxPool(eventMux, chainManager.State, chainManager.GasLimit)
	blockProcessor := core.NewBlockProcessor(stateDb, extraDb, pow, txPool, chainManager, eventMux)
	chainManager.SetProcessor(blockProcessor)

	return chainManager, blockDb, stateDb
}
开发者ID:CedarLogic,项目名称:go-ethereum,代码行数:27,代码来源:flags.go


示例5: Run

func (cmd *unbindFromRunningGroup) Run(context *cli.Context) {
	name := context.Args()[0]

	securityGroup, err := cmd.securityGroupRepo.Read(name)
	switch (err).(type) {
	case nil:
	case *errors.ModelNotFoundError:
		cmd.ui.Ok()
		cmd.ui.Warn(T("Security group {{.security_group}} {{.error_message}}",
			map[string]interface{}{
				"security_group": terminal.EntityNameColor(name),
				"error_message":  terminal.WarningColor(T("does not exist.")),
			}))
		return
	default:
		cmd.ui.Failed(err.Error())
	}

	cmd.ui.Say(T("Unbinding security group {{.security_group}} from defaults for running as {{.username}}",
		map[string]interface{}{
			"security_group": terminal.EntityNameColor(securityGroup.Name),
			"username":       terminal.EntityNameColor(cmd.configRepo.Username()),
		}))
	err = cmd.runningGroupRepo.UnbindFromRunningSet(securityGroup.Guid)
	if err != nil {
		cmd.ui.Failed(err.Error())
	}
	cmd.ui.Ok()
	cmd.ui.Say("\n\n")
	cmd.ui.Say(T("TIP: Changes will not apply to existing running applications until they are restarted."))
}
开发者ID:nttlabs,项目名称:cli,代码行数:31,代码来源:unbind_running_security_group.go


示例6: exportDroplet

func (factory *DropletRunnerCommandFactory) exportDroplet(context *cli.Context) {
	dropletName := context.Args().First()
	if dropletName == "" {
		factory.UI.SayIncorrectUsage("<droplet-name> is required")
		factory.ExitHandler.Exit(exit_codes.InvalidSyntax)
		return
	}

	dropletReader, err := factory.dropletRunner.ExportDroplet(dropletName)
	if err != nil {
		factory.UI.SayLine(fmt.Sprintf("Error exporting droplet %s: %s", dropletName, err))
		factory.ExitHandler.Exit(exit_codes.CommandFailed)
		return
	}
	defer dropletReader.Close()

	dropletPath := dropletName + ".tgz"

	dropletWriter, err := os.OpenFile(dropletPath, os.O_WRONLY|os.O_CREATE, os.FileMode(0644))
	if err != nil {
		factory.UI.SayLine(fmt.Sprintf("Error exporting droplet '%s' to %s: %s", dropletName, dropletPath, err))
		factory.ExitHandler.Exit(exit_codes.CommandFailed)
		return
	}
	defer dropletWriter.Close()

	_, err = io.Copy(dropletWriter, dropletReader)
	if err != nil {
		factory.UI.SayLine(fmt.Sprintf("Error exporting droplet '%s' to %s: %s", dropletName, dropletPath, err))
		factory.ExitHandler.Exit(exit_codes.CommandFailed)
		return
	}

	factory.UI.SayLine(fmt.Sprintf("Droplet '%s' exported to %s.", dropletName, dropletPath))
}
开发者ID:cloudfoundry-incubator,项目名称:ltc,代码行数:35,代码来源:droplet_runner_command_factory.go


示例7: enable

func enable(c *cli.Context) {
	changed := false
	cfg, err := config.LoadConfig()
	if err != nil {
		log.Fatal(err)
	}

	for _, service := range c.Args() {
		if val, ok := cfg.Rancher.ServicesInclude[service]; !ok || !val {
			if strings.HasPrefix(service, "/") && !strings.HasPrefix(service, "/var/lib/rancher/conf") {
				log.Fatalf("ERROR: Service should be in path /var/lib/rancher/conf")
			}
			if _, err := compose.LoadServiceResource(service, true, cfg); err != nil {
				log.Fatalf("could not load service %s", service)
			}
			cfg.Rancher.ServicesInclude[service] = true
			changed = true
		}
	}

	if changed {
		if err := cfg.Set("rancher.services_include", cfg.Rancher.ServicesInclude); err != nil {
			log.Fatal(err)
		}
	}
}
开发者ID:rowhit,项目名称:os,代码行数:26,代码来源:service.go


示例8: setOrganization

func (cmd Login) setOrganization(c *cli.Context) (isOrgSet bool) {
	orgName := c.String("o")

	if orgName == "" {
		availableOrgs := []models.Organization{}
		apiErr := cmd.orgRepo.ListOrgs(func(o models.Organization) bool {
			availableOrgs = append(availableOrgs, o)
			return len(availableOrgs) < maxChoices
		})
		if apiErr != nil {
			cmd.ui.Failed("Error finding avilable orgs\n%s", apiErr.Error())
		}

		if len(availableOrgs) == 1 {
			cmd.targetOrganization(availableOrgs[0])
			return true
		}

		orgName = cmd.promptForOrgName(availableOrgs)
		if orgName == "" {
			cmd.ui.Say("")
			return false
		}
	}

	org, err := cmd.orgRepo.FindByName(orgName)
	if err != nil {
		cmd.ui.Failed("Error finding org %s\n%s", terminal.EntityNameColor(orgName), err.Error())
	}

	cmd.targetOrganization(org)
	return true
}
开发者ID:juggernaut,项目名称:cli,代码行数:33,代码来源:login.go


示例9: setSpace

func (cmd Login) setSpace(c *cli.Context) {
	spaceName := c.String("s")

	if spaceName == "" {
		var availableSpaces []models.Space
		err := cmd.spaceRepo.ListSpaces(func(space models.Space) bool {
			availableSpaces = append(availableSpaces, space)
			return (len(availableSpaces) < maxChoices)
		})
		if err != nil {
			cmd.ui.Failed("Error finding available spaces\n%s", err.Error())
		}

		// Target only space if possible
		if len(availableSpaces) == 1 {
			cmd.targetSpace(availableSpaces[0])
			return
		}

		spaceName = cmd.promptForSpaceName(availableSpaces)
		if spaceName == "" {
			cmd.ui.Say("")
			return
		}
	}

	space, err := cmd.spaceRepo.FindByName(spaceName)
	if err != nil {
		cmd.ui.Failed("Error finding space %s\n%s", terminal.EntityNameColor(spaceName), err.Error())
	}

	cmd.targetSpace(space)
}
开发者ID:juggernaut,项目名称:cli,代码行数:33,代码来源:login.go


示例10: Run

func (cmd Target) Run(c *cli.Context) {
	orgName := c.String("o")
	spaceName := c.String("s")

	if orgName != "" {
		err := cmd.setOrganization(orgName)
		if err != nil {
			cmd.ui.Failed(err.Error())
		} else if spaceName == "" {
			spaceList, apiErr := cmd.getSpaceList()
			if apiErr == nil && len(spaceList) == 1 {
				cmd.setSpace(spaceList[0].Name)
			}
		}
	}

	if spaceName != "" {
		err := cmd.setSpace(spaceName)
		if err != nil {
			cmd.ui.Failed(err.Error())
		}
	}

	cmd.ui.ShowConfiguration(cmd.config)
	if !cmd.config.IsLoggedIn() {
		cmd.ui.PanicQuietly()
	}
	utils.NotifyUpdateIfNeeded(cmd.ui, cmd.config)
	return
}
开发者ID:tools-alexuser01,项目名称:cli,代码行数:30,代码来源:target.go


示例11: Run

func (cmd *SpaceUsers) Run(c *cli.Context) {
	spaceName := c.Args()[1]
	org := cmd.orgReq.GetOrganization()

	space, apiErr := cmd.spaceRepo.FindByNameInOrg(spaceName, org.Guid)
	if apiErr != nil {
		cmd.ui.Failed(apiErr.Error())
	}

	cmd.ui.Say("Getting users in org %s / space %s as %s",
		terminal.EntityNameColor(org.Name),
		terminal.EntityNameColor(space.Name),
		terminal.EntityNameColor(cmd.config.Username()),
	)

	for _, role := range spaceRoles {
		displayName := spaceRoleToDisplayName[role]

		users, apiErr := cmd.userRepo.ListUsersInSpaceForRole(space.Guid, role)

		cmd.ui.Say("")
		cmd.ui.Say("%s", terminal.HeaderColor(displayName))

		for _, user := range users {
			cmd.ui.Say("  %s", user.Username)
		}

		if apiErr != nil {
			cmd.ui.Failed("Failed fetching space-users for role %s.\n%s", apiErr.Error(), displayName)
			return
		}
	}
}
开发者ID:palakmathur,项目名称:cli,代码行数:33,代码来源:space_users.go


示例12: Run

func (cmd CreateOrg) Run(c *cli.Context) {
	name := c.Args()[0]
	cmd.ui.Say(T("Creating org {{.OrgName}} as {{.Username}}...",
		map[string]interface{}{
			"OrgName":  terminal.EntityNameColor(name),
			"Username": terminal.EntityNameColor(cmd.config.Username())}))

	org := models.Organization{OrganizationFields: models.OrganizationFields{Name: name}}

	quotaName := c.String("q")
	if quotaName != "" {
		quota, err := cmd.quotaRepo.FindByName(quotaName)
		if err != nil {
			cmd.ui.Failed(err.Error())
		}

		org.QuotaDefinition.Guid = quota.Guid
	}

	err := cmd.orgRepo.Create(org)
	if err != nil {
		if apiErr, ok := err.(errors.HttpError); ok && apiErr.ErrorCode() == errors.ORG_EXISTS {
			cmd.ui.Ok()
			cmd.ui.Warn(T("Org {{.OrgName}} already exists",
				map[string]interface{}{"OrgName": name}))
			return
		} else {
			cmd.ui.Failed(err.Error())
		}
	}

	cmd.ui.Ok()
	cmd.ui.Say(T("\nTIP: Use '{{.Command}}' to target new org",
		map[string]interface{}{"Command": terminal.CommandColor(cf.Name() + " target -o " + name)}))
}
开发者ID:tools-alexuser01,项目名称:cli,代码行数:35,代码来源:create_org.go


示例13: Run

func (cmd *Files) Run(c *cli.Context) {
	app := cmd.appReq.GetApplication()

	cmd.ui.Say("Getting files for app %s in org %s / space %s as %s...",
		terminal.EntityNameColor(app.Name),
		terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
		terminal.EntityNameColor(cmd.config.SpaceFields().Name),
		terminal.EntityNameColor(cmd.config.Username()),
	)

	path := "/"
	if len(c.Args()) > 1 {
		path = c.Args()[1]
	}

	list, apiResponse := cmd.appFilesRepo.ListFiles(app.Guid, path)
	if apiResponse.IsNotSuccessful() {
		cmd.ui.Failed(apiResponse.Message)
		return
	}

	cmd.ui.Ok()
	cmd.ui.Say("")
	cmd.ui.Say("%s", list)
}
开发者ID:normalnorman,项目名称:cli,代码行数:25,代码来源:files.go


示例14: Run

func (cmd *Push) Run(c *cli.Context) {
	appSet := cmd.findAndValidateAppsToPush(c)
	_, apiErr := cmd.authRepo.RefreshAuthToken()
	if apiErr != nil {
		cmd.ui.Failed(fmt.Sprintf("Error refreshing auth token.\n%s", apiErr.Error()))
		return
	}

	routeActor := actors.NewRouteActor(cmd.ui, cmd.routeRepo)
	noHostname := c.Bool("no-hostname")

	for _, appParams := range appSet {
		cmd.fetchStackGuid(&appParams)
		app := cmd.createOrUpdateApp(appParams)

		cmd.updateRoutes(routeActor, app, appParams, noHostname)

		cmd.ui.Say(T("Uploading {{.AppName}}...",
			map[string]interface{}{"AppName": terminal.EntityNameColor(app.Name)}))

		apiErr := cmd.appBitsRepo.UploadApp(app.Guid, *appParams.Path, cmd.describeUploadOperation)
		if apiErr != nil {
			cmd.ui.Failed(fmt.Sprintf(T("Error uploading application.\n{{.ApiErr}}",
				map[string]interface{}{"ApiErr": apiErr.Error()})))
			return
		}
		cmd.ui.Ok()

		if appParams.ServicesToBind != nil {
			cmd.bindAppToServices(*appParams.ServicesToBind, app)
		}

		cmd.restart(app, appParams, c)
	}
}
开发者ID:ramirito,项目名称:cli,代码行数:35,代码来源:push.go


示例15: SecureYamlCmd

func SecureYamlCmd(c *cli.Context, client drone.Client) error {
	var (
		repo     = c.String("repo")
		inFile   = c.String("in")
		outFile  = c.String("out")
		ymlFile  = c.String("yaml")
		checksum = c.BoolT("checksum")
	)

	owner, name, err := parseRepo(repo)
	if err != nil {
		return err
	}

	keypair, err := client.RepoKey(owner, name)
	if err != nil {
		return err
	}

	key, err := toPublicKey(keypair.Public)
	if err != nil {
		return err
	}

	// read the .drone.sec.yml file (plain text)
	plaintext, err := readInput(inFile)
	if err != nil {
		return err
	}

	// parse the .drone.sec.yml file
	sec := new(secure.Secure)
	err = yaml.Unmarshal(plaintext, sec)
	if err != nil {
		return err
	}

	// read the .drone.yml file and caclulate the
	// checksum. add to the .drone.sec.yml file.
	yml, err := ioutil.ReadFile(ymlFile)
	if err == nil && checksum {
		sec.Checksum = sha256sum(string(yml))
	}

	// re-marshal the .drone.sec.yml file since we've
	// added the checksum
	plaintext, err = yaml.Marshal(sec)
	if err != nil {
		return err
	}

	// encrypt the .drone.sec.yml file
	ciphertext, err := encrypt(plaintext, key)
	if err != nil {
		return err
	}

	// write the encrypted .drone.sec.yml file to .drone.sec
	return writeOutput(outFile, ciphertext)
}
开发者ID:gregorygtseng,项目名称:drone-cli,代码行数:60,代码来源:secure.go


示例16: Run

func (cmd SetSpaceQuota) Run(context *cli.Context) {

	spaceName := context.Args()[0]
	quotaName := context.Args()[1]

	cmd.ui.Say(T("Assigning space quota {{.QuotaName}} to space {{.SpaceName}} as {{.Username}}...", map[string]interface{}{
		"QuotaName": terminal.EntityNameColor(quotaName),
		"SpaceName": terminal.EntityNameColor(spaceName),
		"Username":  terminal.EntityNameColor(cmd.config.Username()),
	}))

	space, err := cmd.spaceRepo.FindByName(spaceName)
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	if space.SpaceQuotaGuid != "" {
		cmd.ui.Failed(T("This space already has an assigned space quota."))
	}

	quota, err := cmd.quotaRepo.FindByName(quotaName)
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	err = cmd.quotaRepo.AssociateSpaceWithQuota(space.Guid, quota.Guid)
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	cmd.ui.Ok()
}
开发者ID:nttlabs,项目名称:cli,代码行数:32,代码来源:set_space_quota.go


示例17: GetRequirements

func (cmd *PluginInstall) GetRequirements(_ requirements.Factory, c *cli.Context) (req []requirements.Requirement, err error) {
	if len(c.Args()) != 1 {
		cmd.ui.FailWithUsage(c)
	}

	return
}
开发者ID:raghulsid,项目名称:cli,代码行数:7,代码来源:install_plugin.go


示例18: delete

// delete is a subcommand to delete a snippet.
func delete(c *cli.Context) {
	force := c.Bool("f")
	snippetName := c.Args().First()
	if len(snippetName) == 0 {
		log.Fatal("please enter snippet name")
	}

	s := NewSnippet(conf.SnippetDirectory, snippetName)

	if !s.Exists() {
		log.Fatal("This snippet doesn't exists.")
	}

	if !force {
		reader := bufio.NewReader(os.Stdin)
		fmt.Print("sure you want to delete %s [yn]?")
		ret, err := reader.ReadString('\n')
		if err != nil {
			log.Fatal(err)
		}

		if ret != "y\n" {
			return
		}
	}

	if err := s.Delete(); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s has been deleted.\n", snippetName)
}
开发者ID:sudix,项目名称:chickenhead,代码行数:33,代码来源:main.go


示例19: enumerate

func (c *clusterClient) enumerate(context *cli.Context) {
	c.clusterOptions(context)
	jsonOut := context.GlobalBool("json")
	outFd := os.Stdout
	fn := "enumerate"

	cluster, err := c.manager.Enumerate()
	if err != nil {
		cmdError(context, fn, err)
		return
	}

	if jsonOut {
		fmtOutput(context, &Format{Cluster: &cluster})
	} else {
		w := new(tabwriter.Writer)
		w.Init(outFd, 12, 12, 1, ' ', 0)

		fmt.Fprintln(w, "ID\t IMAGE\t STATUS\t NAMES\t NODE")
		for _, n := range cluster.Nodes {
			for _, c := range n.Containers {
				fmt.Fprintln(w, c.ID, "\t", c.Image, "\t", c.Status, "\t",
					c.Names, "\t", n.Ip)
			}
		}

		fmt.Fprintln(w)
		w.Flush()
	}
}
开发者ID:mike6350,项目名称:openstorage,代码行数:30,代码来源:cluster.go


示例20: list

// list is a subcommand to list up snippets.
// It just finds snippet files in the snippet directory and listed them.
func list(c *cli.Context) {
	var pattern *regexp.Regexp
	var err error
	query := c.Args().First()
	if len(query) > 0 {
		pattern, err = regexp.Compile(fmt.Sprintf(".*%s.*", query))
		if err != nil {
			log.Fatal(err)
		}
	}

	err = filepath.Walk(
		conf.SnippetDirectory,
		func(path string, info os.FileInfo, err error) error {
			if info.IsDir() {
				return nil
			}
			rel, err := filepath.Rel(conf.SnippetDirectory, path)

			if pattern != nil {
				if pattern.MatchString(rel) {
					fmt.Println(rel)
				}
				return nil
			}

			fmt.Println(rel)
			return nil
		},
	)

	if err != nil {
		log.Fatal(err)
	}
}
开发者ID:sudix,项目名称:chickenhead,代码行数:37,代码来源:main.go



注:本文中的github.com/codegangsta/cli.Context类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang cli.DurationFlag类代码示例发布时间:2022-05-23
下一篇:
Golang cli.Command类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap