本文整理汇总了Golang中github.com/spf13/cobra.Command.OutOrStderr方法的典型用法代码示例。如果您正苦于以下问题:Golang Command.OutOrStderr方法的具体用法?Golang Command.OutOrStderr怎么用?Golang Command.OutOrStderr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/spf13/cobra.Command
的用法示例。
在下文中一共展示了Command.OutOrStderr方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Complete
// Complete sets any default behavior for the command
func (o *NewAppOptions) Complete(commandName string, f *clientcmd.Factory, c *cobra.Command, args []string, out io.Writer) error {
o.Out = out
o.ErrOut = c.OutOrStderr()
o.Output = kcmdutil.GetFlagString(c, "output")
// Only output="" should print descriptions of intermediate steps. Everything
// else should print only some specific output (json, yaml, go-template, ...)
if len(o.Output) == 0 {
o.Config.Out = o.Out
} else {
o.Config.Out = ioutil.Discard
}
o.Config.ErrOut = o.ErrOut
o.Action.Out, o.Action.ErrOut = o.Out, o.ErrOut
o.Action.Bulk.Mapper = clientcmd.ResourceMapper(f)
o.Action.Bulk.Op = configcmd.Create
// Retry is used to support previous versions of the API server that will
// consider the presence of an unknown trigger type to be an error.
o.Action.Bulk.Retry = retryBuildConfig
o.Config.DryRun = o.Action.DryRun
o.CommandPath = c.CommandPath()
o.CommandName = commandName
mapper, _ := f.Object(false)
o.PrintObject = cmdutil.VersionedPrintObject(f.PrintObject, c, mapper, out)
o.LogsForObject = f.LogsForObject
if err := CompleteAppConfig(o.Config, f, c, args); err != nil {
return err
}
if err := setAppConfigLabels(c, o.Config); err != nil {
return err
}
return nil
}
示例2: Complete
// Complete completes any options that are required by validate or run steps.
func (opts *RegistryOptions) Complete(f *clientcmd.Factory, cmd *cobra.Command, out io.Writer, args []string) error {
if len(args) > 0 {
return kcmdutil.UsageError(cmd, "No arguments are allowed to this command")
}
opts.image = opts.Config.ImageTemplate.ExpandOrDie(opts.Config.Type)
opts.label = map[string]string{
"docker-registry": "default",
}
if opts.Config.Labels != defaultLabel {
valid, remove, err := app.LabelsFromSpec(strings.Split(opts.Config.Labels, ","))
if err != nil {
return err
}
if len(remove) > 0 {
return kcmdutil.UsageError(cmd, "You may not pass negative labels in %q", opts.Config.Labels)
}
opts.label = valid
}
opts.nodeSelector = map[string]string{}
if len(opts.Config.Selector) > 0 {
valid, remove, err := app.LabelsFromSpec(strings.Split(opts.Config.Selector, ","))
if err != nil {
return err
}
if len(remove) > 0 {
return kcmdutil.UsageError(cmd, "You may not pass negative labels in selector %q", opts.Config.Selector)
}
opts.nodeSelector = valid
}
var portsErr error
if opts.ports, portsErr = app.ContainerPortsFromString(opts.Config.Ports); portsErr != nil {
return portsErr
}
var nsErr error
if opts.namespace, _, nsErr = f.OpenShiftClientConfig.Namespace(); nsErr != nil {
return fmt.Errorf("error getting namespace: %v", nsErr)
}
var kClientErr error
if _, opts.serviceClient, kClientErr = f.Clients(); kClientErr != nil {
return fmt.Errorf("error getting client: %v", kClientErr)
}
opts.Config.Action.Bulk.Mapper = clientcmd.ResourceMapper(f)
opts.Config.Action.Out, opts.Config.Action.ErrOut = out, cmd.OutOrStderr()
opts.Config.Action.Bulk.Op = configcmd.Create
opts.out = out
opts.cmd = cmd
opts.factory = f
return nil
}
示例3: runInit
func runInit(cmd *cobra.Command, args []string) {
db, err := bolt.Open(database, 0600, nil)
if err != nil {
fmt.Fprintf(cmd.OutOrStderr(), "Could not create database: %v\n", err)
os.Exit(-1)
}
if err := db.Update(func(tx *bolt.Tx) error {
if _, err := tx.CreateBucketIfNotExists([]byte("feeds")); err != nil {
return fmt.Errorf("could not create feeds bucket: %v", err)
}
return nil
}); err != nil {
fmt.Fprintf(cmd.OutOrStderr(), "Could not initialize database: %v\n", err)
os.Exit(-1)
}
}
示例4: Run
func (options *NodeOptions) Run(c *cobra.Command, args []string) {
kcmdutil.CheckErr(options.Complete())
kcmdutil.CheckErr(options.Validate(args))
startProfiler()
if err := options.StartNode(); err != nil {
if kerrors.IsInvalid(err) {
if details := err.(*kerrors.StatusError).ErrStatus.Details; details != nil {
fmt.Fprintf(c.OutOrStderr(), "Invalid %s %s\n", details.Kind, details.Name)
for _, cause := range details.Causes {
fmt.Fprintf(c.OutOrStderr(), " %s: %s\n", cause.Field, cause.Message)
}
os.Exit(255)
}
}
glog.Fatal(err)
}
}
示例5: runAdd
func runAdd(cmd *cobra.Command, args []string) {
if feedName == "" {
fail(cmd, "--name is required.")
}
if feedURL == "" {
fail(cmd, "--url is required.")
}
db, err := bolt.Open(database, 0600, nil)
if err != nil {
fmt.Fprintf(cmd.OutOrStderr(), "Could not create database: %v\n", err)
os.Exit(-1)
}
if err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("feeds"))
if b == nil {
return fmt.Errorf("could not get feeds bucket (need to run `rss init`?)")
}
if b.Get([]byte(feedName)) != nil {
return fmt.Errorf("feed %q already exists", feedName)
}
var buf bytes.Buffer
feed := data.Feed{
Name: feedName,
URL: feedURL,
DayOfWeek: dayOfWeek,
Seconds: seconds,
}
if err := gob.NewEncoder(&buf).Encode(feed); err != nil {
return fmt.Errorf("error encoding feed configuration: %v", err)
}
if err := b.Put([]byte(feedName), buf.Bytes()); err != nil {
return fmt.Errorf("error writing feed configuration: %v", err)
}
return nil
}); err != nil {
fmt.Fprintf(cmd.OutOrStderr(), "Could not add new feed: %v\n", err)
os.Exit(-1)
}
}
示例6: Complete
func (o *StartBuildOptions) Complete(f *clientcmd.Factory, in io.Reader, out io.Writer, cmd *cobra.Command, cmdFullName string, args []string) error {
o.In = in
o.Out = out
o.ErrOut = cmd.OutOrStderr()
o.Git = git.NewRepository()
o.ClientConfig = f.OpenShiftClientConfig
o.Mapper, _ = f.Object(false)
webhook := o.FromWebhook
buildName := o.FromBuild
fromFile := o.FromFile
fromDir := o.FromDir
fromRepo := o.FromRepo
buildLogLevel := o.LogLevel
outputFormat := kcmdutil.GetFlagString(cmd, "output")
if outputFormat != "name" && outputFormat != "" {
return kcmdutil.UsageError(cmd, "Unsupported output format: %s", outputFormat)
}
o.ShortOutput = outputFormat == "name"
switch {
case len(webhook) > 0:
if len(args) > 0 || len(buildName) > 0 || len(fromFile) > 0 || len(fromDir) > 0 || len(fromRepo) > 0 {
return kcmdutil.UsageError(cmd, "The '--from-webhook' flag is incompatible with arguments and all '--from-*' flags")
}
return nil
case len(args) != 1 && len(buildName) == 0:
return kcmdutil.UsageError(cmd, "Must pass a name of a build config or specify build name with '--from-build' flag.\nUse \"%s get bc\" to list all available build configs.", cmdFullName)
}
if len(buildName) != 0 && (len(fromFile) != 0 || len(fromDir) != 0 || len(fromRepo) != 0) {
// TODO: we should support this, it should be possible to clone a build to run again with new uploaded artifacts.
// Doing so requires introducing a new clonebinary endpoint.
return kcmdutil.UsageError(cmd, "Cannot use '--from-build' flag with binary builds")
}
o.AsBinary = len(fromFile) > 0 || len(fromDir) > 0 || len(fromRepo) > 0
namespace, _, err := f.DefaultNamespace()
if err != nil {
return err
}
client, _, err := f.Clients()
if err != nil {
return err
}
o.Client = client
var (
name = buildName
resource = buildapi.Resource("builds")
)
if len(name) == 0 && len(args) > 0 && len(args[0]) > 0 {
mapper, _ := f.Object(false)
resource, name, err = cmdutil.ResolveResource(buildapi.Resource("buildconfigs"), args[0], mapper)
if err != nil {
return err
}
switch resource {
case buildapi.Resource("buildconfigs"):
// no special handling required
case buildapi.Resource("builds"):
if len(o.ListWebhooks) == 0 {
return fmt.Errorf("use --from-build to rerun your builds")
}
default:
return fmt.Errorf("invalid resource provided: %v", resource)
}
}
// when listing webhooks, allow --from-build to lookup a build config
if resource == buildapi.Resource("builds") && len(o.ListWebhooks) > 0 {
build, err := client.Builds(namespace).Get(name)
if err != nil {
return err
}
ref := build.Status.Config
if ref == nil {
return fmt.Errorf("the provided Build %q was not created from a BuildConfig and cannot have webhooks", name)
}
if len(ref.Namespace) > 0 {
namespace = ref.Namespace
}
name = ref.Name
}
if len(name) == 0 {
return fmt.Errorf("a resource name is required either as an argument or by using --from-build")
}
o.Namespace = namespace
o.Name = name
env, _, err := cmdutil.ParseEnv(o.Env, in)
if err != nil {
return err
}
if len(buildLogLevel) > 0 {
//.........这里部分代码省略.........
示例7: Complete
// Complete completes all the required options.
func (o *CancelBuildOptions) Complete(f *clientcmd.Factory, cmd *cobra.Command, args []string, in io.Reader, out io.Writer) error {
o.In = in
o.Out = out
o.ErrOut = cmd.OutOrStderr()
o.ReportError = func(err error) {
o.HasError = true
fmt.Fprintf(o.ErrOut, "error: %s\n", err.Error())
}
if len(args) == 0 {
return kcmdutil.UsageError(cmd, "Must pass a name of a build or a buildconfig to cancel")
}
namespace, _, err := f.DefaultNamespace()
if err != nil {
return err
}
if len(o.States) == 0 {
// If --state is not specified, set the default to "new", "pending" and
// "running".
o.States = []string{"new", "pending", "running"}
} else {
for _, state := range o.States {
if len(state) > 0 && !isStateCancellable(state) {
return kcmdutil.UsageError(cmd, "The '--state' flag has invalid value. Must be one of 'new', 'pending', or 'running'")
}
}
}
client, _, err := f.Clients()
if err != nil {
return err
}
o.Namespace = namespace
o.Client = client
o.BuildLister = buildclient.NewOSClientBuildClient(client)
o.BuildClient = client.Builds(namespace)
o.Mapper, _ = f.Object(false)
for _, item := range args {
resource, name, err := cmdutil.ResolveResource(buildapi.Resource("builds"), item, o.Mapper)
if err != nil {
return err
}
switch resource {
case buildapi.Resource("buildconfigs"):
list, err := buildutil.BuildConfigBuilds(o.BuildLister, o.Namespace, name, nil)
if err != nil {
return err
}
for _, b := range list.Items {
o.BuildNames = append(o.BuildNames, b.Name)
}
case buildapi.Resource("builds"):
o.BuildNames = append(o.BuildNames, strings.TrimSpace(name))
default:
return fmt.Errorf("invalid resource provided: %v", resource)
}
}
return nil
}
示例8: RunCmdRouter
// RunCmdRouter contains all the necessary functionality for the
// OpenShift CLI router command.
func RunCmdRouter(f *clientcmd.Factory, cmd *cobra.Command, out io.Writer, cfg *RouterConfig, args []string) error {
switch len(args) {
case 0:
// uses default value
case 1:
cfg.Name = args[0]
default:
return kcmdutil.UsageError(cmd, "You may pass zero or one arguments to provide a name for the router")
}
name := cfg.Name
var defaultOutputErr error
if len(cfg.StatsUsername) > 0 {
if strings.Contains(cfg.StatsUsername, ":") {
return kcmdutil.UsageError(cmd, "username %s must not contain ':'", cfg.StatsUsername)
}
}
if len(cfg.Subdomain) > 0 && len(cfg.ForceSubdomain) > 0 {
return kcmdutil.UsageError(cmd, "only one of --subdomain, --force-subdomain can be specified")
}
ports, err := app.ContainerPortsFromString(cfg.Ports)
if err != nil {
return fmt.Errorf("unable to parse --ports: %v", err)
}
// HostNetwork overrides HostPorts
if cfg.HostNetwork {
cfg.HostPorts = false
}
// For the host networking case, ensure the ports match.
if cfg.HostNetwork {
for i := 0; i < len(ports); i++ {
if ports[i].HostPort != 0 && ports[i].ContainerPort != ports[i].HostPort {
return fmt.Errorf("when using host networking mode, container port %d and host port %d must be equal", ports[i].ContainerPort, ports[i].HostPort)
}
}
}
if cfg.StatsPort > 0 {
port := kapi.ContainerPort{
Name: "stats",
ContainerPort: int32(cfg.StatsPort),
Protocol: kapi.ProtocolTCP,
}
if cfg.HostPorts {
port.HostPort = int32(cfg.StatsPort)
}
ports = append(ports, port)
}
label := map[string]string{"router": name}
if cfg.Labels != defaultLabel {
valid, remove, err := app.LabelsFromSpec(strings.Split(cfg.Labels, ","))
if err != nil {
glog.Fatal(err)
}
if len(remove) > 0 {
return kcmdutil.UsageError(cmd, "You may not pass negative labels in %q", cfg.Labels)
}
label = valid
}
nodeSelector := map[string]string{}
if len(cfg.Selector) > 0 {
valid, remove, err := app.LabelsFromSpec(strings.Split(cfg.Selector, ","))
if err != nil {
glog.Fatal(err)
}
if len(remove) > 0 {
return kcmdutil.UsageError(cmd, "You may not pass negative labels in selector %q", cfg.Selector)
}
nodeSelector = valid
}
image := cfg.ImageTemplate.ExpandOrDie(cfg.Type)
namespace, _, err := f.OpenShiftClientConfig.Namespace()
if err != nil {
return fmt.Errorf("error getting client: %v", err)
}
_, kClient, err := f.Clients()
if err != nil {
return fmt.Errorf("error getting client: %v", err)
}
cfg.Action.Bulk.Mapper = clientcmd.ResourceMapper(f)
cfg.Action.Out, cfg.Action.ErrOut = out, cmd.OutOrStderr()
cfg.Action.Bulk.Op = configcmd.Create
var clusterIP string
output := cfg.Action.ShouldPrint()
generate := output
if !generate {
//.........这里部分代码省略.........
示例9: fail
func fail(cmd *cobra.Command, msg string) {
fmt.Fprintf(cmd.OutOrStderr(), "%s\n\n", msg)
cmd.Usage()
os.Exit(-1)
}
示例10: RunEnv
//.........这里部分代码省略.........
return err
}
// only apply resource version locking on a single resource
if !one && len(resourceVersion) > 0 {
return kcmdutil.UsageError(cmd, "--resource-version may only be used with a single resource")
}
// Keep a copy of the original objects prior to updating their environment.
// Used in constructing the patch(es) that will be applied in the server.
gv := *clientConfig.GroupVersion
oldObjects, err := resource.AsVersionedObjects(infos, gv, kapi.Codecs.LegacyCodec(gv))
if err != nil {
return err
}
if len(oldObjects) != len(infos) {
return fmt.Errorf("could not convert all objects to API version %q", clientConfig.GroupVersion)
}
oldData := make([][]byte, len(infos))
for i := range oldObjects {
old, err := json.Marshal(oldObjects[i])
if err != nil {
return err
}
oldData[i] = old
}
skipped := 0
errored := []*resource.Info{}
for _, info := range infos {
ok, err := f.UpdatePodSpecForObject(info.Object, func(spec *kapi.PodSpec) error {
resolutionErrorsEncountered := false
containers, _ := selectContainers(spec.Containers, containerMatch)
if len(containers) == 0 {
fmt.Fprintf(cmd.OutOrStderr(), "warning: %s/%s does not have any containers matching %q\n", info.Mapping.Resource, info.Name, containerMatch)
return nil
}
for _, c := range containers {
if !overwrite {
if err := validateNoOverwrites(c.Env, env); err != nil {
errored = append(errored, info)
return err
}
}
c.Env = updateEnv(c.Env, env, remove)
if list {
resolveErrors := map[string][]string{}
store := newResourceStore()
fmt.Fprintf(out, "# %s %s, container %s\n", info.Mapping.Resource, info.Name, c.Name)
for _, env := range c.Env {
// Print the simple value
if env.ValueFrom == nil {
fmt.Fprintf(out, "%s=%s\n", env.Name, env.Value)
continue
}
// Print the reference version
if !resolve {
fmt.Fprintf(out, "# %s from %s\n", env.Name, getEnvVarRefString(env.ValueFrom))
continue
}
value, err := getEnvVarRefValue(f, store, env.ValueFrom, info.Object, c)
// Print the resolved value