Exemple #1
0
        public override async Task <int> ExecuteAsync()
        {
            DarcSettings darcSettings = LocalCommands.GetSettings(_options, Logger);
            // No need to set up a git type or PAT here.
            Remote remote = new Remote(darcSettings, Logger);

            try
            {
                Subscription deletedSubscription = await remote.DeleteSubscriptionAsync(_options.Id);

                Console.WriteLine($"Successfully deleted subscription with id '{_options.Id}'");
                return(Constants.SuccessCode);
            }
            catch (ApiErrorException e) when(e.Response.StatusCode == HttpStatusCode.NotFound)
            {
                // Not found is fine to ignore.  If we get this, it will be an aggregate exception with an inner API exception
                // that has a response message code of NotFound.  Return success.
                Console.WriteLine($"Subscription with id '{_options.Id}' does not exist.");
                return(Constants.SuccessCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, $"Failed to delete subscription with id '{_options.Id}'");
                return(Constants.ErrorCode);
            }
        }
Exemple #2
0
        public override async Task <int> ExecuteAsync()
        {
            DependencyType type = _options.Type.ToLower() == "toolset" ? DependencyType.Toolset : DependencyType.Product;

            Local local = new Local(LocalCommands.GetGitDir(Logger), Logger);

            DependencyDetail dependency = new DependencyDetail
            {
                Name    = _options.Name,
                Version = _options.Version ?? string.Empty,
                RepoUri = _options.RepoUri ?? string.Empty,
                Commit  = _options.Commit ?? string.Empty
            };

            try
            {
                await local.AddDependenciesAsync(dependency, type);

                return(Constants.SuccessCode);
            }
            catch (Exception exc)
            {
                Logger.LogError(exc, $"Something failed while adding dependency '{dependency.Name}' {dependency.Version}.");
                return(Constants.ErrorCode);
            }
        }
Exemple #3
0
 public void ClearAll()
 {
     RelatedConnections.Clear();
     RelatedCommands.Clear();
     RelatedStackTraces.Clear();
     RelatedTrafficUrls.Clear();
     RelatedTrafficWebRequests.Clear();
     ApplicationIdentities.Clear();
     Contexts.Clear();
     RelatedTransactions.Clear();
     LocalCommands.Clear();
 }
Exemple #4
0
 public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst)
 {
     // Track that we've seen the function, but don't analyze the body.
     // the body will be analyzed when the function is called.
     // If we tried to analyze the body now, we may find invocations of
     // functions that will be defined later.
     if (LocalCommands.ContainsKey(functionDefinitionAst.Name))
     {
         ValidationError("Overwriting existing function", functionDefinitionAst.Extent);
     }
     LocalCommands = LocalCommands.SetItem(functionDefinitionAst.Name, functionDefinitionAst);
     return(AstVisitAction.SkipChildren);
 }
Exemple #5
0
        public override async Task <int> ExecuteAsync()
        {
            Local local = new Local(LocalCommands.GetGitDir(Logger), Logger);

            try
            {
                IEnumerable <DependencyDetail> dependencies = await local.GetDependenciesAsync(_options.Name);

                if (!string.IsNullOrEmpty(_options.Name))
                {
                    DependencyDetail dependency = dependencies.Where(d => d.Name.Equals(_options.Name, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

                    if (dependency == null)
                    {
                        throw new Exception($"A dependency with name '{_options.Name}' was not found...");
                    }

                    LogDependency(dependency);
                }

                foreach (DependencyDetail dependency in dependencies)
                {
                    LogDependency(dependency);

                    Console.WriteLine();
                }

                return(Constants.SuccessCode);
            }
            catch (Exception exc)
            {
                if (!string.IsNullOrEmpty(_options.Name))
                {
                    Logger.LogError(exc, $"Something failed while querying for local dependency '{_options.Name}'.");
                }
                else
                {
                    Logger.LogError(exc, "Something failed while querying for local dependencies.");
                }

                return(Constants.ErrorCode);
            }
        }
Exemple #6
0
        private void AnalyzeCommandInvocation(CommandAst commandAst, string commandName)
        {
            bool isModuleFunction = ModuleCommands.ContainsKey(commandName);

            if (isModuleFunction)
            {
                // nothing to analyze, it's in another module.
                return;
            }

            bool isLocalFunction = LocalCommands.TryGetValue(commandName, out var functionDefinition);

            if (isLocalFunction)
            {
                // visit the invoked function's body
                var result = CommandAnalyzer.AnalyzeAst(this.Directory, functionDefinition.Body, LocalCommands, ModuleCommands);
                MergeResult(result);
                return;
            }

            ValidationError(commandName + " is not defined", commandAst.Extent);
        }
Exemple #7
0
        /// <summary>
        /// Retrieve information about the default association between builds of a specific branch/repo
        /// and a channel.
        /// </summary>
        /// <returns></returns>
        public override async Task <int> ExecuteAsync()
        {
            try
            {
                DarcSettings darcSettings = LocalCommands.GetSettings(_options, Logger);
                // No need to set up a git type or PAT here.
                Remote remote = new Remote(darcSettings, Logger);

                var defaultChannels = (await remote.GetDefaultChannelsAsync()).Where(defaultChannel =>
                {
                    return((string.IsNullOrEmpty(_options.SourceRepository) ||
                            defaultChannel.Repository.Contains(_options.SourceRepository, StringComparison.OrdinalIgnoreCase)) &&
                           (string.IsNullOrEmpty(_options.Branch) ||
                            defaultChannel.Branch.Contains(_options.Branch, StringComparison.OrdinalIgnoreCase)) &&
                           (string.IsNullOrEmpty(_options.Channel) ||
                            defaultChannel.Channel.Name.Contains(_options.Channel, StringComparison.OrdinalIgnoreCase)));
                });

                if (defaultChannels.Count() == 0)
                {
                    Console.WriteLine("No matching channels were found.");
                }

                // Write out a simple list of each channel's name
                foreach (var defaultChannel in defaultChannels)
                {
                    Console.WriteLine($"{defaultChannel.Repository} @ {defaultChannel.Branch} -> {defaultChannel.Channel.Name}");
                }

                return(Constants.SuccessCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error: Failed to retrieve default channel information.");
                return(Constants.ErrorCode);
            }
        }
Exemple #8
0
        /// <summary>
        /// Retrieve information about channels
        /// </summary>
        /// <param name="options">Command line options</param>
        /// <returns>Process exit code.</returns>
        public override async Task <int> ExecuteAsync()
        {
            try
            {
                DarcSettings darcSettings = LocalCommands.GetSettings(_options, Logger);
                // No need to set up a git type or PAT here.
                Remote remote = new Remote(darcSettings, Logger);

                var allChannels = await remote.GetChannelsAsync();

                // Write out a simple list of each channel's name
                foreach (var channel in allChannels)
                {
                    Console.WriteLine(channel.Name);
                }

                return(Constants.SuccessCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error: Failed to retrieve channels");
                return(Constants.ErrorCode);
            }
        }
Exemple #9
0
        /// <summary>
        /// Implements the 'add-subscription' operation
        /// </summary>
        /// <param name="options"></param>
        public override async Task <int> ExecuteAsync()
        {
            DarcSettings darcSettings = LocalCommands.GetSettings(_options, Logger);
            // No need to set up a git type or PAT here.
            Remote remote = new Remote(darcSettings, Logger);

            if (_options.IgnoreChecks.Count() > 0 && !_options.AllChecksSuccessfulMergePolicy)
            {
                Logger.LogError($"--ignore-checks must be combined with --all-checks-passed");
                return(Constants.ErrorCode);
            }
            // Parse the merge policies
            List <MergePolicy> mergePolicies = new List <MergePolicy>();

            if (_options.NoExtraCommitsMergePolicy)
            {
                mergePolicies.Add(new MergePolicy("NoExtraCommits", null));
            }
            if (_options.AllChecksSuccessfulMergePolicy)
            {
                mergePolicies.Add(new MergePolicy("AllChecksSuccessful", new Dictionary <string, object>
                {
                    { "ignoreChecks", _options.IgnoreChecks }
                }));
            }
            if (_options.RequireChecksMergePolicy.Count() > 0)
            {
                mergePolicies.Add(new MergePolicy("RequireChecks", new Dictionary <string, object>
                {
                    { "checks", _options.RequireChecksMergePolicy }
                }));
            }

            string channel          = _options.Channel;
            string sourceRepository = _options.SourceRepository;
            string targetRepository = _options.TargetRepository;
            string targetBranch     = _options.TargetBranch;
            string updateFrequency  = _options.UpdateFrequency;

            // If in quiet (non-interactive mode), ensure that all options were passed, then
            // just call the remote API
            if (_options.Quiet)
            {
                if (string.IsNullOrEmpty(channel) ||
                    string.IsNullOrEmpty(sourceRepository) ||
                    string.IsNullOrEmpty(targetRepository) ||
                    string.IsNullOrEmpty(targetBranch) ||
                    string.IsNullOrEmpty(updateFrequency) ||
                    !Constants.AvailableFrequencies.Contains(updateFrequency, StringComparer.OrdinalIgnoreCase))
                {
                    Logger.LogError($"Missing input parameters for the subscription. Please see command help or remove --quiet/-q for interactive mode");
                    return(Constants.ErrorCode);
                }
            }
            else
            {
                // Grab existing subscriptions to get suggested values.
                // TODO: When this becomes paged, set a max number of results to avoid
                // pulling too much.
                var suggestedRepos    = remote.GetSubscriptionsAsync();
                var suggestedChannels = remote.GetChannelsAsync();

                // Help the user along with a form.  We'll use the API to gather suggested values
                // from existing subscriptions based on the input parameters.
                AddSubscriptionPopUp initEditorPopUp =
                    new AddSubscriptionPopUp("add-subscription/add-subscription-todo",
                                             Logger,
                                             channel,
                                             sourceRepository,
                                             targetRepository,
                                             targetBranch,
                                             updateFrequency,
                                             mergePolicies,
                                             (await suggestedChannels).Select(suggestedChannel => suggestedChannel.Name),
                                             (await suggestedRepos).SelectMany(subscription => new List <string> {
                    subscription.SourceRepository, subscription.TargetRepository
                }),
                                             Constants.AvailableFrequencies,
                                             Constants.AvailableMergePolicyYamlHelp);

                UxManager uxManager = new UxManager(Logger);
                int       exitCode  = uxManager.PopUp(initEditorPopUp);
                if (exitCode != Constants.SuccessCode)
                {
                    return(exitCode);
                }
                channel          = initEditorPopUp.Channel;
                sourceRepository = initEditorPopUp.SourceRepository;
                targetRepository = initEditorPopUp.TargetRepository;
                targetBranch     = initEditorPopUp.TargetBranch;
                updateFrequency  = initEditorPopUp.UpdateFrequency;
                mergePolicies    = initEditorPopUp.MergePolicies;
            }

            try
            {
                var newSubscription = await remote.CreateSubscriptionAsync(channel,
                                                                           sourceRepository,
                                                                           targetRepository,
                                                                           targetBranch,
                                                                           updateFrequency,
                                                                           mergePolicies);

                Console.WriteLine($"Successfully created new subscription with id '{newSubscription.Id}'.");
                return(Constants.SuccessCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, $"Failed to create subscription.");
                return(Constants.ErrorCode);
            }
        }
Exemple #10
0
        public override async Task <int> ExecuteAsync()
        {
            try
            {
                DarcSettings darcSettings = LocalCommands.GetSettings(_options, Logger);

                // No need to set up a git type or PAT here.
                Remote remote = new Remote(darcSettings, Logger);

                var subscriptions = (await remote.GetSubscriptionsAsync()).Where(subscription =>
                {
                    return((string.IsNullOrEmpty(_options.TargetRepository) ||
                            subscription.TargetRepository.Contains(_options.TargetRepository, StringComparison.OrdinalIgnoreCase)) &&
                           (string.IsNullOrEmpty(_options.TargetBranch) ||
                            subscription.TargetBranch.Contains(_options.TargetBranch, StringComparison.OrdinalIgnoreCase)) &&
                           (string.IsNullOrEmpty(_options.SourceRepository) ||
                            subscription.SourceRepository.Contains(_options.SourceRepository, StringComparison.OrdinalIgnoreCase)) &&
                           (string.IsNullOrEmpty(_options.Channel) ||
                            subscription.Channel.Name.Contains(_options.Channel, StringComparison.OrdinalIgnoreCase)));
                });

                if (subscriptions.Count() == 0)
                {
                    Console.WriteLine("No subscriptions found matching the specified criteria.");
                }

                // Based on the current output schema, sort by source repo, target repo, target branch, etc.
                // Concat the input strings as a simple sorting mechanism.
                foreach (var subscription in subscriptions.OrderBy(subscription =>
                                                                   $"{subscription.SourceRepository}{subscription.Channel}{subscription.TargetRepository}{subscription.TargetBranch}"))
                {
                    Console.WriteLine($"{subscription.SourceRepository} ({subscription.Channel.Name}) ==> '{subscription.TargetRepository}' ('{subscription.TargetBranch}')");
                    Console.WriteLine($"  - Id: {subscription.Id}");
                    Console.WriteLine($"  - Update Frequency: {subscription.Policy.UpdateFrequency}");
                    Console.WriteLine($"  - Merge Policies:");
                    foreach (var mergePolicy in subscription.Policy.MergePolicies)
                    {
                        Console.WriteLine($"    {mergePolicy.Name}");
                        foreach (var mergePolicyProperty in mergePolicy.Properties)
                        {
                            // The merge policy property is a key value pair.  For formatting, turn it into a string.
                            // It's often a JToken, so handle appropriately
                            // 1. If the number of lines in the string is 1, write on same line as key
                            // 2. If the number of lines in the string is more than one, start on new
                            //    line and indent.
                            string   valueString = mergePolicyProperty.Value.ToString();
                            string[] valueLines  = valueString.Split(System.Environment.NewLine);
                            string   keyString   = $"      {mergePolicyProperty.Key} = ";
                            Console.Write(keyString);
                            if (valueLines.Length == 1)
                            {
                                Console.WriteLine(valueString);
                            }
                            else
                            {
                                string indentString = new string(' ', keyString.Length);
                                Console.WriteLine();
                                foreach (string line in valueLines)
                                {
                                    Console.WriteLine($"{indentString}{line}");
                                }
                            }
                        }
                    }
                    Console.WriteLine($"  - Last Build: {(subscription.LastAppliedBuild != null ? subscription.LastAppliedBuild.BuildNumber : "N/A")}");
                }
                return(Constants.SuccessCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error: Failed to retrieve subscriptions");
                return(Constants.ErrorCode);
            }
        }