當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Context.IsSet方法代碼示例

本文整理匯總了Golang中github.com/urfave/cli.Context.IsSet方法的典型用法代碼示例。如果您正苦於以下問題:Golang Context.IsSet方法的具體用法?Golang Context.IsSet怎麽用?Golang Context.IsSet使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在github.com/urfave/cli.Context的用法示例。


在下文中一共展示了Context.IsSet方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: runUpdate

func runUpdate(c *cli.Context) error {
	if c.IsSet("config") {
		setting.CustomConf = c.String("config")
	}

	setup("update.log")

	if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
		log.GitLogger.Trace("SSH_ORIGINAL_COMMAND is empty")
		return nil
	}

	args := c.Args()
	if len(args) != 3 {
		log.GitLogger.Fatal(2, "Arguments received are not equal to three")
	} else if len(args[0]) == 0 {
		log.GitLogger.Fatal(2, "First argument 'refName' is empty, shouldn't use")
	}

	task := models.UpdateTask{
		UUID:        os.Getenv("uuid"),
		RefName:     args[0],
		OldCommitID: args[1],
		NewCommitID: args[2],
	}

	if err := models.AddUpdateTask(&task); err != nil {
		log.GitLogger.Fatal(2, "AddUpdateTask: %v", err)
	}

	return nil
}
開發者ID:VoyTechnology,項目名稱:gogs,代碼行數:32,代碼來源:update.go

示例2: AddCommand

// AddCommand adds a Note
func AddCommand(c *cli.Context, i storage.Impl) (n storage.Note, err error) {
	nName, err := NoteName(c)
	if err != nil {
		return n, err
	}

	if exists := i.NoteExists(nName); exists == true {
		return n, fmt.Errorf("Note already exists")
	}

	n.Name = nName
	n.Temporary = c.Bool("t")

	// Only open editor if -p (read from clipboard) isnt set
	if c.IsSet("p") {
		nText, err := clipboard.ReadAll()
		if err != nil {
			return n, err
		}
		n.Text = nText
	} else {
		if err := writer.WriteNote(&n); err != nil {
			return n, err
		}
	}

	if err := i.SaveNote(&n); err != nil {
		return n, err
	}

	return n, nil
}
開發者ID:gummiboll,項目名稱:forgetful,代碼行數:33,代碼來源:commands.go

示例3: keypairsCreateCmd

func keypairsCreateCmd(c *CLI, ctx *cli.Context) {
	usage := func(msg string) {
		fmt.Printf("Usage: %s keypairs create --name=<keypair-name> <private-key-path> <certificate-path>\n", c.Name)
		fatal(msg)
	}
	if len(ctx.Args()) < 2 {
		usage("too few arguments")
	}
	if !ctx.IsSet("name") || ctx.String("name") == "" {
		usage("--name is required")
	}
	api := c.GetAPIClient(ctx)
	resourceGroup := c.GetResourceGroup(ctx)
	name := ctx.String("name")
	privateKeyPath := ctx.Args()[0]
	certPath := ctx.Args()[1]
	privateKey, err := ioutil.ReadFile(privateKeyPath)
	if err != nil {
		fatal(err.Error())
	}
	cert, err := ioutil.ReadFile(certPath)
	if err != nil {
		fatal(err.Error())
	}
	keypair := gondor.KeyPair{
		ResourceGroup: resourceGroup.URL,
		Name:          &name,
		Key:           privateKey,
		Certificate:   cert,
	}
	if err := api.KeyPairs.Create(&keypair); err != nil {
		fatal(err.Error())
	}
	success("keypair created.")
}
開發者ID:eldarion-gondor,項目名稱:cli,代碼行數:35,代碼來源:keypairs.go

示例4: server

func server(c *cli.Context) {
	println("CIRCUIT 2015 gocircuit.org")
	var err error

	if c.Bool("docker") {
		cmd, err := docker.Init()
		if err != nil {
			log.Fatalf("cannot use docker: %v", err)
		}
		log.Printf("Enabling docker elements, using %s", cmd)
	}
	// parse arguments
	var tcpaddr = parseAddr(c) // server bind address
	var join n.Addr            // join address of another circuit server
	if c.IsSet("join") {
		if join, err = n.ParseAddr(c.String("join")); err != nil {
			log.Fatalf("join address does not parse (%s)", err)
		}
	}
	var multicast = parseDiscover(c)
	// server instance working directory
	var varDir string
	if !c.IsSet("var") {
		varDir = path.Join(os.TempDir(), fmt.Sprintf("%s-%%W-P%04d", n.Scheme, os.Getpid()))
	} else {
		varDir = c.String("var")
	}

	// start circuit runtime
	addr := load(tcpaddr, varDir, readkey(c))

	// tissue + locus
	kin, xkin, rip := tissue.NewKin()
	xlocus := locus.NewLocus(kin, rip)

	// joining
	switch {
	case join != nil:
		kin.ReJoin(join)
	case multicast != nil:
		log.Printf("Using UDP multicast discovery on address %s", multicast.String())
		go assemble.NewAssembler(addr, multicast).AssembleServer(
			func(joinAddr n.Addr) {
				kin.ReJoin(joinAddr)
			},
		)
	default:
		log.Println("Singleton server.")
	}

	circuit.Listen(tissue.ServiceName, xkin)
	circuit.Listen(LocusName, xlocus)

	<-(chan int)(nil)
}
開發者ID:jmcadden,項目名稱:farmer,代碼行數:55,代碼來源:server.go

示例5: runCreateUser

func runCreateUser(c *cli.Context) error {
	if !c.IsSet("name") {
		return fmt.Errorf("Username is not specified")
	} else if !c.IsSet("password") {
		return fmt.Errorf("Password is not specified")
	} else if !c.IsSet("email") {
		return fmt.Errorf("Email is not specified")
	}

	if c.IsSet("config") {
		setting.CustomConf = c.String("config")
	}

	setting.NewContext()
	models.LoadConfigs()
	models.SetEngine()

	if err := models.CreateUser(&models.User{
		Name:     c.String("name"),
		Email:    c.String("email"),
		Passwd:   c.String("password"),
		IsActive: true,
		IsAdmin:  c.Bool("admin"),
	}); err != nil {
		return fmt.Errorf("CreateUser: %v", err)
	}

	fmt.Printf("New user '%s' has been successfully created!\n", c.String("name"))
	return nil
}
開發者ID:andreynering,項目名稱:gogs,代碼行數:30,代碼來源:admin.go

示例6: setup

func setup(c *cli.Context) error {
	log.Debug("Setup")

	// Input validation
	steplibURI := c.String(CollectionKey)
	if steplibURI == "" {
		log.Fatal("No step collection specified")
	}

	copySpecJSONPath := c.String(CopySpecJSONKey)

	if c.IsSet(LocalCollectionKey) {
		log.Warn("'local' flag is deprecated")
		log.Warn("use 'file://' prefix in steplib path instead")
		fmt.Println()
	}

	if c.Bool(LocalCollectionKey) {
		if !strings.HasPrefix(steplibURI, "file://") {
			log.Warnf("Appending file path prefix (file://) to StepLib (%s)", steplibURI)
			steplibURI = "file://" + steplibURI
			log.Warnf("From now you can refer to this StepLib with URI: %s", steplibURI)
			log.Warnf("For example, to delete StepLib call: `stepman delete --collection %s`", steplibURI)
		}
	}

	// Setup
	if err := setupSteplib(steplibURI, false); err != nil {
		log.Fatalf("Setup failed, error: %s", err)
	}

	// Copy spec.json
	if copySpecJSONPath != "" {
		log.Infof("Copying spec YML to path: %s", copySpecJSONPath)

		route, found := stepman.ReadRoute(steplibURI)
		if !found {
			log.Fatalf("No route found for steplib (%s)", steplibURI)
		}

		sourceSpecJSONPth := stepman.GetStepSpecPath(route)
		if err := cmdex.CopyFile(sourceSpecJSONPth, copySpecJSONPath); err != nil {
			log.Fatalf("Failed to copy spec.json from (%s) to (%s), error: %s", sourceSpecJSONPth, copySpecJSONPath, err)
		}
	}

	return nil
}
開發者ID:godrei,項目名稱:stepman,代碼行數:48,代碼來源:setup.go

示例7: ApplyInputSourceValue

// ApplyInputSourceValue applies a BoolT value to the flagSet if required
func (f *BoolTFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error {
	if f.set != nil {
		if !context.IsSet(f.Name) && !isEnvVarSet(f.EnvVar) {
			value, err := isc.BoolT(f.BoolTFlag.Name)
			if err != nil {
				return err
			}
			if !value {
				eachName(f.Name, func(name string) {
					f.set.Set(f.Name, strconv.FormatBool(value))
				})
			}
		}
	}
	return nil
}
開發者ID:themecloud,項目名稱:heimdall,代碼行數:17,代碼來源:flag.go

示例8: runWeb

func runWeb(ctx *cli.Context) {
	if ctx.IsSet("config") {
		setting.CustomConf = ctx.String("config")
	}
	setting.NewContext()
	models.NewContext()

	log.Info("Peach %s", setting.AppVer)

	m := macaron.New()
	m.Use(macaron.Logger())
	m.Use(macaron.Recovery())
	m.Use(macaron.Statics(macaron.StaticOptions{
		SkipLogging: setting.ProdMode,
	}, "custom/public", "public", models.HTMLRoot))
	m.Use(i18n.I18n(i18n.Options{
		Files:       setting.Docs.Locales,
		DefaultLang: setting.Docs.Langs[0],
	}))
	tplDir := "templates"
	if setting.Page.UseCustomTpl {
		tplDir = "custom/templates"
	}
	m.Use(pongo2.Pongoer(pongo2.Options{
		Directory: tplDir,
	}))
	m.Use(middleware.Contexter())

	m.Get("/", routers.Home)
	m.Get("/docs", routers.Docs)
	m.Get("/docs/images/*", routers.DocsStatic)
	m.Get("/docs/*", routers.Protect, routers.Docs)
	m.Post("/hook", routers.Hook)
	m.Get("/search", routers.Search)
	m.Get("/*", routers.Pages)

	m.NotFound(routers.NotFound)

	listenAddr := fmt.Sprintf("0.0.0.0:%d", setting.HTTPPort)
	log.Info("%s Listen on %s", setting.Site.Name, listenAddr)
	log.Fatal("Fail to start Peach: %v", http.ListenAndServe(listenAddr, m))
}
開發者ID:peachdocs,項目名稱:peach,代碼行數:42,代碼來源:web.go

示例9: setup

func setup(c *cli.Context) error {
	PrintBitriseHeaderASCIIArt(c.App.Version)

	if c.IsSet(MinimalModeKey) {
		log.Warn("'minimal' flag is deprecated")
		log.Warn("currently setup without any flag does the same as minimal setup in previous versions")
		log.Warn("use 'full' flag to achive the full setup process (which includes the 'brew doctor' call)")
		fmt.Println()
	}

	if err := bitrise.RunSetup(c.App.Version, c.Bool(FullModeKey)); err != nil {
		log.Fatalf("Setup failed, error: %s", err)
	}

	log.Infoln("To start using bitrise:")
	log.Infoln("* cd into your project's directory (if you're not there already)")
	log.Infoln("* call: bitrise init")
	log.Infoln("* follow the guide")
	fmt.Println()
	log.Infoln("That's all :)")

	return nil
}
開發者ID:bitrise-io,項目名稱:bitrise,代碼行數:23,代碼來源:setup.go

示例10: parseSQLFromArgs

func parseSQLFromArgs(ctx *cli.Context) *sqlcommand.SQLCommand {
	var sqlText string
	if !ctx.IsSet("sql") {
		//Trying from stdin
		fi, err := os.Stdin.Stat()
		if err != nil {
			panic(err)
		}
		if fi.Mode()&os.ModeNamedPipe == 0 {
			return nil
		}
		bio := bufio.NewReader(os.Stdin)
		sqlText, err = bio.ReadString(0)
		if err != nil && err != io.EOF {
			panic(err)
		}
	} else {
		sqlText = ctx.String("sql")
	}
	//Prepare parameters
	colParams, e := parameters.GetInstance().All()
	if e != nil {
		panic(e)
	}
	params := colParams.Get()
	paramsArgs := ctx.StringSlice("param")
	for i := 0; i < len(paramsArgs); i++ {

		newparam, e := paramsreplace.Replace(paramsArgs[i], params)
		if e != nil {
			logger.Error.Println(e)
		} else {
			paramsArgs[i] = newparam
		}
	}
	return sqlcommand.New(sqlText, paramsArgs)
}
開發者ID:arteev,項目名稱:dsql,代碼行數:37,代碼來源:remotedb.go

示例11: parseOthersFlagsForRunContext

func parseOthersFlagsForRunContext(ctx *cli.Context, ctxRun *action.Context) error {
	if ctx.IsSet("format") {
		format := ctx.String("format")
		subformat := ""
		//TODO: refactor it!
		if strings.Contains(format, "raw:") {
			subformat = format[len("raw:"):]
			format = "raw"
		}
		if strings.Contains(format, "table:") {
			subformat = format[len("table:"):]
			format = "table"
		}
		if strings.Contains(format, "json:") {
			subformat = format[len("json:"):]
			format = "json"
		}
		if strings.Contains(format, "xml:") {
			subformat = format[len("xml:"):]
			format = "xml"
		}

		switch format {
		case "table", "raw", "json", "xml":
			ctxRun.Set("format", format)
			ctxRun.Set("subformat", subformat)
			break
		default:
			return fmt.Errorf("Unknown format:%s", format)
		}
	} else {
		ctxRun.Set("format", "raw")
	}

	if ctx.IsSet("timeout") {
		ctxRun.Set("timeout", ctx.Int("timeout"))
	}
	if ctx.IsSet("commit") {
		ctxRun.Set("commit", ctx.Bool("commit"))
	}
	return nil
}
開發者ID:arteev,項目名稱:dsql,代碼行數:42,代碼來源:remotedb.go

示例12: run

// run is the main run target.
func run(c *cli.Context) error {

	obj := &Main{}

	obj.Program = c.App.Name
	obj.Version = c.App.Version

	if h := c.String("hostname"); c.IsSet("hostname") && h != "" {
		obj.Hostname = &h
	}

	if s := c.String("prefix"); c.IsSet("prefix") && s != "" {
		obj.Prefix = &s
	}
	obj.TmpPrefix = c.Bool("tmp-prefix")
	obj.AllowTmpPrefix = c.Bool("allow-tmp-prefix")

	if _ = c.String("code"); c.IsSet("code") {
		if obj.GAPI != nil {
			return fmt.Errorf("Can't combine code GAPI with existing GAPI.")
		}
		// TODO: implement DSL GAPI
		//obj.GAPI = &dsl.GAPI{
		//	Code: &s,
		//}
		return fmt.Errorf("The Code GAPI is not implemented yet!") // TODO: DSL
	}
	if y := c.String("yaml"); c.IsSet("yaml") {
		if obj.GAPI != nil {
			return fmt.Errorf("Can't combine YAML GAPI with existing GAPI.")
		}
		obj.GAPI = &yamlgraph.GAPI{
			File: &y,
		}
	}
	if p := c.String("puppet"); c.IsSet("puppet") {
		if obj.GAPI != nil {
			return fmt.Errorf("Can't combine puppet GAPI with existing GAPI.")
		}
		obj.GAPI = &puppet.GAPI{
			PuppetParam: &p,
			PuppetConf:  c.String("puppet-conf"),
		}
	}
	obj.Remotes = c.StringSlice("remote") // FIXME: GAPI-ify somehow?

	obj.NoWatch = c.Bool("no-watch")
	obj.Noop = c.Bool("noop")
	obj.Graphviz = c.String("graphviz")
	obj.GraphvizFilter = c.String("graphviz-filter")
	obj.ConvergedTimeout = c.Int("converged-timeout")
	obj.MaxRuntime = uint(c.Int("max-runtime"))

	obj.Seeds = c.StringSlice("seeds")
	obj.ClientURLs = c.StringSlice("client-urls")
	obj.ServerURLs = c.StringSlice("server-urls")
	obj.IdealClusterSize = c.Int("ideal-cluster-size")
	obj.NoServer = c.Bool("no-server")

	obj.CConns = uint16(c.Int("cconns"))
	obj.AllowInteractive = c.Bool("allow-interactive")
	obj.SSHPrivIDRsa = c.String("ssh-priv-id-rsa")
	obj.NoCaching = c.Bool("no-caching")
	obj.Depth = uint16(c.Int("depth"))

	if err := obj.Init(); err != nil {
		return err
	}

	// install the exit signal handler
	exit := make(chan struct{})
	defer close(exit)
	go func() {
		signals := make(chan os.Signal, 1)
		signal.Notify(signals, os.Interrupt) // catch ^C
		//signal.Notify(signals, os.Kill) // catch signals
		signal.Notify(signals, syscall.SIGTERM)

		select {
		case sig := <-signals: // any signal will do
			if sig == os.Interrupt {
				log.Println("Interrupted by ^C")
				obj.Exit(nil)
				return
			}
			log.Println("Interrupted by signal")
			obj.Exit(fmt.Errorf("Killed by %v", sig))
			return
		case <-exit:
			return
		}
	}()

	if err := obj.Run(); err != nil {
		return err
		//return cli.NewExitError(err.Error(), 1) // TODO: ?
		//return cli.NewExitError("", 1) // TODO: ?
	}
	return nil
//.........這裏部分代碼省略.........
開發者ID:igalic,項目名稱:mgmt,代碼行數:101,代碼來源:cli.go

示例13: run

// run is the main run target.
func run(c *cli.Context) error {
	var start = time.Now().UnixNano()
	log.Printf("This is: %v, version: %v", program, version)
	log.Printf("Main: Start: %v", start)

	hostname, _ := os.Hostname()
	// allow passing in the hostname, instead of using --hostname
	if c.IsSet("file") {
		if config := gconfig.ParseConfigFromFile(c.String("file")); config != nil {
			if h := config.Hostname; h != "" {
				hostname = h
			}
		}
	}
	if c.IsSet("hostname") { // override by cli
		if h := c.String("hostname"); h != "" {
			hostname = h
		}
	}
	noop := c.Bool("noop")

	seeds, err := etcdtypes.NewURLs(
		util.FlattenListWithSplit(c.StringSlice("seeds"), []string{",", ";", " "}),
	)
	if err != nil && len(c.StringSlice("seeds")) > 0 {
		log.Printf("Main: Error: seeds didn't parse correctly!")
		return cli.NewExitError("", 1)
	}
	clientURLs, err := etcdtypes.NewURLs(
		util.FlattenListWithSplit(c.StringSlice("client-urls"), []string{",", ";", " "}),
	)
	if err != nil && len(c.StringSlice("client-urls")) > 0 {
		log.Printf("Main: Error: clientURLs didn't parse correctly!")
		return cli.NewExitError("", 1)
	}
	serverURLs, err := etcdtypes.NewURLs(
		util.FlattenListWithSplit(c.StringSlice("server-urls"), []string{",", ";", " "}),
	)
	if err != nil && len(c.StringSlice("server-urls")) > 0 {
		log.Printf("Main: Error: serverURLs didn't parse correctly!")
		return cli.NewExitError("", 1)
	}

	idealClusterSize := uint16(c.Int("ideal-cluster-size"))
	if idealClusterSize < 1 {
		log.Printf("Main: Error: idealClusterSize should be at least one!")
		return cli.NewExitError("", 1)
	}

	if c.IsSet("file") && c.IsSet("puppet") {
		log.Println("Main: Error: the --file and --puppet parameters cannot be used together!")
		return cli.NewExitError("", 1)
	}

	if c.Bool("no-server") && len(c.StringSlice("remote")) > 0 {
		// TODO: in this case, we won't be able to tunnel stuff back to
		// here, so if we're okay with every remote graph running in an
		// isolated mode, then this is okay. Improve on this if there's
		// someone who really wants to be able to do this.
		log.Println("Main: Error: the --no-server and --remote parameters cannot be used together!")
		return cli.NewExitError("", 1)
	}

	cConns := uint16(c.Int("cconns"))
	if cConns < 0 {
		log.Printf("Main: Error: --cconns should be at least zero!")
		return cli.NewExitError("", 1)
	}

	if c.IsSet("converged-timeout") && cConns > 0 && len(c.StringSlice("remote")) > c.Int("cconns") {
		log.Printf("Main: Error: combining --converged-timeout with more remotes than available connections will never converge!")
		return cli.NewExitError("", 1)
	}

	depth := uint16(c.Int("depth"))
	if depth < 0 { // user should not be using this argument manually
		log.Printf("Main: Error: negative values for --depth are not permitted!")
		return cli.NewExitError("", 1)
	}

	if c.IsSet("prefix") && c.Bool("tmp-prefix") {
		log.Println("Main: Error: combining --prefix and the request for a tmp prefix is illogical!")
		return cli.NewExitError("", 1)
	}
	if s := c.String("prefix"); c.IsSet("prefix") && s != "" {
		prefix = s
	}

	// make sure the working directory prefix exists
	if c.Bool("tmp-prefix") || os.MkdirAll(prefix, 0770) != nil {
		if c.Bool("tmp-prefix") || c.Bool("allow-tmp-prefix") {
			if prefix, err = ioutil.TempDir("", program+"-"); err != nil {
				log.Printf("Main: Error: Can't create temporary prefix!")
				return cli.NewExitError("", 1)
			}
			log.Println("Main: Warning: Working prefix directory is temporary!")

		} else {
			log.Printf("Main: Error: Can't create prefix!")
//.........這裏部分代碼省略.........
開發者ID:ffrank,項目名稱:mgmt,代碼行數:101,代碼來源:main.go

示例14: commonSparse

func (c *Config) commonSparse(context *cli.Context) *Config {
	s := *c

	if s.XMPPServer == DefaultConfig.XMPPServer {
		s.XMPPServer = ""
	}
	if !context.IsSet("xmpp-port") &&
		s.XMPPPort == DefaultConfig.XMPPPort {
		s.XMPPPort = 0
	}
	if !context.IsSet("xmpp-ping-timeout") &&
		s.XMPPPingTimeout == DefaultConfig.XMPPPingTimeout {
		s.XMPPPingTimeout = ""
	}
	if !context.IsSet("xmpp-ping-interval") &&
		s.XMPPPingInterval == DefaultConfig.XMPPPingInterval {
		s.XMPPPingInterval = ""
	}
	if s.GCPBaseURL == DefaultConfig.GCPBaseURL {
		s.GCPBaseURL = ""
	}
	if s.GCPOAuthClientID == DefaultConfig.GCPOAuthClientID {
		s.GCPOAuthClientID = ""
	}
	if s.GCPOAuthClientSecret == DefaultConfig.GCPOAuthClientSecret {
		s.GCPOAuthClientSecret = ""
	}
	if s.GCPOAuthAuthURL == DefaultConfig.GCPOAuthAuthURL {
		s.GCPOAuthAuthURL = ""
	}
	if s.GCPOAuthTokenURL == DefaultConfig.GCPOAuthTokenURL {
		s.GCPOAuthTokenURL = ""
	}
	if !context.IsSet("gcp-max-concurrent-downloads") &&
		s.GCPMaxConcurrentDownloads == DefaultConfig.GCPMaxConcurrentDownloads {
		s.GCPMaxConcurrentDownloads = 0
	}
	if !context.IsSet("native-job-queue-size") &&
		s.NativeJobQueueSize == DefaultConfig.NativeJobQueueSize {
		s.NativeJobQueueSize = 0
	}
	if !context.IsSet("native-printer-poll-interval") &&
		s.NativePrinterPollInterval == DefaultConfig.NativePrinterPollInterval {
		s.NativePrinterPollInterval = ""
	}
	if !context.IsSet("cups-job-full-username") &&
		reflect.DeepEqual(s.CUPSJobFullUsername, DefaultConfig.CUPSJobFullUsername) {
		s.CUPSJobFullUsername = nil
	}
	if !context.IsSet("prefix-job-id-to-job-title") &&
		reflect.DeepEqual(s.PrefixJobIDToJobTitle, DefaultConfig.PrefixJobIDToJobTitle) {
		s.PrefixJobIDToJobTitle = nil
	}
	if !context.IsSet("display-name-prefix") &&
		s.DisplayNamePrefix == DefaultConfig.DisplayNamePrefix {
		s.DisplayNamePrefix = ""
	}
	if !context.IsSet("local-port-low") &&
		s.LocalPortLow == DefaultConfig.LocalPortLow {
		s.LocalPortLow = 0
	}
	if !context.IsSet("local-port-high") &&
		s.LocalPortHigh == DefaultConfig.LocalPortHigh {
		s.LocalPortHigh = 0
	}

	return &s
}
開發者ID:jacobmarble,項目名稱:cloud-print-connector,代碼行數:68,代碼來源:config.go

示例15: handleCommand

//
// handleCommand is a generic wrapper for handling commands, or more precisely their errors
//
func handleCommand(cx *cli.Context, options []string, cmd *cliCommand, method func(*formatter, *cli.Context, *cliCommand) error) error {
	// step: handle any panics in the command
	defer func() {
		if r := recover(); r != nil {
			fmt.Fprintf(os.Stderr, "[error] internal error occurred, message: %s", r)
			os.Exit(1)
		}
	}()

	// step: check the required options were specified
	for _, k := range options {
		items := strings.Split(k, ":")
		if len(items) != 3 {
			panic("invalid required option definition, SCOPE:NAME:TYPE")
		}
		name := items[1]

		//
		// @Fix the cli lib IsSet does not check if the option was set by a environment variable, the
		// issue https://github.com/urfave/cli/issues/294 highlights problem. As a consequence, we can't determine
		// if the variable is actually set. The hack below attempts to remedy it.
		//
		var invalid bool

		switch scope := items[0]; scope {
		case "g":
			switch t := items[2]; t {
			case "s":
				invalid = !cx.GlobalIsSet(name) && cx.String(name) == ""
			case "a":
				invalid = !cx.GlobalIsSet(name) && len(cx.GlobalStringSlice(name)) == 0
			}
			if invalid {
				printError("the global option: '%s' is required", name)
			}
		default:
			switch t := items[2]; t {
			case "s":
				invalid = !cx.IsSet(name) && cx.String(name) == ""
			case "a":
				invalid = !cx.IsSet(name) && len(cx.StringSlice(name)) == 0
			}
			if invalid {
				printError("the command option: '%s' is required", name)
			}
		}
	}

	// step: create a cli output
	writer, err := newFormatter(cx.GlobalString("format"), os.Stdout)
	if err != nil {
		printError("error: %s", err)
	}

	// step: call the command and handle any errors
	if err := method(writer, cx, cmd); err != nil {
		printError("operation failed, error: %s", err)
	}

	return nil
}
開發者ID:UKHomeOffice,項目名稱:s3secrets,代碼行數:64,代碼來源:cli.go


注:本文中的github.com/urfave/cli.Context.IsSet方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。