Beispiel #1
0
        public override async Task <int> ExecuteAsync()
        {
            try
            {
                IRemote remote = RemoteFactory.GetBarOnlyRemote(_options, Logger);

                IEnumerable <RepositoryBranch> allRepositories = await remote.GetRepositoriesAsync();

                IEnumerable <RepositoryBranch> filteredRepositories = allRepositories.Where(repositories =>
                                                                                            (string.IsNullOrEmpty(_options.Repo) || repositories.Repository.Contains(_options.Repo, StringComparison.OrdinalIgnoreCase)) &&
                                                                                            (string.IsNullOrEmpty(_options.Branch) || repositories.Branch.Contains(_options.Branch, StringComparison.OrdinalIgnoreCase)));

                // List only those repos and branches that are targeted by a batchable subscription (active) unless the user
                // passes --all.
                if (!_options.All)
                {
                    HashSet <string> batchableTargets = (await remote.GetSubscriptionsAsync())
                                                        .Where(s => s.Policy.Batchable)
                                                        .Select <Subscription, string>(s => $"{s.TargetRepository}{s.TargetBranch}")
                                                        .ToHashSet(StringComparer.OrdinalIgnoreCase);
                    var targetedRepositories = filteredRepositories.Where(r => batchableTargets.Contains($"{r.Repository}{r.Branch}"));

                    // If the number of repositories we're about to print is less than what we could have printed, then print a
                    // message.
                    int difference = filteredRepositories.Count() - targetedRepositories.Count();
                    if (difference != 0)
                    {
                        Console.WriteLine($"Filtered {difference} policies for branches not targeted by an active batchable subscription. To include, pass --all.{Environment.NewLine}");
                    }

                    filteredRepositories = targetedRepositories;
                }

                foreach (var repository in filteredRepositories)
                {
                    Console.WriteLine($"{repository.Repository} @ {repository.Branch}");
                    Console.Write(UxHelpers.GetMergePoliciesDescription(repository.MergePolicies));
                }

                return(Constants.SuccessCode);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine(e.Message);
                return(Constants.ErrorCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error: Failed to retrieve repositories");
                return(Constants.ErrorCode);
            }
        }
        public override async Task <int> ExecuteAsync()
        {
            IRemote remote = RemoteFactory.GetBarOnlyRemote(_options, Logger);

            if (_options.IgnoreChecks.Count() > 0 && !_options.AllChecksSuccessfulMergePolicy)
            {
                Console.WriteLine($"--ignore-checks must be combined with --all-checks-passed");
                return(Constants.ErrorCode);
            }

            // Parse the merge policies
            List <MergePolicy> mergePolicies = new List <MergePolicy>();

            if (_options.AllChecksSuccessfulMergePolicy)
            {
                mergePolicies.Add(
                    new MergePolicy
                {
                    Name       = MergePolicyConstants.AllCheckSuccessfulMergePolicyName,
                    Properties = ImmutableDictionary.Create <string, JToken>()
                                 .Add(MergePolicyConstants.IgnoreChecksMergePolicyPropertyName, JToken.FromObject(_options.IgnoreChecks))
                });
            }

            if (_options.NoRequestedChangesMergePolicy)
            {
                mergePolicies.Add(
                    new MergePolicy
                {
                    Name       = MergePolicyConstants.NoRequestedChangesMergePolicyName,
                    Properties = ImmutableDictionary.Create <string, JToken>()
                });
            }

            if (_options.StandardAutoMergePolicies)
            {
                mergePolicies.Add(
                    new MergePolicy
                {
                    Name       = MergePolicyConstants.StandardMergePolicyName,
                    Properties = ImmutableDictionary.Create <string, JToken>()
                });
            }

            string repository = _options.Repository;
            string branch     = _options.Branch;

            // If in quiet (non-interactive mode), ensure that all options were passed, then
            // just call the remote API
            if (_options.Quiet)
            {
                if (string.IsNullOrEmpty(repository) ||
                    string.IsNullOrEmpty(branch))
                {
                    Logger.LogError($"Missing input parameters for merge policies. Please see command help or remove --quiet/-q for interactive mode");
                    return(Constants.ErrorCode);
                }
            }
            else
            {
                // Look up existing merge policies if the repository and branch were specified, and the user didn't
                // specify policies on the command line. In this case, they typically want to update
                if (!mergePolicies.Any() && !string.IsNullOrEmpty(repository) && !string.IsNullOrEmpty(branch))
                {
                    mergePolicies = (await remote.GetRepositoryMergePoliciesAsync(repository, branch)).ToList();
                }

                // Help the user along with a form.  We'll use the API to gather suggested values
                // from existing subscriptions based on the input parameters.
                SetRepositoryMergePoliciesPopUp initEditorPopUp =
                    new SetRepositoryMergePoliciesPopUp("set-policies/set-policies-todo",
                                                        Logger,
                                                        repository,
                                                        branch,
                                                        mergePolicies,
                                                        Constants.AvailableMergePolicyYamlHelp);

                UxManager uxManager = new UxManager(_options.GitLocation, Logger);
                int       exitCode  = uxManager.PopUp(initEditorPopUp);
                if (exitCode != Constants.SuccessCode)
                {
                    return(exitCode);
                }
                repository    = initEditorPopUp.Repository;
                branch        = initEditorPopUp.Branch;
                mergePolicies = initEditorPopUp.MergePolicies;
            }

            IRemote verifyRemote = RemoteFactory.GetRemote(_options, repository, Logger);
            IEnumerable <RepositoryBranch> targetRepository = await verifyRemote.GetRepositoriesAsync(repository);

            if (targetRepository == null || !targetRepository.Any())
            {
                Console.WriteLine($"The target repository '{repository}' doesn't have a Maestro installation. Aborting merge policy creation.");
                return(Constants.ErrorCode);
            }

            if (!(await UxHelpers.VerifyAndConfirmBranchExistsAsync(verifyRemote, repository, branch, !_options.Quiet)))
            {
                Console.WriteLine("Aborting merge policy creation.");
                return(Constants.ErrorCode);
            }

            try
            {
                await remote.SetRepositoryMergePoliciesAsync(
                    repository, branch, mergePolicies);

                Console.WriteLine($"Successfully updated merge policies for {repository}@{branch}.");
                return(Constants.SuccessCode);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine(e.Message);
                return(Constants.ErrorCode);
            }
            catch (RestApiException e) when(e.Response.Status == (int)System.Net.HttpStatusCode.BadRequest)
            {
                Logger.LogError($"Failed to set repository auto merge policies: {e.Response.Content}");
                return(Constants.ErrorCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, $"Failed to set merge policies.");
                return(Constants.ErrorCode);
            }
        }