本文整理汇总了Golang中github.com/spf13/cobra.Command.Flag方法的典型用法代码示例。如果您正苦于以下问题:Golang Command.Flag方法的具体用法?Golang Command.Flag怎么用?Golang Command.Flag使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/spf13/cobra.Command
的用法示例。
在下文中一共展示了Command.Flag方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: startHoarder
func startHoarder(ccmd *cobra.Command, args []string) error {
// convert the log level
logLvl := lumber.LvlInt(viper.GetString("log-level"))
// configure the logger
lumber.Prefix("[hoader]")
lumber.Level(logLvl)
// enable/start garbage collection if age config was changed
if ccmd.Flag("clean-after").Changed {
lumber.Debug("Starting garbage collector (data older than %vs)...\n", ccmd.Flag("clean-after").Value)
// start garbage collector
go collector.Start()
}
// set, and initialize, the backend driver
if err := backends.Initialize(); err != nil {
lumber.Error("Failed to initialize backend - %v", err)
return err
}
// start the API
if err := api.Start(); err != nil {
lumber.Fatal("Failed to start API: ", err.Error())
return err
}
return nil
}
示例2: generate
func generate(pkgName, pkgPath string, c *cobra.Command) ([]string, error) {
m := make(map[string]string)
c.Flags().Visit(func(f *pflag.Flag) {
if f.Name != "pkg-path" {
m[f.Name] = f.Value.String()
}
})
if _, ok := m["out"]; !ok {
m["out"] = c.Flag("out").DefValue
}
// turn "out" into an absolute path
var err error
m["out"], err = filepath.Abs(m["out"])
if err != nil {
return nil, err
}
gen, err := meta.NewGenerator(
pkgName+".Generate",
[]*codegen.ImportSpec{codegen.SimpleImport(pkgPath)},
m,
)
if err != nil {
return nil, err
}
return gen.Generate()
}
示例3: Complete
// Complete turns a partially defined TopImagesOptions into a solvent structure
// which can be validated and used for showing limits usage.
func (o *TopImagesOptions) Complete(f *clientcmd.Factory, cmd *cobra.Command, args []string, out io.Writer) error {
osClient, kClient, err := f.Clients()
if err != nil {
return err
}
namespace := cmd.Flag("namespace").Value.String()
if len(namespace) == 0 {
namespace = kapi.NamespaceAll
}
o.out = out
allImages, err := osClient.Images().List(kapi.ListOptions{})
if err != nil {
return err
}
o.Images = allImages
allStreams, err := osClient.ImageStreams(namespace).List(kapi.ListOptions{})
if err != nil {
return err
}
o.Streams = allStreams
allPods, err := kClient.Pods(namespace).List(kapi.ListOptions{})
if err != nil {
return err
}
o.Pods = allPods
return nil
}
示例4: Restore
// Restore loads the arguments from disk and prefills the Request
func Restore(config *api.Config, cmd *cobra.Command) {
data, err := ioutil.ReadFile(DefaultConfigPath)
if err != nil {
data, err = ioutil.ReadFile(".stifile")
if err != nil {
glog.V(1).Infof("Unable to restore %s: %v", DefaultConfigPath, err)
return
}
glog.Infof("DEPRECATED: Use %s instead of .stifile", DefaultConfigPath)
}
c := Config{}
if err := json.Unmarshal(data, &c); err != nil {
glog.V(1).Infof("Unable to parse %s: %v", DefaultConfigPath, err)
return
}
config.BuilderImage = c.BuilderImage
config.Source = c.Source
config.Tag = c.Tag
for name, value := range c.Flags {
// Do not change flags that user sets. Allow overriding of stored flags.
if cmd.Flag(name).Changed {
continue
}
cmd.Flags().Set(name, value)
}
}
示例5: mustLoadConfig
func mustLoadConfig(cmd *cobra.Command) {
home := os.Getenv("HOME")
if home == "" {
home = os.Getenv("USERPROFILE")
}
if home == "" {
log.Fatalf("Unable to locate home directory, giving up\n")
}
configFile := filepath.Join(home, perUserDotFile)
if raw, err := ioutil.ReadFile(configFile); err != nil {
log.Fatalf("Unable to load config file; try running \"grind init\"\n")
} else if err := json.Unmarshal(raw, &Config); err != nil {
log.Printf("failed to parse %s: %v", configFile, err)
log.Fatalf("you may wish to try deleting the file and running \"grind init\" again\n")
}
if cmd.Flag("api").Value.String() == "true" {
Config.apiReport = true
}
if cmd.Flag("api-dump").Value.String() == "true" {
Config.apiReport = true
Config.apiDump = true
}
checkVersion()
}
示例6: connect
func connect(cmd *cobra.Command) (*http.Client, error) {
url := cmd.Flag("registry").Value.String()
// XXX construct client using TLS
client := &http.Client{Transport: &http.Transport{}}
resp, err := client.Get(url + "/v2/")
if err != nil {
return nil, err
}
defer resp.Body.Close()
switch resp.StatusCode {
case http.StatusUnauthorized:
// error text in resp.Body
return nil, errors.New("take action based on WWW-Authenticate")
case http.StatusNotFound:
return nil, errors.New("registry does not support v2 API")
case http.StatusOK:
break
default:
return nil, fmt.Errorf("bad status (%s/v2/) %d", url, resp.StatusCode)
}
// consume body so connection can be reused
ioutil.ReadAll(resp.Body)
ver := resp.Header.Get("Docker-Distribution-API-Version")
if ver != "registry/2.0" {
return nil, errors.New("registry does not support v2 API")
}
return client, nil
}
示例7: Complete
func (o *LogsOptions) Complete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error {
containerName := cmdutil.GetFlagString(cmd, "container")
switch len(args) {
case 0:
return cmdutil.UsageError(cmd, "POD is required for logs")
case 1:
o.ResourceArg = args[0]
case 2:
if cmd.Flag("container").Changed {
return cmdutil.UsageError(cmd, "only one of -c, [CONTAINER] arg is allowed")
}
o.ResourceArg = args[0]
containerName = args[1]
default:
return cmdutil.UsageError(cmd, "logs POD [-c CONTAINER]")
}
var err error
o.Namespace, _, err = f.DefaultNamespace()
if err != nil {
return err
}
logOptions := &api.PodLogOptions{
Container: containerName,
Follow: cmdutil.GetFlagBool(cmd, "follow"),
Previous: cmdutil.GetFlagBool(cmd, "previous"),
Timestamps: cmdutil.GetFlagBool(cmd, "timestamps"),
}
if sinceTime := cmdutil.GetFlagString(cmd, "since-time"); len(sinceTime) > 0 {
t, err := api.ParseRFC3339(sinceTime, unversioned.Now)
if err != nil {
return err
}
logOptions.SinceTime = &t
}
if limit := cmdutil.GetFlagInt64(cmd, "limit-bytes"); limit != 0 {
logOptions.LimitBytes = &limit
}
if tail := cmdutil.GetFlagInt64(cmd, "tail"); tail != -1 {
logOptions.TailLines = &tail
}
if sinceSeconds := cmdutil.GetFlagDuration(cmd, "since"); sinceSeconds != 0 {
// round up to the nearest second
sec := int64(math.Ceil(float64(sinceSeconds) / float64(time.Second)))
logOptions.SinceSeconds = &sec
}
o.Options = logOptions
o.Mapper, o.Typer = f.Object()
o.Decoder = f.Decoder(true)
o.ClientMapper = resource.ClientMapperFunc(f.ClientForMapping)
o.LogsForObject = f.LogsForObject
o.Out = out
return nil
}
示例8: testFlag
func testFlag(cmd *cobra.Command, flagName string, defaultVal string, t *testing.T) {
f := cmd.Flag(flagName)
if f == nil {
t.Fatalf("expected flag %s to be registered but found none", flagName)
}
if f.DefValue != defaultVal {
t.Errorf("expected default value of %s for %s but found %s", defaultVal, flagName, f.DefValue)
}
}
示例9: globalFlags
func globalFlags(cmd *cobra.Command) {
if verbose {
logrus.SetLevel(logrus.DebugLevel)
}
if cmd.Flag("driver").Changed {
driver = cmd.Flag("driver").Value.String()
} else {
driver = os.Getenv("DOCKER_GRAPHDRIVER")
}
}
示例10: globalFlags
func (c *CLI) globalFlags(cmd *cobra.Command) *flag.FlagSet {
fs := &flag.FlagSet{}
if cmd.HasParent() {
fs.AddFlagSet(cmd.InheritedFlags())
if fs.Lookup("help") == nil && cmd.Flag("help") != nil {
fs.AddFlag(cmd.Flag("help"))
}
} else {
fs.AddFlagSet(cmd.PersistentFlags())
}
return c.sansDriverFlags(c.sansAdditionalFlags(fs))
}
示例11: runGen
func runGen(c *cobra.Command) ([]string, error) {
pkgPath := c.Flag("pkg-path").Value.String()
pkgSrcPath, err := codegen.PackageSourcePath(pkgPath)
if err != nil {
return nil, fmt.Errorf("invalid plugin package import path: %s", err)
}
pkgName, err := codegen.PackageName(pkgSrcPath)
if err != nil {
return nil, fmt.Errorf("invalid plugin package import path: %s", err)
}
return generate(pkgName, pkgPath, c)
}
示例12: getIncludeExcludeArgs
func getIncludeExcludeArgs(cmd *cobra.Command) (include, exclude *string) {
includeFlag := cmd.Flag("include")
excludeFlag := cmd.Flag("exclude")
if includeFlag.Changed {
include = &includeArg
}
if excludeFlag.Changed {
exclude = &excludeArg
}
return
}
示例13: delete
func delete(cmd *cobra.Command, args []string) {
url := cmd.Flag("registry").Value.String()
if len(args) != 1 {
cmd.UsageFunc()(cmd)
return
}
delimg := args[0]
conn, err := connect(cmd)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
images, err := catalog(conn, url)
for _, name := range images {
tags, err := tags(conn, url, name)
if err != nil {
fmt.Fprintln(os.Stderr, err)
continue
}
for _, tag := range tags {
if strings.Compare(delimg, name+":"+tag) == 0 {
digest, _, err := manifest(conn, url, name, tag)
if err != nil {
fmt.Fprintf(os.Stderr, "manifest: %v\n", err)
return
}
err = deleteImage(conn, url, name, digest)
if err != nil {
fmt.Fprintf(os.Stderr, "delete: %v\n", err)
return
}
fmt.Printf("deleted %s:%s\n", name, tag)
return
}
}
}
}
示例14: ValidOperation
func ValidOperation(c *cobra.Command) error {
numOps := 0
if c.Flag("schedulable").Changed {
numOps++
}
if evacuate {
numOps++
}
if listpods {
numOps++
}
if numOps == 0 {
return errors.New("must provide a node operation. Supported operations: --schedulable, --evacuate and --list-pods")
} else if numOps != 1 {
return errors.New("must provide only one node operation at a time")
}
return nil
}
示例15: Complete
func (o *LogsOptions) Complete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error {
switch len(args) {
case 0:
return cmdutil.UsageError(cmd, "POD is required for log")
case 1:
o.PodName = args[0]
case 2:
if cmd.Flag("container").Changed {
return cmdutil.UsageError(cmd, "only one of -c, [CONTAINER] arg is allowed")
}
o.PodName = args[0]
o.ContainerName = args[1]
default:
return cmdutil.UsageError(cmd, "log POD [-c CONTAINER]")
}
var err error
o.PodNamespace, _, err = f.DefaultNamespace()
if err != nil {
return err
}
o.Client, err = f.Client()
if err != nil {
return err
}
sinceTime := cmdutil.GetFlagString(cmd, "since-time")
if len(sinceTime) > 0 {
t, err := api.ParseRFC3339(sinceTime, unversioned.Now)
if err != nil {
return err
}
o.SinceTime = &t
}
return nil
}