// NewProjectCreateCommand returns a new instance of an `argocd proj create` command
12188
func NewProjectCreateCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
	var (
		opts projectOpts
	)
	var command = &cobra.Command{
		Use:   "create PROJECT",
		Short: "Create a project",
		Run: func(c *cobra.Command, args []string) {
			if len(args) == 0 {
				c.HelpFunc()(c, args)
				os.Exit(1)
			}
			projName := args[0]
			proj := v1alpha1.AppProject{
				ObjectMeta: v1.ObjectMeta{Name: projName},
				Spec: v1alpha1.AppProjectSpec{
					Description:  opts.description,
					Destinations: opts.GetDestinations(),
					SourceRepos:  opts.sources,
				},
			}
			conn, projIf := argocdclient.NewClientOrDie(clientOpts).NewProjectClientOrDie()
			defer util.Close(conn)

			_, err := projIf.Create(context.Background(), &project.ProjectCreateRequest{Project: &proj})
			errors.CheckError(err)
		},
	}
	addProjFlags(command, &opts)
	return command
}
1089143
func (p *Project) Create(ctx context.Context, options options.Create, services ...string) error {
	if options.NoRecreate && options.ForceRecreate {
		return fmt.Errorf("no-recreate and force-recreate cannot be combined")
	}
	if err := p.initialize(ctx); err != nil {
		return err
	}
	return p.perform(events.ProjectCreateStart, events.ProjectCreateDone, services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) {
		wrapper.Do(wrappers, events.ServiceCreateStart, events.ServiceCreate, func(service Service) error {
			return service.Create(ctx, options)
		})
	}), nil)
}
896130
func CreateProject(c *check.C, name string, composeFiles ...string) *Project {
	project, err := compose.CreateProject(name, composeFiles...)
	c.Assert(err, check.IsNil,
		check.Commentf("error while creating compose project %s from %v", name, composeFiles))
	return &Project{
		project: project,
	}
}
309970
func NewProjectionInProcess(ctx *plan.Context, p *plan.Projection) *Projection {
	s := &Projection{
		TaskBase: NewTaskBase(ctx),
		p:        p,
	}
	s.Handler = s.projectionEvaluator(p.Final)
	return s
}
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
}
168437
func NewApplicationCreateCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
	var (
		appOpts appOptions
		fileURL string
		appName string
		upsert  bool
	)
	var command = &cobra.Command{
		Use:   "create APPNAME",
		Short: "Create an application from a git location",
		Run: func(c *cobra.Command, args []string) {
			var app argoappv1.Application
			argocdClient := argocdclient.NewClientOrDie(clientOpts)
			if fileURL != "" {
				parsedURL, err := url.ParseRequestURI(fileURL)
				if err != nil || !(parsedURL.Scheme == "http" || parsedURL.Scheme == "https") {
					err = config.UnmarshalLocalFile(fileURL, &app)
				} else {
					err = config.UnmarshalRemoteFile(fileURL, &app)
				}
				errors.CheckError(err)
				if len(args) == 1 && args[0] != app.Name {
					log.Fatalf("app name '%s' does not match app spec metadata.name '%s'", args[0], app.Name)
				}
				if appName != "" && appName != app.Name {
					log.Fatalf("--name argument '%s' does not match app spec metadata.name '%s'", appName, app.Name)
				}
			} else {
				if len(args) == 1 {
					if appName != "" && appName != args[0] {
						log.Fatalf("--name argument '%s' does not match app name %s", appName, args[0])
					}
					appName = args[0]
				}
				app = argoappv1.Application{
					ObjectMeta: metav1.ObjectMeta{
						Name: appName,
					},
				}
				setAppOptions(c.Flags(), &app, &appOpts)
				setParameterOverrides(&app, appOpts.parameters)
			}
			if app.Name == "" {
				c.HelpFunc()(c, args)
				os.Exit(1)
			}
			conn, appIf := argocdClient.NewApplicationClientOrDie()
			defer util.Close(conn)
			appCreateRequest := application.ApplicationCreateRequest{
				Application: app,
				Upsert:      &upsert,
			}
			created, err := appIf.Create(context.Background(), &appCreateRequest)
			errors.CheckError(err)
			fmt.Printf("application '%s' created\n", created.ObjectMeta.Name)
		},
	}
	command.Flags().StringVarP(&fileURL, "file", "f", "", "Filename or URL to Kubernetes manifests for the app")
	command.Flags().StringVar(&appName, "name", "", "A name for the app, ignored if a file is set (DEPRECATED)")
	command.Flags().BoolVar(&upsert, "upsert", false, "Allows to override application with the same name even if supplied application spec is different from existing spec")
	addAppFlags(command, &appOpts)
	return command
}
660426
func NewCommand() *cobra.Command {
	var command = &cobra.Command{
		Use:   CLIName,
		Short: "argo is the command line interface to Argo",
		Run: func(cmd *cobra.Command, args []string) {
			cmd.HelpFunc()(cmd, args)
		},
	}

	command.AddCommand(NewCompletionCommand())
	command.AddCommand(NewDeleteCommand())
	command.AddCommand(NewGetCommand())
	command.AddCommand(NewLintCommand())
	command.AddCommand(NewListCommand())
	command.AddCommand(NewLogsCommand())
	command.AddCommand(NewResubmitCommand())
	command.AddCommand(NewResumeCommand())
	command.AddCommand(NewRetryCommand())
	command.AddCommand(NewSubmitCommand())
	command.AddCommand(NewSuspendCommand())
	command.AddCommand(NewWaitCommand())
	command.AddCommand(NewWatchCommand())
	command.AddCommand(NewTerminateCommand())
	command.AddCommand(cmd.NewVersionCmd(CLIName))

	addKubectlFlagsToCmd(command)
	return command
}
877962
func (c *container) Create(cmds []string) {
	adHoc := (len(cmds) > 0)
	if !adHoc {
		c.Rm(true, false)
	}
	msg := "Creating container %s"
	if adHoc {
		msg += " (ad-hoc)"
	}
	fmt.Fprintf(c.CommandsOut(), msg+" ...\n", c.ActualName(adHoc))

	args := append([]string{"create"}, c.createArgs(cmds)...)
	executeCommand("docker", args, c.CommandsOut(), c.CommandsErr())

	c.connectWithNetworks(adHoc)
}
478831
func NewApplicationCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
	var command = &cobra.Command{
		Use:     "app",
		Short:   "Manage applications",
		Example: appExample,
		Run: func(c *cobra.Command, args []string) {
			c.HelpFunc()(c, args)
			os.Exit(1)
		},
	}
	command.AddCommand(NewApplicationCreateCommand(clientOpts))
	command.AddCommand(NewApplicationGetCommand(clientOpts))
	command.AddCommand(NewApplicationDiffCommand(clientOpts))
	command.AddCommand(NewApplicationSetCommand(clientOpts))
	command.AddCommand(NewApplicationUnsetCommand(clientOpts))
	command.AddCommand(NewApplicationSyncCommand(clientOpts))
	command.AddCommand(NewApplicationHistoryCommand(clientOpts))
	command.AddCommand(NewApplicationRollbackCommand(clientOpts))
	command.AddCommand(NewApplicationListCommand(clientOpts))
	command.AddCommand(NewApplicationDeleteCommand(clientOpts))
	command.AddCommand(NewApplicationWaitCommand(clientOpts))
	command.AddCommand(NewApplicationManifestsCommand(clientOpts))
	command.AddCommand(NewApplicationTerminateOpCommand(clientOpts))
	command.AddCommand(NewApplicationEditCommand(clientOpts))
	command.AddCommand(NewApplicationPatchCommand(clientOpts))
	command.AddCommand(NewApplicationPatchResourceCommand(clientOpts))
	command.AddCommand(NewApplicationResourceActionsCommand(clientOpts))
	return command
}
582451
func CreateProject(name string, composeFiles ...string) (*Project, error) {
	// FIXME(vdemeester) temporarly normalize the project name, should not be needed.
	r := regexp.MustCompile("[^a-z0-9]+")
	name = r.ReplaceAllString(strings.ToLower(name), "")

	apiClient, err := client.NewEnvClient()
	if err != nil {
		return nil, err
	}

	ping := types.Ping{APIVersion: d.CurrentAPIVersion}
	apiClient.NegotiateAPIVersionPing(ping)

	composeProject, err := docker.NewProject(&ctx.Context{
		Context: project.Context{
			ComposeFiles: composeFiles,
			ProjectName:  name,
		},
	}, &config.ParseOptions{
		Interpolate: true,
		Validate:    true,
	})
	if err != nil {
		return nil, err
	}
	p := &Project{
		composeFiles:   composeFiles,
		composeProject: composeProject,
		name:           name,
		listenChan:     make(chan events.Event),
		started:        make(chan struct{}),
		stopped:        make(chan struct{}),
		deleted:        make(chan struct{}),
		client:         apiClient,
		hasOpenedChan:  true,
	}

	// Listen to compose events
	go p.startListening()
	p.composeProject.AddListener(p.listenChan)

	return p, nil
}
697049
func NewImportCommand() *cobra.Command {
	var (
		clientConfig clientcmd.ClientConfig
		prune        bool
		dryRun       bool
	)
	var command = cobra.Command{
		Use:   "import SOURCE",
		Short: "Import Argo CD data from stdin (specify `-') or a file",
		Run: func(c *cobra.Command, args []string) {
			if len(args) != 1 {
				c.HelpFunc()(c, args)
				os.Exit(1)
			}
			config, err := clientConfig.ClientConfig()
			config.QPS = 100
			config.Burst = 50
			errors.CheckError(err)
			namespace, _, err := clientConfig.Namespace()
			errors.CheckError(err)
			acdClients := newArgoCDClientsets(config, namespace)

			var input []byte
			if in := args[0]; in == "-" {
				input, err = ioutil.ReadAll(os.Stdin)
			} else {
				input, err = ioutil.ReadFile(in)
			}
			errors.CheckError(err)
			var dryRunMsg string
			if dryRun {
				dryRunMsg = " (dry run)"
			}

			// pruneObjects tracks live objects and it's current resource version. any remaining
			// items in this map indicates the resource should be pruned since it no longer appears
			// in the backup
			pruneObjects := make(map[kube.ResourceKey]string)
			configMaps, err := acdClients.configMaps.List(metav1.ListOptions{})
			errors.CheckError(err)
			for _, cm := range configMaps.Items {
				cmName := cm.GetName()
				if cmName == common.ArgoCDConfigMapName || cmName == common.ArgoCDRBACConfigMapName {
					pruneObjects[kube.ResourceKey{Group: "", Kind: "ConfigMap", Name: cm.GetName()}] = cm.GetResourceVersion()
				}
			}
			secrets, err := acdClients.secrets.List(metav1.ListOptions{})
			errors.CheckError(err)
			for _, secret := range secrets.Items {
				if isArgoCDSecret(nil, secret) {
					pruneObjects[kube.ResourceKey{Group: "", Kind: "Secret", Name: secret.GetName()}] = secret.GetResourceVersion()
				}
			}
			applications, err := acdClients.applications.List(metav1.ListOptions{})
			errors.CheckError(err)
			for _, app := range applications.Items {
				pruneObjects[kube.ResourceKey{Group: "argoproj.io", Kind: "Application", Name: app.GetName()}] = app.GetResourceVersion()
			}
			projects, err := acdClients.projects.List(metav1.ListOptions{})
			errors.CheckError(err)
			for _, proj := range projects.Items {
				pruneObjects[kube.ResourceKey{Group: "argoproj.io", Kind: "AppProject", Name: proj.GetName()}] = proj.GetResourceVersion()
			}

			// Create or replace existing object
			objs, err := kube.SplitYAML(string(input))
			errors.CheckError(err)
			for _, obj := range objs {
				gvk := obj.GroupVersionKind()
				key := kube.ResourceKey{Group: gvk.Group, Kind: gvk.Kind, Name: obj.GetName()}
				resourceVersion, exists := pruneObjects[key]
				delete(pruneObjects, key)
				var dynClient dynamic.ResourceInterface
				switch obj.GetKind() {
				case "Secret":
					dynClient = acdClients.secrets
				case "ConfigMap":
					dynClient = acdClients.configMaps
				case "AppProject":
					dynClient = acdClients.projects
				case "Application":
					dynClient = acdClients.applications
				}
				if !exists {
					if !dryRun {
						_, err = dynClient.Create(obj, metav1.CreateOptions{})
						errors.CheckError(err)
					}
					fmt.Printf("%s/%s %s created%s\n", gvk.Group, gvk.Kind, obj.GetName(), dryRunMsg)
				} else {
					if !dryRun {
						obj.SetResourceVersion(resourceVersion)
						_, err = dynClient.Update(obj, metav1.UpdateOptions{})
						errors.CheckError(err)
					}
					fmt.Printf("%s/%s %s replaced%s\n", gvk.Group, gvk.Kind, obj.GetName(), dryRunMsg)
				}
			}

			// Delete objects not in backup
			for key := range pruneObjects {
				if prune {
					var dynClient dynamic.ResourceInterface
					switch key.Kind {
					case "Secret":
						dynClient = acdClients.secrets
					case "AppProject":
						dynClient = acdClients.projects
					case "Application":
						dynClient = acdClients.applications
					default:
						log.Fatalf("Unexpected kind '%s' in prune list", key.Kind)
					}
					if !dryRun {
						err = dynClient.Delete(key.Name, &metav1.DeleteOptions{})
						errors.CheckError(err)
					}
					fmt.Printf("%s/%s %s pruned%s\n", key.Group, key.Kind, key.Name, dryRunMsg)
				} else {
					fmt.Printf("%s/%s %s needs pruning\n", key.Group, key.Kind, key.Name)
				}
			}
		},
	}

	clientConfig = cli.AddKubectlFlagsToCmd(&command)
	command.Flags().BoolVar(&dryRun, "dry-run", false, "Print what will be performed")
	command.Flags().BoolVar(&prune, "prune", false, "Prune secrets, applications and projects which do not appear in the backup")

	return &command
}
784457
func New(cmd string, args []string) *simpleSource {
	return &simpleSource{command: cmd, args: args}
}
47716
func buildCommand(buf []byte, args ...[]byte) []byte {
	buf = append(buf, '*')
	buf = append(buf, strconv.FormatInt(int64(len(args)), 10)...)
	buf = append(buf, '\r', '\n')
	for _, arg := range args {
		buf = append(buf, '$')
		buf = append(buf, strconv.FormatInt(int64(len(arg)), 10)...)
		buf = append(buf, '\r', '\n')
		buf = append(buf, arg...)
		buf = append(buf, '\r', '\n')
	}
	return buf
}
1078082
func BuildCommand(factory app.ProjectFactory) cli.Command {
	return cli.Command{
		Name:   "build",
		Usage:  "Build or rebuild services.",
		Action: app.WithProject(factory, app.ProjectBuild),
		Flags: []cli.Flag{
			cli.BoolFlag{
				Name:  "no-cache",
				Usage: "Do not use cache when building the image",
			},
			cli.BoolFlag{
				Name:  "force-rm",
				Usage: "Always remove intermediate containers",
			},
			cli.BoolFlag{
				Name:  "pull",
				Usage: "Always attempt to pull a newer version of the image",
			},
		},
	}
}
451035
func NewCommand(name string, args ...interface{}) *Command {
	return &Command{
		name: strings.TrimSpace(name),
		args: args,
	}
}
790727
func (c *projects) Create(projectResource *project.Project) (result *project.Project, err error) {
	result = &project.Project{}
	err = c.client.Post().
		Resource("projects").
		Body(projectResource).
		Do().
		Into(result)
	return
}
1353498
func (s *RepositoriesService) CreateProject(ctx context.Context, owner, repo string, opt *ProjectOptions) (*Project, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/projects", owner, repo)
	req, err := s.client.NewRequest("POST", u, opt)
	if err != nil {
		return nil, nil, err
	}

	// TODO: remove custom Accept headers when APIs fully launch.
	req.Header.Set("Accept", mediaTypeProjectsPreview)

	project := &Project{}
	resp, err := s.client.Do(ctx, req, project)
	if err != nil {
		return nil, resp, err
	}

	return project, resp, nil
}