// runSetAcct invokes the REST API with POST action and key prefix as // path. The specified configuration file is read from disk and sent // as the POST body. func runSetAcct(cmd *cobra.Command, args []string) { if len(args) != 2 { cmd.Usage() return } server.RunSetAcct(Context, args[0], args[1]) }
// initCoreCommonFlags initializes common flags used by Hugo core commands. func initCoreCommonFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&cfgFile, "config", "", "config file (default is path/config.yaml|json|toml)") // Set bash-completion validConfigFilenames := []string{"json", "js", "yaml", "yml", "toml", "tml"} cmd.Flags().SetAnnotation("config", cobra.BashCompFilenameExt, validConfigFilenames) }
func serverComplexFlags(ccmd *cobra.Command) { serverSimpleFlags(ccmd) ccmd.Flags().StringVarP(&server.Forwarder, "server-forwarder", "f", "g", "Forwarder method [g i m]") ccmd.Flags().IntVarP(&server.Weight, "server-weight", "w", 1, "weight of down-stream server") ccmd.Flags().IntVarP(&server.UpperThreshold, "server-upper-threshold", "u", 0, "Upper threshold of down-stream server") ccmd.Flags().IntVarP(&server.LowerThreshold, "server-lower-threshold", "l", 0, "Lower threshold of down-stream server") }
func (a *Acl) AddDestroySub(c *cobra.Command) { destroyCmd := &cobra.Command{ Use: "destroy <token>", Short: "Destroy an ACL", Long: "Destroy an ACL", RunE: func(cmd *cobra.Command, args []string) error { return a.Destroy(args) }, } oldDestroyCmd := &cobra.Command{ Use: "acl-destroy <token>", Short: "Destroy an ACL", Long: "Destroy an ACL", Deprecated: "Use acl destroy", Hidden: true, RunE: func(cmd *cobra.Command, args []string) error { return a.Destroy(args) }, } c.AddCommand(destroyCmd) a.AddCommand(oldDestroyCmd) }
func UseOptionsTemplates(cmd *cobra.Command) { cmd.SetHelpTemplate(OptionsHelpTemplate()) templater := &templater{ UsageTemplate: OptionsUsageTemplate(), } cmd.SetUsageFunc(templater.UsageFunc()) }
func GetFlagBool(cmd *cobra.Command, flag string) bool { b, err := cmd.Flags().GetBool(flag) if err != nil { glog.Fatalf("err accessing flag %s for command %s: %v", flag, cmd.Name(), err) } return b }
func GetFlagDuration(cmd *cobra.Command, flag string) time.Duration { d, err := cmd.Flags().GetDuration(flag) if err != nil { glog.Fatalf("err accessing flag %s for command %s: %v", flag, cmd.Name(), err) } return d }
// addServiceFlags adds all flags that are common to both `create` and `update`. // Any flags that are not common are added separately in the individual command func addServiceFlags(cmd *cobra.Command, opts *serviceOptions) { flags := cmd.Flags() flags.StringVar(&opts.name, flagName, "", "Service name") flags.StringVarP(&opts.workdir, flagWorkdir, "w", "", "Working directory inside the container") flags.StringVarP(&opts.user, flagUser, "u", "", "Username or UID (format: <name|uid>[:<group|gid>])") flags.StringSliceVar(&opts.groups, flagGroupAdd, []string{}, "Add additional user groups to the container") flags.Var(&opts.resources.limitCPU, flagLimitCPU, "Limit CPUs") flags.Var(&opts.resources.limitMemBytes, flagLimitMemory, "Limit Memory") flags.Var(&opts.resources.resCPU, flagReserveCPU, "Reserve CPUs") flags.Var(&opts.resources.resMemBytes, flagReserveMemory, "Reserve Memory") flags.Var(&opts.stopGrace, flagStopGracePeriod, "Time to wait before force killing a container") flags.Var(&opts.replicas, flagReplicas, "Number of tasks") flags.StringVar(&opts.restartPolicy.condition, flagRestartCondition, "", "Restart when condition is met (none, on-failure, or any)") flags.Var(&opts.restartPolicy.delay, flagRestartDelay, "Delay between restart attempts") flags.Var(&opts.restartPolicy.maxAttempts, flagRestartMaxAttempts, "Maximum number of restarts before giving up") flags.Var(&opts.restartPolicy.window, flagRestartWindow, "Window used to evaluate the restart policy") flags.Uint64Var(&opts.update.parallelism, flagUpdateParallelism, 1, "Maximum number of tasks updated simultaneously (0 to update all at once)") flags.DurationVar(&opts.update.delay, flagUpdateDelay, time.Duration(0), "Delay between updates") flags.StringVar(&opts.update.onFailure, flagUpdateFailureAction, "pause", "Action on update failure (pause|continue)") flags.StringVar(&opts.endpoint.mode, flagEndpointMode, "", "Endpoint mode (vip or dnsrr)") flags.BoolVar(&opts.registryAuth, flagRegistryAuth, false, "Send registry authentication details to swarm agents") flags.StringVar(&opts.logDriver.name, flagLogDriver, "", "Logging driver for service") flags.Var(&opts.logDriver.opts, flagLogOpt, "Logging driver options") }
// GetFlagStringList can be used to accept multiple argument with flag repetition (e.g. -f arg1 -f arg2 ...) func GetFlagStringList(cmd *cobra.Command, flag string) util.StringList { f := cmd.Flags().Lookup(flag) if f == nil { return util.StringList{} } return *f.Value.(*util.StringList) }
func runRun(cmd *cobra.Command, args []string) (exit int) { if len(args) == 0 { cmd.Usage() return 1 } if debug { stderr("Running: %v", args) } engine, ok := engines[engineName] if !ok { stderr("run: no such engine %q", engineName) return 1 } err := newACBuild().Run(args, workingdir, insecure, engine) if err != nil { stderr("run: %v", err) return getErrorCode(err) } return 0 }
// runRmPerms invokes the REST API with DELETE action and key prefix as // path. func runRmPerms(cmd *cobra.Command, args []string) { if len(args) != 1 { cmd.Usage() return } server.RunRmPerm(Context, args[0]) }
func runDeleteContext(out io.Writer, configAccess clientcmd.ConfigAccess, cmd *cobra.Command) error { config, err := configAccess.GetStartingConfig() if err != nil { return err } args := cmd.Flags().Args() if len(args) != 1 { cmd.Help() return nil } configFile := configAccess.GetDefaultFilename() if configAccess.IsExplicitFile() { configFile = configAccess.GetExplicitFile() } name := args[0] _, ok := config.Contexts[name] if !ok { return fmt.Errorf("cannot delete context %s, not in %s", name, configFile) } delete(config.Contexts, name) if err := clientcmd.ModifyConfig(configAccess, *config, true); err != nil { return err } fmt.Fprintf(out, "deleted context %s from %s", name, configFile) return nil }
func tufAdd(cmd *cobra.Command, args []string) { if len(args) < 3 { cmd.Usage() fatalf("must specify a GUN, target, and path to target data") } gun := args[0] targetName := args[1] targetPath := args[2] kdb := keys.NewDB() signer := signed.NewSigner(NewCryptoService(gun)) repo := tuf.NewTufRepo(kdb, signer) b, err := ioutil.ReadFile(targetPath) if err != nil { fatalf(err.Error()) } filestore := bootstrapRepo(gun, repo) fmt.Println("Generating metadata for target") meta, err := data.NewFileMeta(bytes.NewBuffer(b)) if err != nil { fatalf(err.Error()) } fmt.Printf("Adding target \"%s\" with sha256 \"%s\" and size %d bytes.\n", targetName, meta.Hashes["sha256"], meta.Length) _, err = repo.AddTargets("targets", data.Files{targetName: meta}) if err != nil { fatalf(err.Error()) } saveRepo(repo, filestore) }
func tufList(cmd *cobra.Command, args []string) { if len(args) < 1 { cmd.Usage() fatalf("must specify a GUN") } gun := args[0] kdb := keys.NewDB() repo := tuf.NewTufRepo(kdb, nil) remote, err := store.NewHTTPStore( "https://notary:4443/v2/"+gun+"/_trust/tuf/", "", "json", "", ) c, err := bootstrapClient(remote, repo, kdb) if err != nil { return } err = c.Update() if err != nil { logrus.Error("Error updating client: ", err.Error()) return } if rawOutput { for name, meta := range repo.Targets["targets"].Signed.Targets { fmt.Println(name, " ", meta.Hashes["sha256"], " ", meta.Length) } } else { for name, meta := range repo.Targets["targets"].Signed.Targets { fmt.Println(name, " ", meta.Hashes["sha256"], " ", meta.Length) } } }
// GetFlagStringList can be used to accept multiple argument with flag repetition (e.g. -f arg1 -f arg2 ...) func GetFlagStringSlice(cmd *cobra.Command, flag string) []string { s, err := cmd.Flags().GetStringSlice(flag) if err != nil { glog.Fatalf("err accessing flag %s for command %s: %v", flag, cmd.Name(), err) } return s }
func keysList(cmd *cobra.Command, args []string) { if len(args) > 0 { cmd.Usage() os.Exit(1) } fmt.Println("# Trusted CAs:") trustedCAs := caStore.GetCertificates() for _, c := range trustedCAs { printCert(c) } fmt.Println("") fmt.Println("# Trusted Certificates:") trustedCerts := certificateStore.GetCertificates() for _, c := range trustedCerts { printCert(c) } fmt.Println("") fmt.Println("# Signing keys: ") for _, k := range privKeyStore.ListFiles(true) { printKey(k) } }
// GetWideFlag is used to determine if "-o wide" is used func GetWideFlag(cmd *cobra.Command) bool { f := cmd.Flags().Lookup("output") if f.Value.String() == "wide" { return true } return false }
func runGenManCmd(cmd *cobra.Command, args []string) error { info := build.GetInfo() header := &doc.GenManHeader{ Section: "1", Manual: "CockroachDB Manual", Source: fmt.Sprintf("CockroachDB %s", info.Tag), } if !strings.HasSuffix(manPath, string(os.PathSeparator)) { manPath += string(os.PathSeparator) } if _, err := os.Stat(manPath); err != nil { if os.IsNotExist(err) { if err := os.MkdirAll(manPath, 0755); err != nil { return err } } else { return err } } if err := doc.GenManTree(cmd.Root(), header, manPath); err != nil { return err } // TODO(cdo): The man page generated by the cobra package doesn't include a list of commands, so // one has to notice the "See Also" section at the bottom of the page to know which commands // are supported. I'd like to make this better somehow. fmt.Println("Generated CockroachDB man pages in", manPath) return nil }
// Assumes the flag has a default value. func GetFlagInt64(cmd *cobra.Command, flag string) int64 { i, err := cmd.Flags().GetInt64(flag) if err != nil { glog.Fatalf("err accessing flag %s for command %s: %v", flag, cmd.Name(), err) } return i }
func runGenAutocompleteCmd(cmd *cobra.Command, args []string) error { if err := cmd.Root().GenBashCompletionFile(autoCompletePath); err != nil { return err } fmt.Println("Generated bash completion file", autoCompletePath) return nil }
// addServiceFlags adds all flags that are common to both `create` and `update`. // Any flags that are not common are added separately in the individual command func addServiceFlags(cmd *cobra.Command, opts *serviceOptions) { flags := cmd.Flags() flags.StringVar(&opts.name, flagName, "", "Service name") flags.VarP(&opts.labels, flagLabel, "l", "Service labels") flags.VarP(&opts.env, "env", "e", "Set environment variables") flags.StringVarP(&opts.workdir, "workdir", "w", "", "Working directory inside the container") flags.StringVarP(&opts.user, flagUser, "u", "", "Username or UID") flags.VarP(&opts.mounts, flagMount, "m", "Attach a mount to the service") flags.Var(&opts.resources.limitCPU, flagLimitCPU, "Limit CPUs") flags.Var(&opts.resources.limitMemBytes, flagLimitMemory, "Limit Memory") flags.Var(&opts.resources.resCPU, flagReserveCPU, "Reserve CPUs") flags.Var(&opts.resources.resMemBytes, flagReserveMemory, "Reserve Memory") flags.Var(&opts.stopGrace, flagStopGracePeriod, "Time to wait before force killing a container") flags.Var(&opts.replicas, flagReplicas, "Number of tasks") flags.StringVar(&opts.restartPolicy.condition, flagRestartCondition, "", "Restart when condition is met (none, on-failure, or any)") flags.Var(&opts.restartPolicy.delay, flagRestartDelay, "Delay between restart attempts") flags.Var(&opts.restartPolicy.maxAttempts, flagRestartMaxAttempts, "Maximum number of restarts before giving up") flags.Var(&opts.restartPolicy.window, flagRestartWindow, "Window used to evaluate the restart policy") flags.StringSliceVar(&opts.constraints, flagConstraint, []string{}, "Placement constraints") flags.Uint64Var(&opts.update.parallelism, flagUpdateParallelism, 0, "Maximum number of tasks updated simultaneously") flags.DurationVar(&opts.update.delay, flagUpdateDelay, time.Duration(0), "Delay between updates") flags.StringSliceVar(&opts.networks, flagNetwork, []string{}, "Network attachments") flags.StringVar(&opts.endpoint.mode, flagEndpointMode, "", "Endpoint mode (vip or dnsrr)") flags.VarP(&opts.endpoint.ports, flagPublish, "p", "Publish a port as a node port") flags.BoolVar(&opts.registryAuth, flagRegistryAuth, false, "Send registry authentication details to Swarm agents") }
// PrinterForMapping returns a printer suitable for displaying the provided resource type. // Requires that printer flags have been added to cmd (see AddPrinterFlags). func (f *Factory) PrinterForMapping(cmd *cobra.Command, mapping *meta.RESTMapping, withNamespace bool) (kubectl.ResourcePrinter, error) { printer, ok, err := PrinterForCommand(cmd) if err != nil { return nil, err } if ok { clientConfig, err := f.ClientConfig() if err != nil { return nil, err } defaultVersion := clientConfig.Version version := OutputVersion(cmd, defaultVersion) if len(version) == 0 { version = mapping.APIVersion } if len(version) == 0 { return nil, fmt.Errorf("you must specify an output-version when using this output format") } printer = kubectl.NewVersionedPrinter(printer, mapping.ObjectConvertor, version, mapping.APIVersion) } else { // Some callers do not have "label-columns" so we can't use the GetFlagStringSlice() helper columnLabel, err := cmd.Flags().GetStringSlice("label-columns") if err != nil { columnLabel = []string{} } printer, err = f.Printer(mapping, GetFlagBool(cmd, "no-headers"), withNamespace, GetWideFlag(cmd), GetFlagBool(cmd, "show-all"), columnLabel) if err != nil { return nil, err } printer = maybeWrapSortingPrinter(cmd, printer) } return printer, nil }
func (g CommandGroups) Add(c *cobra.Command) { for _, group := range g { for _, command := range group.Commands { c.AddCommand(command) } } }
func (o *AppJSONOptions) Complete(f *clientcmd.Factory, cmd *cobra.Command, args []string) error { version, _ := cmd.Flags().GetString("output-version") for _, v := range strings.Split(version, ",") { gv, err := unversioned.ParseGroupVersion(v) if err != nil { return fmt.Errorf("provided output-version %q is not valid: %v", v, err) } o.OutputVersions = append(o.OutputVersions, gv) } o.OutputVersions = append(o.OutputVersions, registered.EnabledVersions()...) o.Action.Bulk.Mapper = clientcmd.ResourceMapper(f) o.Action.Bulk.Op = configcmd.Create mapper, _ := f.Object(false) o.PrintObject = cmdutil.VersionedPrintObject(f.PrintObject, cmd, mapper, o.Action.Out) o.Generator, _ = cmd.Flags().GetString("generator") ns, _, err := f.DefaultNamespace() if err != nil { return err } o.Namespace = ns o.Client, _, err = f.Clients() return err }
// Complete verifies command line arguments and loads data from the command environment func (o *RsyncOptions) Complete(f *clientcmd.Factory, cmd *cobra.Command, args []string) error { switch n := len(args); { case n == 0: cmd.Help() fallthrough case n < 2: return kcmdutil.UsageError(cmd, "SOURCE_DIR and POD:DESTINATION_DIR are required arguments") case n > 2: return kcmdutil.UsageError(cmd, "only SOURCE_DIR and POD:DESTINATION_DIR should be specified as arguments") } // Set main command arguments var err error o.Source, err = parsePathSpec(args[0]) if err != nil { return err } o.Destination, err = parsePathSpec(args[1]) if err != nil { return err } namespace, _, err := f.DefaultNamespace() if err != nil { return err } o.Namespace = namespace o.Strategy, err = o.determineStrategy(f, cmd, o.StrategyName) if err != nil { return err } return nil }
// PrinterForCommand returns the default printer for this command. // Requires that printer flags have been added to cmd (see AddPrinterFlags). func PrinterForCommand(cmd *cobra.Command) (kubectl.ResourcePrinter, bool, error) { outputFormat := GetFlagString(cmd, "output") // templates are logically optional for specifying a format. // TODO once https://github.com/kubernetes/kubernetes/issues/12668 is fixed, this should fall back to GetFlagString templateFile, _ := cmd.Flags().GetString("template") if len(outputFormat) == 0 && len(templateFile) != 0 { outputFormat = "template" } templateFormat := []string{"go-template=", "go-template-file=", "jsonpath=", "jsonpath-file="} for _, format := range templateFormat { if strings.HasPrefix(outputFormat, format) { templateFile = outputFormat[len(format):] outputFormat = format[:len(format)-1] } } printer, generic, err := kubectl.GetPrinter(outputFormat, templateFile) if err != nil { return nil, generic, err } return maybeWrapSortingPrinter(cmd, printer), generic, nil }
func GetFlagString(cmd *cobra.Command, flag string) string { f := cmd.Flags().Lookup(flag) if f == nil { glog.Fatalf("Flag accessed but not defined for command %s: %s", cmd.Name(), flag) } return f.Value.String() }
func getFlag(cmd *cobra.Command, flag string) *pflag.Flag { f := cmd.Flags().Lookup(flag) if f == nil { glog.Fatalf("flag accessed but not defined for command %s: %s", cmd.Name(), flag) } return f }
func server(cmd *cobra.Command, args []string) { InitializeConfig() if cmd.Flags().Lookup("disableLiveReload").Changed { viper.Set("DisableLiveReload", disableLiveReload) } if serverWatch { viper.Set("Watch", true) } if viper.GetBool("watch") { serverWatch = true } l, err := net.Listen("tcp", net.JoinHostPort(serverInterface, strconv.Itoa(serverPort))) if err == nil { l.Close() } else { jww.ERROR.Println("port", serverPort, "already in use, attempting to use an available port") sp, err := helpers.FindAvailablePort() if err != nil { jww.ERROR.Println("Unable to find alternative port to use") jww.ERROR.Fatalln(err) } serverPort = sp.Port } viper.Set("port", serverPort) BaseURL, err := fixURL(BaseURL) if err != nil { jww.ERROR.Fatal(err) } viper.Set("BaseURL", BaseURL) if err := memStats(); err != nil { jww.ERROR.Println("memstats error:", err) } build(serverWatch) // Watch runs its own server as part of the routine if serverWatch { watched := getDirList() workingDir := helpers.AbsPathify(viper.GetString("WorkingDir")) for i, dir := range watched { watched[i], _ = helpers.GetRelativePath(dir, workingDir) } unique := strings.Join(helpers.RemoveSubpaths(watched), ",") jww.FEEDBACK.Printf("Watching for changes in %s/{%s}\n", workingDir, unique) err := NewWatcher(serverPort) if err != nil { fmt.Println(err) } } serve(serverPort) }
func run(cmd *cobra.Command, args []string) { p, err := pkg.ReadCaddyJSON() if err != nil { log.Fatal(err) return } if script, ok := p.Scripts[args[0]]; ok { fmt.Printf("Running script \"%s\"\n%s\n", args[0], script) fields := strings.Fields(script) cmd := exec.Command(fields[0], fields[1:]...) cmd.Env = append(os.Environ(), "GO15VENDOREXPERIMENT=1") var buf bytes.Buffer cmd.Stderr = &buf cmd.Stdout = &buf err := cmd.Run() out := buf.String() fmt.Println(out) if err != nil { fmt.Println(err) } return } }