// NewCommand returns a new instance of an argocd command
543678
func NewCommand() *cobra.Command {
	var (
		insecure               bool
		logLevel               string
		glogLevel              int
		clientConfig           clientcmd.ClientConfig
		staticAssetsDir        string
		baseHRef               string
		repoServerAddress      string
		dexServerAddress       string
		disableAuth            bool
		tlsConfigCustomizerSrc func() (tls.ConfigCustomizer, error)
		cacheSrc               func() (*cache.Cache, error)
	)
	var command = &cobra.Command{
		Use:   cliName,
		Short: "Run the argocd API server",
		Long:  "Run the argocd API server",
		Run: func(c *cobra.Command, args []string) {
			cli.SetLogLevel(logLevel)
			cli.SetGLogLevel(glogLevel)

			config, err := clientConfig.ClientConfig()
			errors.CheckError(err)
			config.QPS = common.K8sClientConfigQPS
			config.Burst = common.K8sClientConfigBurst

			namespace, _, err := clientConfig.Namespace()
			errors.CheckError(err)

			tlsConfigCustomizer, err := tlsConfigCustomizerSrc()
			errors.CheckError(err)
			cache, err := cacheSrc()
			errors.CheckError(err)

			kubeclientset := kubernetes.NewForConfigOrDie(config)
			appclientset := appclientset.NewForConfigOrDie(config)
			repoclientset := reposerver.NewRepoServerClientset(repoServerAddress, 0)

			argoCDOpts := server.ArgoCDServerOpts{
				Insecure:            insecure,
				Namespace:           namespace,
				StaticAssetsDir:     staticAssetsDir,
				BaseHRef:            baseHRef,
				KubeClientset:       kubeclientset,
				AppClientset:        appclientset,
				RepoClientset:       repoclientset,
				DexServerAddr:       dexServerAddress,
				DisableAuth:         disableAuth,
				TLSConfigCustomizer: tlsConfigCustomizer,
				Cache:               cache,
			}

			stats.RegisterStackDumper()
			stats.StartStatsTicker(10 * time.Minute)
			stats.RegisterHeapDumper("memprofile")

			for {
				ctx := context.Background()
				ctx, cancel := context.WithCancel(ctx)
				argocd := server.NewServer(ctx, argoCDOpts)
				argocd.Run(ctx, common.PortAPIServer)
				cancel()
			}
		},
	}

	clientConfig = cli.AddKubectlFlagsToCmd(command)
	command.Flags().BoolVar(&insecure, "insecure", false, "Run server without TLS")
	command.Flags().StringVar(&staticAssetsDir, "staticassets", "", "Static assets directory path")
	command.Flags().StringVar(&baseHRef, "basehref", "/", "Value for base href in index.html. Used if Argo CD is running behind reverse proxy under subpath different from /")
	command.Flags().StringVar(&logLevel, "loglevel", "info", "Set the logging level. One of: debug|info|warn|error")
	command.Flags().IntVar(&glogLevel, "gloglevel", 0, "Set the glog logging level")
	command.Flags().StringVar(&repoServerAddress, "repo-server", common.DefaultRepoServerAddr, "Repo server address")
	command.Flags().StringVar(&dexServerAddress, "dex-server", common.DefaultDexServerAddr, "Dex server address")
	command.Flags().BoolVar(&disableAuth, "disable-auth", false, "Disable client authentication")
	command.AddCommand(cli.NewVersionCmd(cliName))
	tlsConfigCustomizerSrc = tls.AddTLSFlagsToCmd(command)
	cacheSrc = cache.AddCacheFlagsToCmd(command)
	return command
}
24291
func NewEventsCommand(dockerCli command.Cli) *cobra.Command {
	options := eventsOptions{filter: opts.NewFilterOpt()}

	cmd := &cobra.Command{
		Use:   "events [OPTIONS]",
		Short: "Get real time events from the server",
		Args:  cli.NoArgs,
		RunE: func(cmd *cobra.Command, args []string) error {
			return runEvents(dockerCli, &options)
		},
	}

	flags := cmd.Flags()
	flags.StringVar(&options.since, "since", "", "Show all events created since timestamp")
	flags.StringVar(&options.until, "until", "", "Stream events until this timestamp")
	flags.VarP(&options.filter, "filter", "f", "Filter output based on conditions provided")
	flags.StringVar(&options.format, "format", "", "Format the output using the given Go template")

	return cmd
}
374552
func NewCommand(p *Program) *cobra.Command {
	var cmd = &cobra.Command{
		Use:  p.Name,
		Args: cobra.NoArgs,
		RunE: func(_ *cobra.Command, _ []string) error {
			return p.Run()
		},
	}

	viper.SetEnvPrefix(strings.ToUpper(p.Name))
	viper.AutomaticEnv()
	// This normalizes "-" to an underscore in env names.
	viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))

	BindOptions(cmd, p.Opts)

	return cmd
}
701694
func NewPoolCreateCommand() cmd.Command {
	cmd := &poolCreateCommand{}
	cmd.newAPIFunc = func() (PoolCreateAPI, error) {
		return cmd.NewStorageAPI()
	}
	return modelcmd.Wrap(cmd)
}
883774
func NewReloginCommand(globalClientOpts *argocdclient.ClientOptions) *cobra.Command {
	var (
		password string
		ssoPort  int
	)
	var command = &cobra.Command{
		Use:   "relogin",
		Short: "Refresh an expired authenticate token",
		Long:  "Refresh an expired authenticate token",
		Run: func(c *cobra.Command, args []string) {
			if len(args) != 0 {
				c.HelpFunc()(c, args)
				os.Exit(1)
			}
			localCfg, err := localconfig.ReadLocalConfig(globalClientOpts.ConfigPath)
			errors.CheckError(err)
			if localCfg == nil {
				log.Fatalf("No context found. Login using `argocd login`")
			}
			configCtx, err := localCfg.ResolveContext(localCfg.CurrentContext)
			errors.CheckError(err)

			var tokenString string
			var refreshToken string
			clientOpts := argocdclient.ClientOptions{
				ConfigPath: "",
				ServerAddr: configCtx.Server.Server,
				Insecure:   configCtx.Server.Insecure,
				GRPCWeb:    globalClientOpts.GRPCWeb,
				PlainText:  configCtx.Server.PlainText,
			}
			acdClient := argocdclient.NewClientOrDie(&clientOpts)
			claims, err := configCtx.User.Claims()
			errors.CheckError(err)
			if claims.Issuer == session.SessionManagerClaimsIssuer {
				fmt.Printf("Relogging in as '%s'\n", claims.Subject)
				tokenString = passwordLogin(acdClient, claims.Subject, password)
			} else {
				fmt.Println("Reinitiating SSO login")
				setConn, setIf := acdClient.NewSettingsClientOrDie()
				defer util.Close(setConn)
				ctx := context.Background()
				httpClient, err := acdClient.HTTPClient()
				errors.CheckError(err)
				ctx = oidc.ClientContext(ctx, httpClient)
				acdSet, err := setIf.Get(ctx, &settings.SettingsQuery{})
				errors.CheckError(err)
				oauth2conf, provider, err := acdClient.OIDCConfig(ctx, acdSet)
				errors.CheckError(err)
				tokenString, refreshToken = oauth2Login(ctx, ssoPort, oauth2conf, provider)
			}

			localCfg.UpsertUser(localconfig.User{
				Name:         localCfg.CurrentContext,
				AuthToken:    tokenString,
				RefreshToken: refreshToken,
			})
			err = localconfig.WriteLocalConfig(*localCfg, globalClientOpts.ConfigPath)
			errors.CheckError(err)
			fmt.Printf("Context '%s' updated\n", localCfg.CurrentContext)
		},
	}
	command.Flags().StringVar(&password, "password", "", "the password of an account to authenticate")
	command.Flags().IntVar(&ssoPort, "sso-port", DefaultSSOLocalPort, "port to run local OAuth2 login application")
	return command
}
581910
func NewCmd(cmd *exec.Cmd) *Cmd {
	c := &Cmd{
		Cmd:     cmd,
		stopped: make(chan struct{}, 1),
	}
	c.stoppingValue.Store(false)
	c.Stdout = os.Stdout
	c.Stderr = os.Stderr
	return c
}
873000
func newInspectCommand(dockerCli command.Cli) *cobra.Command {
	var opts inspectOptions

	cmd := &cobra.Command{
		Use:   "inspect [OPTIONS] [CONTEXT] [CONTEXT...]",
		Short: "Display detailed information on one or more contexts",
		RunE: func(cmd *cobra.Command, args []string) error {
			opts.refs = args
			if len(opts.refs) == 0 {
				if dockerCli.CurrentContext() == "" {
					return errors.New("no context specified")
				}
				opts.refs = []string{dockerCli.CurrentContext()}
			}
			return runInspect(dockerCli, opts)
		},
	}

	flags := cmd.Flags()
	flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template")
	return cmd
}
451035
func NewCommand(name string, args ...interface{}) *Command {
	return &Command{
		name: strings.TrimSpace(name),
		args: args,
	}
}
68288
func NewCommandLong(PARAM1 float32, PARAM2 float32, PARAM3 float32, PARAM4 float32, PARAM5 float32, PARAM6 float32, PARAM7 float32, COMMAND uint16, TARGET_SYSTEM uint8, TARGET_COMPONENT uint8, CONFIRMATION uint8) *CommandLong {
	m := CommandLong{}
	m.PARAM1 = PARAM1
	m.PARAM2 = PARAM2
	m.PARAM3 = PARAM3
	m.PARAM4 = PARAM4
	m.PARAM5 = PARAM5
	m.PARAM6 = PARAM6
	m.PARAM7 = PARAM7
	m.COMMAND = COMMAND
	m.TARGET_SYSTEM = TARGET_SYSTEM
	m.TARGET_COMPONENT = TARGET_COMPONENT
	m.CONFIRMATION = CONFIRMATION
	return &m
}
1052835
func (c *Command) AddCommand(cmds ...*Command) {
	for i, x := range cmds {
		if cmds[i] == c {
			panic("Command can't be a child of itself")
		}
		cmds[i].parent = c
		// update max lengths
		usageLen := len(x.Use)
		if usageLen > c.commandsMaxUseLen {
			c.commandsMaxUseLen = usageLen
		}
		commandPathLen := len(x.CommandPath())
		if commandPathLen > c.commandsMaxCommandPathLen {
			c.commandsMaxCommandPathLen = commandPathLen
		}
		nameLen := len(x.Name())
		if nameLen > c.commandsMaxNameLen {
			c.commandsMaxNameLen = nameLen
		}
		// If global normalization function exists, update all children
		if c.globNormFunc != nil {
			x.SetGlobalNormalizationFunc(c.globNormFunc)
		}
		c.commands = append(c.commands, x)
		c.commandsAreSorted = false
	}
}
462817
func NewClusterAddCommand(clientOpts *argocdclient.ClientOptions, pathOpts *clientcmd.PathOptions) *cobra.Command {
	var (
		inCluster      bool
		upsert         bool
		awsRoleArn     string
		awsClusterName string
	)
	var command = &cobra.Command{
		Use:   "add",
		Short: fmt.Sprintf("%s cluster add CONTEXT", cliName),
		Run: func(c *cobra.Command, args []string) {
			var configAccess clientcmd.ConfigAccess = pathOpts
			if len(args) == 0 {
				log.Error("Choose a context name from:")
				printKubeContexts(configAccess)
				os.Exit(1)
			}
			config, err := configAccess.GetStartingConfig()
			errors.CheckError(err)
			clstContext := config.Contexts[args[0]]
			if clstContext == nil {
				log.Fatalf("Context %s does not exist in kubeconfig", args[0])
			}

			overrides := clientcmd.ConfigOverrides{
				Context: *clstContext,
			}
			clientConfig := clientcmd.NewDefaultClientConfig(*config, &overrides)
			conf, err := clientConfig.ClientConfig()
			errors.CheckError(err)

			managerBearerToken := ""
			var awsAuthConf *argoappv1.AWSAuthConfig
			if awsClusterName != "" {
				awsAuthConf = &argoappv1.AWSAuthConfig{
					ClusterName: awsClusterName,
					RoleARN:     awsRoleArn,
				}
			} else {
				// Install RBAC resources for managing the cluster
				clientset, err := kubernetes.NewForConfig(conf)
				errors.CheckError(err)
				managerBearerToken, err = common.InstallClusterManagerRBAC(clientset)
				errors.CheckError(err)
			}
			conn, clusterIf := argocdclient.NewClientOrDie(clientOpts).NewClusterClientOrDie()
			defer util.Close(conn)
			clst := NewCluster(args[0], conf, managerBearerToken, awsAuthConf)
			if inCluster {
				clst.Server = common.KubernetesInternalAPIServerAddr
			}
			clstCreateReq := cluster.ClusterCreateRequest{
				Cluster: clst,
				Upsert:  upsert,
			}
			clst, err = clusterIf.Create(context.Background(), &clstCreateReq)
			errors.CheckError(err)
			fmt.Printf("Cluster '%s' added\n", clst.Name)
		},
	}
	command.PersistentFlags().StringVar(&pathOpts.LoadingRules.ExplicitPath, pathOpts.ExplicitFileFlag, pathOpts.LoadingRules.ExplicitPath, "use a particular kubeconfig file")
	command.Flags().BoolVar(&inCluster, "in-cluster", false, "Indicates Argo CD resides inside this cluster and should connect using the internal k8s hostname (kubernetes.default.svc)")
	command.Flags().BoolVar(&upsert, "upsert", false, "Override an existing cluster with the same name even if the spec differs")
	command.Flags().StringVar(&awsClusterName, "aws-cluster-name", "", "AWS Cluster name if set then aws-iam-authenticator will be used to access cluster")
	command.Flags().StringVar(&awsRoleArn, "aws-role-arn", "", "Optional AWS role arn. If set then AWS IAM Authenticator assume a role to perform cluster operations instead of the default AWS credential provider chain.")
	return command
}
1263414
func (o *NSGateway) CreateCommand(child *Command) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}
250228
func NewCommand(module Module, usedModules ...Module) *cli.Command {
	flags := []cli.Flag{}
	flags = append(flags, module.Flags...)
	flags = append(flags, module.Depend.Flags(usedModules...)...)

	beforeActions := Actions{}
	beforeActions.Add(module.Depend.BeforeActions()...)
	beforeActions.Add(module.Before)
	actions := Actions{}
	actions.Add(module.Depend.Actions()...)
	actions.Add(module.Action)
	afterActions := Actions{}
	afterActions.Add(module.After)
	afterActions.Add(module.Depend.AfterActions()...)

	return &cli.Command{
		Name:   module.Name,
		Usage:  module.Usage,
		Flags:  flags,
		Before: cli.BeforeFunc(beforeActions.Wrap()),
		Action: actions.Wrap(),
		After:  cli.AfterFunc(afterActions.Wrap()),
	}
}
202785
func NewNodeCommand(dockerCli command.Cli) *cobra.Command {
	cmd := &cobra.Command{
		Use:   "node",
		Short: "Manage Swarm nodes",
		Args:  cli.NoArgs,
		RunE:  command.ShowHelp(dockerCli.Err()),
		Annotations: map[string]string{
			"version": "1.24",
			"swarm":   "",
		},
	}
	cmd.AddCommand(
		newDemoteCommand(dockerCli),
		newInspectCommand(dockerCli),
		newListCommand(dockerCli),
		newPromoteCommand(dockerCli),
		newRemoveCommand(dockerCli),
		newPsCommand(dockerCli),
		newUpdateCommand(dockerCli),
	)
	return cmd
}
632814
func NewExecCommand(dockerCli command.Cli) *cobra.Command {
	options := newExecOptions()

	cmd := &cobra.Command{
		Use:   "exec [OPTIONS] CONTAINER COMMAND [ARG...]",
		Short: "Run a command in a running container",
		Args:  cli.RequiresMinArgs(2),
		RunE: func(cmd *cobra.Command, args []string) error {
			options.container = args[0]
			options.command = args[1:]
			return runExec(dockerCli, options)
		},
	}

	flags := cmd.Flags()
	flags.SetInterspersed(false)

	flags.StringVarP(&options.detachKeys, "detach-keys", "", "", "Override the key sequence for detaching a container")
	flags.BoolVarP(&options.interactive, "interactive", "i", false, "Keep STDIN open even if not attached")
	flags.BoolVarP(&options.tty, "tty", "t", false, "Allocate a pseudo-TTY")
	flags.BoolVarP(&options.detach, "detach", "d", false, "Detached mode: run command in the background")
	flags.StringVarP(&options.user, "user", "u", "", "Username or UID (format: <name|uid>[:<group|gid>])")
	flags.BoolVarP(&options.privileged, "privileged", "", false, "Give extended privileges to the command")
	flags.VarP(&options.env, "env", "e", "Set environment variables")
	flags.SetAnnotation("env", "version", []string{"1.25"})
	flags.StringVarP(&options.workdir, "workdir", "w", "", "Working directory inside the container")
	flags.SetAnnotation("workdir", "version", []string{"1.35"})

	return cmd
}
68185
func CreateCommand(commandType CommandType) (Command, error) {
	commandsMu.RLock()
	defer commandsMu.RUnlock()
	if factory, ok := commands[commandType]; ok {
		return factory(), nil
	}
	return nil, ErrCommandNotRegistered
}
415094
func newCommandConn(args []string, cli *client.Client) (command, error) {
	// Create a flag set.
	var flg flag.FlagSet

	// Define the flags.
	network := flg.String("n", defaultNetwork, "network on which the Client connects to the Server")
	host := flg.String("h", defaultHost, "host name of the Server which the Client connects to")
	port := flg.Uint("p", defaultPort, "port number of the Server which the Client connects to")
	crtPath := flg.String("crt", "", "the path of the certificate authority file to verify the server connection")
	connackTimeout := flg.Uint(
		"ct",
		defaultCONNACKTimeout,
		"Timeout in seconds for the Client to wait for receiving the CONNACK Packet after sending the CONNECT Packet",
	)
	pingrespTimeout := flg.Uint(
		"pt",
		defaultPINGRESPTimeout,
		"Timeout in seconds for the Client to wait for receiving the PINGRESP Packet after sending the PINGREQ Packet",
	)
	clientID := flg.String("i", "", "Client identifier for the Client")
	userName := flg.String("u", "", "User Name")
	password := flg.String("P", "", "Password")
	cleanSession := flg.Bool("c", defaultCleanSession, "Clean Session")
	keepAlive := flg.Uint("k", defaultKeepAlive, "Keep Alive measured in seconds")
	willTopic := flg.String("wt", "", "Will Topic")
	willMessage := flg.String("wm", "", "Will Message")
	willQoS := flg.Uint("wq", uint(mqtt.QoS0), "Will QoS")
	willRetain := flg.Bool("wr", false, "Will Retain")

	// Parse the flag.
	if err := flg.Parse(args); err != nil {
		return nil, errCmdArgsParse
	}

	var tlsConfig *tls.Config

	// Parse the certificate authority file.
	if *crtPath != "" {
		b, err := ioutil.ReadFile(*crtPath)
		if err != nil {
			return nil, err
		}

		roots := x509.NewCertPool()
		if ok := roots.AppendCertsFromPEM(b); !ok {
			return nil, errParseCrtFailure
		}

		tlsConfig = &tls.Config{
			RootCAs: roots,
		}
	}

	// Create a conn command.
	cmd := &commandConn{
		cli: cli,
		connectOpts: &client.ConnectOptions{
			Network:         *network,
			Address:         *host + ":" + strconv.Itoa(int(*port)),
			TLSConfig:       tlsConfig,
			CONNACKTimeout:  time.Duration(*connackTimeout),
			PINGRESPTimeout: time.Duration(*pingrespTimeout),
			ClientID:        []byte(*clientID),
			UserName:        []byte(*userName),
			Password:        []byte(*password),
			CleanSession:    *cleanSession,
			KeepAlive:       uint16(*keepAlive),
			WillTopic:       []byte(*willTopic),
			WillMessage:     []byte(*willMessage),
			WillQoS:         byte(*willQoS),
			WillRetain:      *willRetain,
		},
	}

	// Return the command.
	return cmd, nil
}