// NewAttachCommand creates a new cobra.Command for `docker attach`
512406
func NewAttachCommand(dockerCli command.Cli) *cobra.Command {
	var opts attachOptions

	cmd := &cobra.Command{
		Use:   "attach [OPTIONS] CONTAINER",
		Short: "Attach local standard input, output, and error streams to a running container",
		Args:  cli.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			opts.container = args[0]
			return runAttach(dockerCli, &opts)
		},
	}

	flags := cmd.Flags()
	flags.BoolVar(&opts.noStdin, "no-stdin", false, "Do not attach STDIN")
	flags.BoolVar(&opts.proxy, "sig-proxy", true, "Proxy all received signals to the process")
	flags.StringVar(&opts.detachKeys, "detach-keys", "", "Override the key sequence for detaching a container")
	return cmd
}
523651
func NewSetAutoAttachArgs(autoAttach bool, waitForDebuggerOnStart bool) *SetAutoAttachArgs {
	args := new(SetAutoAttachArgs)
	args.AutoAttach = autoAttach
	args.WaitForDebuggerOnStart = waitForDebuggerOnStart
	return args
}
810623
func NewPullCommand(dockerCli command.Cli) *cobra.Command {
	var opts PullOptions

	cmd := &cobra.Command{
		Use:   "pull [OPTIONS] NAME[:TAG|@DIGEST]",
		Short: "Pull an image or a repository from a registry",
		Args:  cli.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			opts.remote = args[0]
			return RunPull(dockerCli, opts)
		},
	}

	flags := cmd.Flags()

	flags.BoolVarP(&opts.all, "all-tags", "a", false, "Download all tagged images in the repository")
	flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Suppress verbose output")

	command.AddPlatformFlag(flags, &opts.platform)
	command.AddTrustVerificationFlags(flags, &opts.untrusted, dockerCli.ContentTrustEnabled())

	return cmd
}
394635
func NewCommand(name string, runFn func(*cobra.Command, []string)) *cobra.Command {
	return &cobra.Command{Use: name, Run: runFn, PreRun: setupHTTPLogger}
}
1001961
func NewMetadataCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "metadata",
		Short: "Extract RETS metadata",
		Run:   metadata,
	}
	cmd.Flags().String(mTypeFlag, "METADATA-SYSTEM", "The type of metadata requested")
	cmd.Flags().String(mFormatFlag, "COMPACT", "Metadata format")
	cmd.Flags().String(mIDFlag, "*", "Metadata identifier")
	return cmd
}
719993
func NewRepoAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
	var (
		repo                  appsv1.Repository
		upsert                bool
		sshPrivateKeyPath     string
		insecureIgnoreHostKey bool
	)
	var command = &cobra.Command{
		Use:   "add REPO",
		Short: "Add git repository credentials",
		Run: func(c *cobra.Command, args []string) {
			if len(args) != 1 {
				c.HelpFunc()(c, args)
				os.Exit(1)
			}
			repo.Repo = args[0]
			if sshPrivateKeyPath != "" {
				keyData, err := ioutil.ReadFile(sshPrivateKeyPath)
				if err != nil {
					log.Fatal(err)
				}
				repo.SSHPrivateKey = string(keyData)
			}
			repo.InsecureIgnoreHostKey = insecureIgnoreHostKey
			// First test the repo *without* username/password. This gives us a hint on whether this
			// is a private repo.
			// NOTE: it is important not to run git commands to test git credentials on the user's
			// system since it may mess with their git credential store (e.g. osx keychain).
			// See issue #315
			err := git.TestRepo(repo.Repo, "", "", repo.SSHPrivateKey, repo.InsecureIgnoreHostKey)
			if err != nil {
				if git.IsSSHURL(repo.Repo) {
					// If we failed using git SSH credentials, then the repo is automatically bad
					log.Fatal(err)
				}
				// If we can't test the repo, it's probably private. Prompt for credentials and
				// let the server test it.
				repo.Username, repo.Password = cli.PromptCredentials(repo.Username, repo.Password)
			}
			conn, repoIf := argocdclient.NewClientOrDie(clientOpts).NewRepoClientOrDie()
			defer util.Close(conn)
			repoCreateReq := repository.RepoCreateRequest{
				Repo:   &repo,
				Upsert: upsert,
			}
			createdRepo, err := repoIf.Create(context.Background(), &repoCreateReq)
			errors.CheckError(err)
			fmt.Printf("repository '%s' added\n", createdRepo.Repo)
		},
	}
	command.Flags().StringVar(&repo.Username, "username", "", "username to the repository")
	command.Flags().StringVar(&repo.Password, "password", "", "password to the repository")
	command.Flags().StringVar(&sshPrivateKeyPath, "ssh-private-key-path", "", "path to the private ssh key (e.g. ~/.ssh/id_rsa)")
	command.Flags().BoolVar(&insecureIgnoreHostKey, "insecure-ignore-host-key", false, "disables SSH strict host key checking")
	command.Flags().BoolVar(&upsert, "upsert", false, "Override an existing repository with the same name even if the spec differs")
	return command
}
774479
func NewAttachToTargetArgs(targetID ID) *AttachToTargetArgs {
	args := new(AttachToTargetArgs)
	args.TargetID = targetID
	return args
}
451035
func NewCommand(name string, args ...interface{}) *Command {
	return &Command{
		name: strings.TrimSpace(name),
		args: args,
	}
}
603539
func NewUpdateCommand(dockerCli command.Cli) *cobra.Command {
	var options updateOptions

	cmd := &cobra.Command{
		Use:   "update [OPTIONS] CONTAINER [CONTAINER...]",
		Short: "Update configuration of one or more containers",
		Args:  cli.RequiresMinArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			options.containers = args
			options.nFlag = cmd.Flags().NFlag()
			return runUpdate(dockerCli, &options)
		},
	}

	flags := cmd.Flags()
	flags.Uint16Var(&options.blkioWeight, "blkio-weight", 0, "Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)")
	flags.Int64Var(&options.cpuPeriod, "cpu-period", 0, "Limit CPU CFS (Completely Fair Scheduler) period")
	flags.Int64Var(&options.cpuQuota, "cpu-quota", 0, "Limit CPU CFS (Completely Fair Scheduler) quota")
	flags.Int64Var(&options.cpuRealtimePeriod, "cpu-rt-period", 0, "Limit the CPU real-time period in microseconds")
	flags.SetAnnotation("cpu-rt-period", "version", []string{"1.25"})
	flags.Int64Var(&options.cpuRealtimeRuntime, "cpu-rt-runtime", 0, "Limit the CPU real-time runtime in microseconds")
	flags.SetAnnotation("cpu-rt-runtime", "version", []string{"1.25"})
	flags.StringVar(&options.cpusetCpus, "cpuset-cpus", "", "CPUs in which to allow execution (0-3, 0,1)")
	flags.StringVar(&options.cpusetMems, "cpuset-mems", "", "MEMs in which to allow execution (0-3, 0,1)")
	flags.Int64VarP(&options.cpuShares, "cpu-shares", "c", 0, "CPU shares (relative weight)")
	flags.VarP(&options.memory, "memory", "m", "Memory limit")
	flags.Var(&options.memoryReservation, "memory-reservation", "Memory soft limit")
	flags.Var(&options.memorySwap, "memory-swap", "Swap limit equal to memory plus swap: '-1' to enable unlimited swap")
	flags.Var(&options.kernelMemory, "kernel-memory", "Kernel memory limit")
	flags.StringVar(&options.restartPolicy, "restart", "", "Restart policy to apply when a container exits")
	flags.Int64Var(&options.pidsLimit, "pids-limit", 0, "Tune container pids limit (set -1 for unlimited)")
	flags.SetAnnotation("pids-limit", "version", []string{"1.40"})

	flags.Var(&options.cpus, "cpus", "Number of CPUs")
	flags.SetAnnotation("cpus", "version", []string{"1.29"})

	return cmd
}
133404
func newCommand(cmdName string, cmdArgs []string, cli *client.Client) (command, error) {
	switch cmdName {
	case cmdNameConn:
		return newCommandConn(cmdArgs, cli)
	case cmdNameDisconn:
		return newCommandDisconn(cli), nil
	case cmdNameHelp:
		return newCommandHelp(), nil
	case cmdNamePub:
		return newCommandPub(cmdArgs, cli)
	case cmdNameQuit:
		return newCommandQuit(cli), nil
	case cmdNameSub:
		return newCommandSub(cmdArgs, cli)
	case cmdNameUnsub:
		return newCommandUnsub(cmdArgs, cli)
	}

	return nil, errInvalidCmdName
}
57254
func NewAddCredentialCommand() cmd.Command {
	return &addCredentialCommand{
		store:           jujuclient.NewFileCredentialStore(),
		cloudByNameFunc: jujucloud.CloudByName,
	}
}
251339
func NewAttachStorageCommandWithAPI() cmd.Command {
	cmd := &attachStorageCommand{}
	cmd.newEntityAttacherCloser = func() (EntityAttacherCloser, error) {
		return cmd.NewStorageAPI()
	}
	return modelcmd.Wrap(cmd)
}
1010121
func NewCmdBuild(cfg *api.Config) *cobra.Command {
	var ref string
	useConfig := false
	oldScriptsFlag := ""
	oldDestination := ""

	var networkMode string

	buildCmd := &cobra.Command{
		Use:   "build <source> <image> [<tag>]",
		Short: "Build a new image",
		Long:  "Build a new Docker image named <tag> (if provided) from a source repository and base image.",
		Example: `
# Build a Docker image from a remote Git repository
$ s2i build https://github.com/openshift/ruby-hello-world centos/ruby-22-centos7 hello-world-app

# Build from a local directory.  If this directory is a git repo then the current commit will be built.
$ s2i build . centos/ruby-22-centos7 hello-world-app
`,
		Run: func(cmd *cobra.Command, args []string) {
			glog.V(1).Infof("Running S2I version %q\n", version.Get())

			// Attempt to restore the build command from the configuration file
			if useConfig {
				config.Restore(cfg, cmd)
			}

			// If user specifies the arguments, then we override the stored ones
			if len(args) >= 2 {
				source, err := git.Parse(args[0])
				if err != nil {
					fmt.Fprintf(os.Stderr, "ERROR: couldn't parse %q: %v\n", args[0], err)
					return
				}
				cfg.Source = source
				cfg.Source.URL.Fragment = ref
				cfg.BuilderImage = args[1]
				if len(args) >= 3 {
					cfg.Tag = args[2]
				}
			}

			if len(cfg.AsDockerfile) > 0 {
				if cfg.RunImage {
					fmt.Fprintln(os.Stderr, "ERROR: --run cannot be used with --as-dockerfile")
					return
				}
				if len(cfg.RuntimeImage) > 0 {
					fmt.Fprintln(os.Stderr, "ERROR: --runtime-image cannot be used with --as-dockerfile")
					return
				}
			}

			if cfg.Incremental && len(cfg.RuntimeImage) > 0 {
				fmt.Fprintln(os.Stderr, "ERROR: Incremental build with runtime image isn't supported")
				return
			}
			//set default image pull policy
			if len(cfg.BuilderPullPolicy) == 0 {
				cfg.BuilderPullPolicy = api.DefaultBuilderPullPolicy
			}
			if len(cfg.PreviousImagePullPolicy) == 0 {
				cfg.PreviousImagePullPolicy = api.DefaultPreviousImagePullPolicy
			}
			if len(cfg.RuntimeImagePullPolicy) == 0 {
				cfg.RuntimeImagePullPolicy = api.DefaultRuntimeImagePullPolicy
			}

			if errs := validation.ValidateConfig(cfg); len(errs) > 0 {
				for _, e := range errs {
					fmt.Fprintf(os.Stderr, "ERROR: %s\n", e)
				}
				fmt.Println()
				cmd.Help()
				return
			}

			// Persists the current command line options and config into .s2ifile
			if useConfig {
				config.Save(cfg, cmd)
			}

			// Attempt to read the .dockercfg and extract the authentication for
			// docker pull
			if r, err := os.Open(cfg.DockerCfgPath); err == nil {
				defer r.Close()
				auths := docker.LoadImageRegistryAuth(r)
				cfg.PullAuthentication = docker.GetImageRegistryAuth(auths, cfg.BuilderImage)
				if cfg.Incremental {
					cfg.IncrementalAuthentication = docker.GetImageRegistryAuth(auths, cfg.Tag)
				}
				if len(cfg.RuntimeImage) > 0 {
					cfg.RuntimeAuthentication = docker.GetImageRegistryAuth(auths, cfg.RuntimeImage)
				}
			}

			if len(cfg.EnvironmentFile) > 0 {
				result, err := util.ReadEnvironmentFile(cfg.EnvironmentFile)
				if err != nil {
					glog.Warningf("Unable to read environment file %q: %v", cfg.EnvironmentFile, err)
				} else {
					for name, value := range result {
						cfg.Environment = append(cfg.Environment, api.EnvironmentSpec{Name: name, Value: value})
					}
				}
			}

			if len(oldScriptsFlag) != 0 {
				glog.Warning("DEPRECATED: Flag --scripts is deprecated, use --scripts-url instead")
				cfg.ScriptsURL = oldScriptsFlag
			}
			if len(oldDestination) != 0 {
				glog.Warning("DEPRECATED: Flag --location is deprecated, use --destination instead")
				cfg.Destination = oldDestination
			}

			if networkMode != "" {
				cfg.DockerNetworkMode = api.DockerNetworkMode(networkMode)
			}

			client, err := docker.NewEngineAPIClient(cfg.DockerConfig)
			if err != nil {
				glog.Fatal(err)
			}

			if len(cfg.AsDockerfile) == 0 {
				d := docker.New(client, cfg.PullAuthentication)
				err := d.CheckReachable()
				if err != nil {
					glog.Fatal(err)
				}
			}

			glog.V(2).Infof("\n%s\n", describe.Config(client, cfg))

			builder, _, err := strategies.GetStrategy(client, cfg)
			s2ierr.CheckError(err)
			result, err := builder.Build(cfg)
			if err != nil {
				glog.V(0).Infof("Build failed")
				s2ierr.CheckError(err)
			} else {
				if len(cfg.AsDockerfile) > 0 {
					glog.V(0).Infof("Application dockerfile generated in %s", cfg.AsDockerfile)
				} else {
					glog.V(0).Infof("Build completed successfully")

				}
			}

			for _, message := range result.Messages {
				glog.V(1).Infof(message)
			}

			if cfg.RunImage {
				runner := run.New(client, cfg)
				err = runner.Run(cfg)
				s2ierr.CheckError(err)
			}
		},
	}

	cmdutil.AddCommonFlags(buildCmd, cfg)

	buildCmd.Flags().BoolVar(&(cfg.RunImage), "run", false, "Run resulting image as part of invocation of this command")
	buildCmd.Flags().BoolVar(&(cfg.IgnoreSubmodules), "ignore-submodules", false, "Ignore all git submodules when cloning application repository")
	buildCmd.Flags().VarP(&(cfg.Environment), "env", "e", "Specify an single environment variable in NAME=VALUE format")
	buildCmd.Flags().StringVarP(&(ref), "ref", "r", "", "Specify a ref to check-out")
	buildCmd.Flags().StringVarP(&(cfg.AssembleUser), "assemble-user", "", "", "Specify the user to run assemble with")
	buildCmd.Flags().StringVarP(&(cfg.AssembleRuntimeUser), "assemble-runtime-user", "", "", "Specify the user to run assemble-runtime with")
	buildCmd.Flags().StringVarP(&(cfg.ContextDir), "context-dir", "", "", "Specify the sub-directory inside the repository with the application sources")
	buildCmd.Flags().StringVarP(&(cfg.ExcludeRegExp), "exclude", "", tar.DefaultExclusionPattern.String(), "Regular expression for selecting files from the source tree to exclude from the build, where the default excludes the '.git' directory (see https://golang.org/pkg/regexp for syntax, but note that \"\" will be interpreted as allow all files and exclude no files)")
	buildCmd.Flags().StringVar(&(cfg.ImageScriptsURL), "image-scripts-url", "image:///usr/libexec/s2i", "Specify a URL containing the default assemble and run scripts for the builder image")
	buildCmd.Flags().StringVarP(&(cfg.ScriptsURL), "scripts-url", "s", "", "Specify a URL for the assemble, assemble-runtime and run scripts")
	buildCmd.Flags().StringVar(&(oldScriptsFlag), "scripts", "", "DEPRECATED: Specify a URL for the assemble and run scripts")
	buildCmd.Flags().BoolVar(&(useConfig), "use-config", false, "Store command line options to .s2ifile")
	buildCmd.Flags().StringVarP(&(cfg.EnvironmentFile), "environment-file", "E", "", "Specify the path to the file with environment")
	buildCmd.Flags().StringVarP(&(cfg.DisplayName), "application-name", "n", "", "Specify the display name for the application (default: output image name)")
	buildCmd.Flags().StringVarP(&(cfg.Description), "description", "", "", "Specify the description of the application")
	buildCmd.Flags().VarP(&(cfg.AllowedUIDs), "allowed-uids", "u", "Specify a range of allowed user ids for the builder and runtime images")
	buildCmd.Flags().VarP(&(cfg.Injections), "inject", "i", "Specify a directory to inject into the assemble container")
	buildCmd.Flags().StringArrayVarP(&(cfg.BuildVolumes), "volume", "v", []string{}, "Specify a volume to mount into the assemble container")
	buildCmd.Flags().StringSliceVar(&(cfg.DropCapabilities), "cap-drop", []string{}, "Specify a comma-separated list of capabilities to drop when running Docker containers")
	buildCmd.Flags().StringVarP(&(oldDestination), "location", "l", "",
		"DEPRECATED: Specify a destination location for untar operation")
	buildCmd.Flags().BoolVarP(&(cfg.ForceCopy), "copy", "c", false, "Use local file system copy instead of git cloning the source url")
	buildCmd.Flags().StringVar(&(cfg.RuntimeImage), "runtime-image", "", "Image that will be used as the base for the runtime image")
	buildCmd.Flags().VarP(&(cfg.RuntimeArtifacts), "runtime-artifact", "a", "Specify a file or directory to be copied from the builder to the runtime image")
	buildCmd.Flags().StringVar(&(networkMode), "network", "", "Specify the default Docker Network name to be used in build process")
	buildCmd.Flags().StringVarP(&(cfg.AsDockerfile), "as-dockerfile", "", "", "EXPERIMENTAL: Output a Dockerfile to this path instead of building a new image")
	buildCmd.Flags().BoolVarP(&(cfg.KeepSymlinks), "keep-symlinks", "", false, "When using '--copy', copy symlinks as symlinks. Default behavior is to follow symlinks and copy files by content")
	buildCmd.Flags().StringArrayVar(&cfg.AddHost, "add-host", []string{}, "Specify additional entries to add to the /etc/hosts in the assemble container, multiple --add-host can be used to add multiple entries")
	return buildCmd
}
320716
func NewCmdTag(fullName string, f kcmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
	o := NewTagOptions(streams)
	cmd := &cobra.Command{
		Use:     "tag [--source=SOURCETYPE] SOURCE DEST [DEST ...]",
		Short:   "Tag existing images into image streams",
		Long:    tagLong,
		Example: fmt.Sprintf(tagExample, fullName),
		Run: func(cmd *cobra.Command, args []string) {
			kcmdutil.CheckErr(o.Complete(f, cmd, args))
			kcmdutil.CheckErr(o.Validate())
			kcmdutil.CheckErr(o.Run())
		},
	}

	cmd.Flags().StringVar(&o.sourceKind, "source", o.sourceKind, "Optional hint for the source type; valid values are 'imagestreamtag', 'istag', 'imagestreamimage', 'isimage', and 'docker'.")
	cmd.Flags().BoolVarP(&o.deleteTag, "delete", "d", o.deleteTag, "Delete the provided spec tags.")
	cmd.Flags().BoolVar(&o.aliasTag, "alias", o.aliasTag, "Should the destination tag be updated whenever the source tag changes. Applies only to a single image stream. Defaults to false.")
	cmd.Flags().BoolVar(&o.referenceTag, "reference", o.referenceTag, "Should the destination tag continue to pull from the source namespace. Defaults to false.")
	cmd.Flags().BoolVar(&o.scheduleTag, "scheduled", o.scheduleTag, "Set a Docker image to be periodically imported from a remote repository. Defaults to false.")
	cmd.Flags().BoolVar(&o.insecureTag, "insecure", o.insecureTag, "Set to true if importing the specified Docker image requires HTTP or has a self-signed certificate. Defaults to false.")
	cmd.Flags().StringVar(&o.referencePolicy, "reference-policy", SourceReferencePolicy, "Allow to request pullthrough for external image when set to 'local'. Defaults to 'source'.")

	return cmd
}
501082
func NewContextCommand(dockerCli command.Cli) *cobra.Command {
	cmd := &cobra.Command{
		Use:   "context",
		Short: "Manage contexts",
		Args:  cli.NoArgs,
		RunE:  command.ShowHelp(dockerCli.Err()),
	}
	cmd.AddCommand(
		newCreateCommand(dockerCli),
		newListCommand(dockerCli),
		newUseCommand(dockerCli),
		newExportCommand(dockerCli),
		newImportCommand(dockerCli),
		newRemoveCommand(dockerCli),
		newUpdateCommand(dockerCli),
		newInspectCommand(dockerCli),
	)
	return cmd
}
903693
func generateDockerExecCommand(containerID string, bashcmd []string, prependBash bool) ([]string, error) {
	if containerID == "" {
		return []string{}, fmt.Errorf("will not attach to container with empty containerID")
	}

	exeMap, err := exePaths([]string{"docker"})
	if err != nil {
		return []string{}, err
	}

	// TODO: add '-h' hostname to specify the container hostname when that
	// feature becomes available
	attachCmd := []string{exeMap["docker"], "exec"}

	if Isatty(os.Stdin) {
		attachCmd = append(attachCmd, "-t")
	}
	if Isatty(os.Stdout) && Isatty(os.Stdin) {
		attachCmd = append(attachCmd, "-i")
	}
	attachCmd = append(attachCmd, containerID)

	if prependBash {
		attachCmd = append(attachCmd, "/bin/bash", "-c", fmt.Sprintf("%s", strings.Join(bashcmd, " ")))
	} else {
		attachCmd = append(attachCmd, bashcmd...)
	}
	glog.V(1).Infof("attach command for container:%v command: %v\n", containerID, attachCmd)
	return attachCmd, nil
}
748949
func NewCmd(fullName string, f kcmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
	image := &cobra.Command{
		Use:   "registry COMMAND",
		Short: "Commands for working with the registry",
		Long:  imageLong,
		Run:   kcmdutil.DefaultSubCommandRun(streams.ErrOut),
	}

	name := fmt.Sprintf("%s registry", fullName)

	groups := ktemplates.CommandGroups{
		{
			Message: "Advanced commands:",
			Commands: []*cobra.Command{
				info.NewRegistryInfoCmd(name, f, streams),
				login.NewRegistryLoginCmd(name, f, streams),
			},
		},
	}
	groups.Add(image)
	templates.ActsAsRootCommand(image, []string{"options"}, groups...)
	return image
}