public bool Process(IPostAction actionConfig, ICreationResult templateCreationResult, string outputBasePath)
        {
            if (templateCreationResult.PrimaryOutputs.Count == 0)
            {
                Reporter.Output.WriteLine("No Primary Outputs to restore");
                return(true);
            }

            bool allSucceeded = true;

            foreach (ICreationPath output in templateCreationResult.PrimaryOutputs)
            {
                string  pathToRestore  = !string.IsNullOrEmpty(outputBasePath) ? Path.Combine(outputBasePath, output.Path) : output.Path;
                Command restoreCommand = Command.CreateDotNet("restore", new[] { pathToRestore });
                restoreCommand.CaptureStdOut();
                restoreCommand.CaptureStdErr();

                Reporter.Output.WriteLine($"Running 'dotnet restore' on {pathToRestore}");
                var commandResult = restoreCommand.Execute();
                Reporter.Output.WriteLine(commandResult.StdOut);

                if (commandResult.ExitCode != 0)
                {
                    Reporter.Output.WriteLine("restore failed:");
                    Reporter.Output.WriteLine($"StdErr: {commandResult.StdErr}");
                    Reporter.Output.WriteLine();
                    allSucceeded = false;
                }
            }

            return(allSucceeded);
        }
Esempio n. 2
0
        private bool AskUserIfActionShouldRun(IPostAction action)
        {
            const string YesAnswer = "Y";
            const string NoAnswer  = "N";

            Reporter.Output.WriteLine(LocalizableStrings.PostActionPromptHeader);
            if (!string.IsNullOrWhiteSpace(action.Description))
            {
                Reporter.Output.WriteLine(string.Format(LocalizableStrings.PostActionDescription, action.Description));
            }
            // actual command that will be run by 'Run script' post action
            if (action.Args != null && action.Args.TryGetValue("executable", out string?executable))
            {
                action.Args.TryGetValue("args", out string?commandArgs);
                Reporter.Output.WriteLine(string.Format(LocalizableStrings.PostActionCommand, $"{executable} {commandArgs}").Bold().Red());
            }
            Reporter.Output.WriteLine(string.Format(LocalizableStrings.PostActionPromptRequest, YesAnswer, NoAnswer));

            do
            {
                string input = _inputGetter();

                if (input.Equals(YesAnswer, StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }
                else if (input.Equals(NoAnswer, StringComparison.OrdinalIgnoreCase))
                {
                    return(false);
                }

                Reporter.Output.WriteLine(string.Format(LocalizableStrings.PostActionInvalidInputRePrompt, input, YesAnswer, NoAnswer));
            }while (true);
        }
        public bool Process(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationResult templateCreationResult, string outputBasePath)
        {
            if (string.IsNullOrEmpty(outputBasePath))
            {
                environment.Host.LogMessage(LocalizableStrings.AddRefPostActionUnresolvedProjFile);
            }

            HashSet <string> extensionLimiters = new HashSet <string>(StringComparer.Ordinal);

            if (actionConfig.Args.TryGetValue("projectFileExtensions", out string projectFileExtensions))
            {
                if (projectFileExtensions.Contains("/") || projectFileExtensions.Contains("\\") || projectFileExtensions.Contains("*"))
                {
                    // these must be literals
                    environment.Host.LogMessage(LocalizableStrings.AddRefPostActionMisconfigured);
                    return(false);
                }

                extensionLimiters.UnionWith(projectFileExtensions.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            }

            IReadOnlyList <string> nearestProjectFilesFound = FindProjFileAtOrAbovePath(environment.Host.FileSystem, outputBasePath, extensionLimiters);

            return(AddReference(environment, actionConfig, nearestProjectFilesFound));
        }
Esempio n. 4
0
        private bool AskUserIfActionShouldRun(IPostAction action, Func <string> inputGetter)
        {
            const string YesAnswer = "Y";
            const string NoAnswer  = "N";

            Reporter.Output.WriteLine(LocalizableStrings.PostActionPromptHeader);
            DisplayInstructionsForAction(action);

            Reporter.Output.WriteLine(string.Format(LocalizableStrings.PostActionPromptRequest, YesAnswer, NoAnswer));

            do
            {
                string input = inputGetter();

                if (input.Equals(YesAnswer, StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }
                else if (input.Equals(NoAnswer, StringComparison.OrdinalIgnoreCase))
                {
                    return(false);
                }

                Reporter.Output.WriteLine(string.Format(LocalizableStrings.PostActionInvalidInputRePrompt, input, YesAnswer, NoAnswer));
            }while (true);
        }
        public bool Process(IEngineEnvironmentSettings settings, IPostAction actionConfig, ICreationResult templateCreationResult, string outputBasePath)
        {
            bool allSucceeded = true;

            settings.Host.LogMessage(string.Format(LocalizableStrings.RunningCommand, actionConfig.Args["executable"] + " " + actionConfig.Args["args"]));
            System.Diagnostics.Process commandResult = System.Diagnostics.Process.Start(new ProcessStartInfo
            {
                RedirectStandardError  = true,
                RedirectStandardOutput = true,
                UseShellExecute        = false,
                CreateNoWindow         = false,
                WorkingDirectory       = outputBasePath,
                FileName  = actionConfig.Args["executable"],
                Arguments = actionConfig.Args["args"]
            });

            commandResult.WaitForExit();

            if (commandResult.ExitCode != 0)
            {
                string error = commandResult.StandardError.ReadToEnd();
                settings.Host.LogMessage(LocalizableStrings.CommandFailed);
                settings.Host.LogMessage(string.Format(LocalizableStrings.CommandOutput, error));
                settings.Host.LogMessage(string.Empty);
                allSucceeded = false;
            }
            else
            {
                settings.Host.LogMessage(LocalizableStrings.CommandSucceeded);
            }

            return(allSucceeded);
        }
Esempio n. 6
0
        private PostActionExecutionStatus ProcessAction(
            ICreationEffects creationEffects,
            ICreationResult creationResult,
            string outputBaseDirectory,
            IPostAction action,
            IPostActionProcessor actionProcessor)
        {
            if (actionProcessor is PostActionProcessor2Base actionProcessor2Base)
            {
                actionProcessor2Base.Callbacks = _callbacks;
            }

            //catch all exceptions on post action execution
            //post actions can be added using components and it's not sure if they handle exceptions properly
            try
            {
                if (actionProcessor.Process(_environment, action, creationEffects, creationResult, outputBaseDirectory))
                {
                    return(PostActionExecutionStatus.Success);
                }

                Reporter.Error.WriteLine(LocalizableStrings.PostActionFailedInstructionHeader);
                DisplayInstructionsForAction(action, useErrorOutput: true);
                return(PostActionExecutionStatus.Failure);
            }
            catch (Exception e)
            {
                Reporter.Error.WriteLine(LocalizableStrings.PostActionFailedInstructionHeader);
                Reporter.Verbose.WriteLine(string.Format(LocalizableStrings.Generic_Details, e.ToString()));
                DisplayInstructionsForAction(action, useErrorOutput: true);
                return(PostActionExecutionStatus.Failure);
            }
        }
Esempio n. 7
0
        public bool Process(IEngineEnvironmentSettings settings, IPostAction actionConfig, ICreationResult templateCreationResult, string outputBasePath)
        {
            if (templateCreationResult.PrimaryOutputs.Count == 0)
            {
                settings.Host.LogMessage(LocalizableStrings.NoPrimaryOutputsToRestore);
                return(true);
            }

            bool allSucceeded = true;

            foreach (ICreationPath output in templateCreationResult.PrimaryOutputs)
            {
                string pathToRestore  = !string.IsNullOrEmpty(outputBasePath) ? Path.Combine(outputBasePath, output.Path) : output.Path;
                Dotnet restoreCommand = Dotnet.Restore(pathToRestore);
                restoreCommand.CaptureStdOut();
                restoreCommand.CaptureStdErr();

                settings.Host.LogMessage(string.Format(LocalizableStrings.RunningDotnetRestoreOn, pathToRestore));
                Dotnet.Result commandResult = restoreCommand.Execute();

                if (commandResult.ExitCode != 0)
                {
                    settings.Host.LogMessage(LocalizableStrings.RestoreFailed);
                    settings.Host.LogMessage(string.Format(LocalizableStrings.CommandOutput, commandResult.StdOut + Environment.NewLine + Environment.NewLine + commandResult.StdErr));
                    settings.Host.LogMessage(string.Empty);
                    allSucceeded = false;
                }
                else
                {
                    settings.Host.LogMessage(LocalizableStrings.RestoreSucceeded);
                }
            }

            return(allSucceeded);
        }
 public bool Process(IPostAction actionConfig, ICreationResult templateCreationResult, string outputBasePath)
 {
     Reporter.Output.WriteLine(actionConfig.Description);
     Reporter.Output.WriteLine(actionConfig.ManualInstructions);
     Reporter.Output.WriteLine();
     return(true);
 }
Esempio n. 9
0
 static bool IsInstallPackagePostAction(IPostAction action)
 {
     return(action.ActionId == addReferencePostActionId &&
            action.Args != null &&
            action.Args.TryGetValue("referenceType", out string referenceType) &&
            StringComparer.OrdinalIgnoreCase.Equals(referenceType, "package"));
 }
Esempio n. 10
0
 public ChainedPostActionDestination(IDestination next, IPostAction postAction)
     : base(next)
 {
     Guard.NotNull(() => next, next);
     Guard.NotNull(() => postAction, postAction);
     this.next       = next;
     this.postAction = postAction;
 }
 private string GetSolutionFolder(IPostAction actionConfig)
 {
     if (actionConfig.Args != null && actionConfig.Args.TryGetValue("solutionFolder", out string solutionFolder))
     {
         return(solutionFolder);
     }
     return(string.Empty);
 }
        public bool Process(IEngineEnvironmentSettings environment, IPostAction action, ICreationEffects2 creationEffects, ICreationResult templateCreationResult, string outputBasePath)
        {
            IReadOnlyList <string> allTargets = null;

            if (action.Args.TryGetValue("targetFiles", out string singleTarget) && singleTarget != null)
            {
                JToken config = JToken.Parse(singleTarget);

                if (config.Type == JTokenType.String)
                {
                    allTargets = singleTarget.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                }
                else if (config is JArray arr)
                {
                    List <string> parts = new List <string>();

                    foreach (JToken token in arr)
                    {
                        if (token.Type != JTokenType.String)
                        {
                            continue;
                        }

                        parts.Add(token.ToString());
                    }

                    if (parts.Count > 0)
                    {
                        allTargets = parts;
                    }
                }
            }
            else
            {
                //If the author didn't opt in to the new behavior by using "targetFiles", do things the old way
                return(Process(environment, action, templateCreationResult, outputBasePath));
            }

            if (allTargets is null)
            {
                return(Process(environment, action, creationEffects.CreationResult, outputBasePath));
            }

            bool success = true;

            foreach (string target in allTargets)
            {
                success &= AddReference(environment, action, GetTargetForSource(creationEffects, target));

                if (!success)
                {
                    return(false);
                }
            }

            return(true);
        }
        private bool ProcessAction(IPostAction action, IPostActionProcessor actionProcessor)
        {
            if (actionProcessor is IPostActionProcessor2 actionProcessor2 && _creationResult.CreationEffects is ICreationEffects2 creationEffects)
            {
                return(actionProcessor2.Process(_environment, action, creationEffects, _creationResult.ResultInfo, _creationResult.OutputBaseDirectory));
            }

            return(actionProcessor.Process(_environment, action, _creationResult.ResultInfo, _creationResult.OutputBaseDirectory));
        }
        public TemplateDefinedPostAction(string relatedTemplate, IPostAction templateDefinedPostAction)
            : base(relatedTemplate)
        {
            ContinueOnError = templateDefinedPostAction.ContinueOnError;

            if (IsIdsMatch(templateDefinedPostAction))
            {
                Args = templateDefinedPostAction.Args;
            }
        }
        public bool Process(IEngineEnvironmentSettings settings, IPostAction actionConfig, ICreationResult templateCreationResult, string outputBasePath)
        {
            Console.WriteLine(string.Format(LocalizableStrings.PostActionDescription, actionConfig.Description));
            Console.WriteLine(string.Format(LocalizableStrings.PostActionInstructions, actionConfig.ManualInstructions));

            if (actionConfig.Args != null && actionConfig.Args.TryGetValue("executable", out string executable))
            {
                actionConfig.Args.TryGetValue("args", out string commandArgs);
                Reporter.Output.WriteLine(string.Format(LocalizableStrings.PostActionCommand, $"{executable} {commandArgs}").Bold().Red());
            }

            return(true);
        }
        public bool Process(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationResult templateCreationResult, string outputBasePath)
        {
            if (templateCreationResult.PrimaryOutputs.Count == 0)
            {
                environment.Host.LogMessage(LocalizableStrings.NoPrimaryOutputsToRestore);
                return(true);
            }

            bool allSucceeded = true;

            foreach (ICreationPath output in templateCreationResult.PrimaryOutputs)
            {
                string pathToRestore = !string.IsNullOrEmpty(outputBasePath) ? Path.Combine(outputBasePath, output.Path) : output.Path;

                if (string.IsNullOrEmpty(pathToRestore) ||
                    (!Directory.Exists(pathToRestore) &&
                     !Path.GetExtension(pathToRestore).EndsWith("proj", StringComparison.OrdinalIgnoreCase) &&
                     !Path.GetExtension(pathToRestore).Equals(".sln", StringComparison.OrdinalIgnoreCase)
                    ))
                {
                    continue;
                }

                environment.Host.LogMessage(string.Format(LocalizableStrings.RunningDotnetRestoreOn, pathToRestore));

                // Prefer to restore the project in-proc vs. creating a new process.
                bool succeeded = false;
                if (Callbacks.RestoreProject != null)
                {
                    succeeded = Callbacks.RestoreProject(pathToRestore);
                }
                else
                {
                    Dotnet        restoreCommand = Dotnet.Restore(pathToRestore).ForwardStdErr().ForwardStdOut();
                    Dotnet.Result commandResult  = restoreCommand.Execute();
                    succeeded = commandResult.ExitCode == 0;
                }

                if (!succeeded)
                {
                    environment.Host.LogMessage(LocalizableStrings.RestoreFailed);
                    allSucceeded = false;
                }
                else
                {
                    environment.Host.LogMessage(LocalizableStrings.RestoreSucceeded);
                }
            }

            return(allSucceeded);
        }
Esempio n. 17
0
 public bool Process(
     IEngineEnvironmentSettings environment,
     IPostAction action,
     ICreationEffects creationEffects,
     ICreationResult templateCreationResult,
     string outputBasePath)
 {
     if (string.IsNullOrWhiteSpace(outputBasePath))
     {
         throw new ArgumentException($"'{nameof(outputBasePath)}' cannot be null or whitespace.", nameof(outputBasePath));
     }
     outputBasePath = Path.GetFullPath(outputBasePath);
     return(ProcessInternal(environment, action, creationEffects, templateCreationResult, outputBasePath));
 }
Esempio n. 18
0
        public bool Process(IEngineEnvironmentSettings settings, IPostAction actionConfig, ICreationResult templateCreationResult, string outputBasePath)
        {
            bool allSucceeded = true;

            actionConfig.Args.TryGetValue("args", out string args);

            bool redirectStandardOutput = true;

            // By default, standard out is redirected.
            // Only redirect when the configuration says "redirectStandardOutput = false"
            if (actionConfig.Args.TryGetValue("redirectStandardOutput", out string redirectStandardOutputString) &&
                string.Equals(redirectStandardOutputString, "false", StringComparison.OrdinalIgnoreCase))
            {
                redirectStandardOutput = false;
            }

            settings.Host.LogMessage(string.Format(LocalizableStrings.RunningCommand, actionConfig.Args["executable"] + " " + args));

            string resolvedExecutablePath = ResolveExecutableFilePath(actionConfig.Args["executable"], outputBasePath);

            System.Diagnostics.Process commandResult = System.Diagnostics.Process.Start(new ProcessStartInfo
            {
                RedirectStandardError  = true,
                RedirectStandardOutput = redirectStandardOutput,
                UseShellExecute        = false,
                CreateNoWindow         = false,
                WorkingDirectory       = outputBasePath,
                FileName  = resolvedExecutablePath,
                Arguments = args
            });

            commandResult.WaitForExit();

            if (commandResult.ExitCode != 0)
            {
                string error = commandResult.StandardError.ReadToEnd();
                settings.Host.LogMessage(LocalizableStrings.CommandFailed);
                settings.Host.LogMessage(string.Format(LocalizableStrings.CommandOutput, error));
                settings.Host.LogMessage(string.Empty);
                allSucceeded = false;
            }
            else
            {
                settings.Host.LogMessage(LocalizableStrings.CommandSucceeded);
            }

            return(allSucceeded);
        }
        public bool Process(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationResult templateCreationResult, string outputBasePath)
        {
            bool allSucceeded = true;

            foreach (KeyValuePair <string, string> entry in actionConfig.Args)
            {
                string[] values;
                try
                {
                    JArray valueArray = JArray.Parse(entry.Value);
                    values = new string[valueArray.Count];

                    for (int i = 0; i < valueArray.Count; ++i)
                    {
                        values[i] = valueArray[i].ToString();
                    }
                }
                catch
                {
                    values = new[] { entry.Value };
                }

                foreach (string file in values)
                {
                    Process commandResult = System.Diagnostics.Process.Start(new ProcessStartInfo
                    {
                        RedirectStandardError  = false,
                        RedirectStandardOutput = false,
                        UseShellExecute        = true,
                        CreateNoWindow         = false,
                        WorkingDirectory       = outputBasePath,
                        FileName  = "/bin/sh",
                        Arguments = $"-c \"chmod {entry.Key} {file}\""
                    });

                    commandResult.WaitForExit();

                    if (commandResult.ExitCode != 0)
                    {
                        environment.Host.LogMessage(string.Format(LocalizableStrings.UnableToSetPermissions, entry.Key, file));
                        allSucceeded = false;
                    }
                }
            }

            return(allSucceeded);
        }
Esempio n. 20
0
        // If the action is just instructions, display them and be done with the action.
        // Otherwise ask the user if they want to run the action.
        // If they do, run it, and return the result.
        // Otherwise return false, indicating the action was not run.
        private bool HandlePromptRequired(IPostAction action, IPostActionProcessor actionProcessor, Func <string> inputGetter)
        {
            if (actionProcessor is InstructionDisplayPostActionProcessor)
            {   // it's just instructions, no need to prompt
                bool result = ProcessAction(action, actionProcessor);
                return(result);
            }

            // TODO: determine if this is the proper way to get input.
            bool userWantsToRunAction = AskUserIfActionShouldRun(action, inputGetter);

            if (!userWantsToRunAction)
            {
                return(false);
            }

            return(ProcessAction(action, actionProcessor));
        }
        private bool IsIdsMatch(IPostAction templateDefinedPostAction)
        {
            if (templateDefinedPostAction.ActionId != ActionId)
            {
                string errorMsg = string.Format(StringRes.PostActionIdsNotMatchError, templateDefinedPostAction.ActionId.ToString(), ActionId.ToString(), RelatedTemplate);
                if (!ContinueOnError)
                {
                    throw new Exception(errorMsg);
                }
                else
                {
                    AppHealth.Current.Error.TrackAsync(errorMsg).FireAndForget();
                    return(false);
                }
            }

            return(true);
        }
Esempio n. 22
0
        private void DisplayInstructionsForAction(IPostAction action, bool useErrorOutput = false)
        {
            if (string.IsNullOrWhiteSpace(action.ManualInstructions))
            {
                //no manual instructions was written by template author for post action
                return;
            }

            Reporter stream = useErrorOutput ? Reporter.Error : Reporter.Output;

            stream.WriteLine(string.Format(LocalizableStrings.PostActionInstructions, action.ManualInstructions));

            // if the post action executes the command ('Run script' post action), additionally display command to be executed.
            if (action.Args != null && action.Args.TryGetValue("executable", out string?executable))
            {
                action.Args.TryGetValue("args", out string?commandArgs);
                stream.WriteLine(string.Format(LocalizableStrings.PostActionCommand, $"{executable} {commandArgs}").Bold().Red());
            }
        }
        public bool Process(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationResult templateCreationResult, string outputBasePath)
        {
            if (string.IsNullOrEmpty(outputBasePath))
            {
                environment.Host.LogMessage(string.Format(LocalizableStrings.AddProjToSlnPostActionUnresolvedSlnFile));
                return(false);
            }

            IReadOnlyList <string> nearestSlnFilesFould = FindSolutionFilesAtOrAbovePath(environment.Host.FileSystem, outputBasePath);

            if (nearestSlnFilesFould.Count != 1)
            {
                environment.Host.LogMessage(LocalizableStrings.AddProjToSlnPostActionUnresolvedSlnFile);
                return(false);
            }

            if (!TryGetProjectFilesToAdd(environment, actionConfig, templateCreationResult, outputBasePath, out IReadOnlyList <string> projectFiles))
            {
                environment.Host.LogMessage(LocalizableStrings.AddProjToSlnPostActionNoProjFiles);
                return(false);
            }

            string solutionFolder      = GetSolutionFolder(actionConfig);
            Dotnet addProjToSlnCommand = Dotnet.AddProjectsToSolution(nearestSlnFilesFould[0], projectFiles, GetSolutionFolder(actionConfig));

            addProjToSlnCommand.CaptureStdOut();
            addProjToSlnCommand.CaptureStdErr();
            environment.Host.LogMessage(string.Format(LocalizableStrings.AddProjToSlnPostActionRunning, addProjToSlnCommand.Command));
            Dotnet.Result commandResult = addProjToSlnCommand.Execute();

            if (commandResult.ExitCode != 0)
            {
                environment.Host.LogMessage(string.Format(LocalizableStrings.AddProjToSlnPostActionFailed, string.Join(" ", projectFiles), nearestSlnFilesFould[0], solutionFolder));
                environment.Host.LogMessage(string.Format(LocalizableStrings.CommandOutput, commandResult.StdOut + Environment.NewLine + Environment.NewLine + commandResult.StdErr));
                environment.Host.LogMessage(string.Empty);
                return(false);
            }
            else
            {
                environment.Host.LogMessage(string.Format(LocalizableStrings.AddProjToSlnPostActionSucceeded, string.Join(" ", projectFiles), nearestSlnFilesFould[0], solutionFolder));
                return(true);
            }
        }
Esempio n. 24
0
        TemplatePackageReference CreatePackageReference(IPostAction action)
        {
            if (!IsInstallPackagePostAction(action))
            {
                return(null);
            }

            if (!action.Args.TryGetValue("reference", out string packageId))
            {
                return(null);
            }

            if (!action.Args.TryGetValue("version", out string packageVersion))
            {
                return(null);
            }

            return(new TemplatePackageReference(packageId, packageVersion));
        }
        public bool Process(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationResult templateCreationResult, string outputBasePath)
        {
            if (templateCreationResult.PrimaryOutputs.Count == 0)
            {
                environment.Host.LogMessage(LocalizableStrings.NoPrimaryOutputsToRestore);
                return(true);
            }

            bool allSucceeded = true;

            foreach (ICreationPath output in templateCreationResult.PrimaryOutputs)
            {
                string pathToRestore = !string.IsNullOrEmpty(outputBasePath) ? Path.Combine(outputBasePath, output.Path) : output.Path;

                if (string.IsNullOrEmpty(pathToRestore) || (!Directory.Exists(pathToRestore) && !Path.GetExtension(pathToRestore).EndsWith("proj", StringComparison.OrdinalIgnoreCase)))
                {
                    continue;
                }

                Dotnet restoreCommand = Dotnet.Restore(pathToRestore);
                restoreCommand.CaptureStdOut();
                restoreCommand.CaptureStdErr();

                environment.Host.LogMessage(string.Format(LocalizableStrings.RunningDotnetRestoreOn, pathToRestore));
                Dotnet.Result commandResult = restoreCommand.Execute();

                if (commandResult.ExitCode != 0)
                {
                    environment.Host.LogMessage(LocalizableStrings.RestoreFailed);
                    environment.Host.LogMessage(string.Format(LocalizableStrings.CommandOutput, commandResult.StdOut + Environment.NewLine + Environment.NewLine + commandResult.StdErr));
                    environment.Host.LogMessage(string.Empty);
                    allSucceeded = false;
                }
                else
                {
                    environment.Host.LogMessage(LocalizableStrings.RestoreSucceeded);
                }
            }

            return(allSucceeded);
        }
Esempio n. 26
0
        // The project files to add are a subset of the primary outputs, specifically the primary outputs indicated by the primaryOutputIndexes post action argument (semicolon separated)
        // If any indexes are out of range or non-numeric, this method returns false and projectFiles is set to null.
        internal static bool TryGetProjectFilesToAdd(IPostAction actionConfig, ICreationResult templateCreationResult, string outputBasePath, [NotNullWhen(true)] out IReadOnlyList <string>?projectFiles)
        {
            List <string> filesToAdd = new List <string>();

            if ((actionConfig.Args != null) && actionConfig.Args.TryGetValue("primaryOutputIndexes", out string?projectIndexes))
            {
                foreach (string indexString in projectIndexes.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    if (int.TryParse(indexString.Trim(), out int index))
                    {
                        if (templateCreationResult.PrimaryOutputs.Count <= index || index < 0)
                        {
                            projectFiles = null;
                            return(false);
                        }

                        filesToAdd.Add(Path.GetFullPath(templateCreationResult.PrimaryOutputs[index].Path, outputBasePath));
                    }
                    else
                    {
                        projectFiles = null;
                        return(false);
                    }
                }

                projectFiles = filesToAdd;
                return(true);
            }
            else
            {
                foreach (string pathString in templateCreationResult.PrimaryOutputs.Select(x => x.Path))
                {
                    filesToAdd.Add(Path.GetFullPath(pathString, outputBasePath));
                }

                projectFiles = filesToAdd;
                return(true);
            }
        }
        // The project files to add are a subset of the primary outputs, specifically the primary outputs indicated by the primaryOutputIndexes post action arg (semicolon separated)
        // If any indexes are out of range or non-numeric, thsi method returns false and projectFiles is set to null.
        internal static bool TryGetProjectFilesToAdd(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationResult templateCreationResult, string outputBasePath, out IReadOnlyList <string> projectFiles)
        {
            List <string> filesToAdd = new List <string>();

            if ((actionConfig.Args != null) && actionConfig.Args.TryGetValue("primaryOutputIndexes", out string projectIndexes))
            {
                foreach (string indexString in projectIndexes.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    if (int.TryParse(indexString.Trim(), out int index))
                    {
                        if (templateCreationResult.PrimaryOutputs.Count <= index || index < 0)
                        {
                            projectFiles = null;
                            return(false);
                        }

                        filesToAdd.Add(Path.Combine(outputBasePath, templateCreationResult.PrimaryOutputs[index].Path));
                    }
                    else
                    {
                        projectFiles = null;
                        return(false);
                    }
                }

                projectFiles = filesToAdd;
                return(true);
            }
            else
            {
                foreach (string pathString in templateCreationResult.PrimaryOutputs.Select(x => x.Path))
                {
                    filesToAdd.Add(!string.IsNullOrEmpty(outputBasePath) ? Path.Combine(outputBasePath, pathString) : pathString);
                }

                projectFiles = filesToAdd;
                return(true);
            }
        }
        private bool AddReference(IEngineEnvironmentSettings environment, IPostAction actionConfig, IReadOnlyList <string> nearestProjectFilesFound)
        {
            if (actionConfig.Args == null || !actionConfig.Args.TryGetValue("reference", out string referenceToAdd))
            {
                environment.Host.LogMessage(LocalizableStrings.AddRefPostActionMisconfigured);
                return(false);
            }

            if (!actionConfig.Args.TryGetValue("referenceType", out string referenceType))
            {
                environment.Host.LogMessage(LocalizableStrings.AddRefPostActionMisconfigured);
                return(false);
            }

            if (nearestProjectFilesFound.Count == 1)
            {
                string        projectFile = nearestProjectFilesFound[0];
                Dotnet.Result commandResult;

                if (string.Equals(referenceType, "project", StringComparison.OrdinalIgnoreCase))
                {
                    // actually do the add ref
                    Dotnet addReferenceCommand = Dotnet.AddProjectToProjectReference(projectFile, referenceToAdd);
                    addReferenceCommand.CaptureStdOut();
                    addReferenceCommand.CaptureStdErr();
                    environment.Host.LogMessage(string.Format(LocalizableStrings.AddRefPostActionAddProjectRef, projectFile, referenceToAdd));
                    commandResult = addReferenceCommand.Execute();
                }
                else if (string.Equals(referenceType, "package", StringComparison.OrdinalIgnoreCase))
                {
                    actionConfig.Args.TryGetValue("version", out string version);

                    Dotnet addReferenceCommand = Dotnet.AddPackageReference(projectFile, referenceToAdd, version);
                    addReferenceCommand.CaptureStdOut();
                    addReferenceCommand.CaptureStdErr();
                    if (string.IsNullOrEmpty(version))
                    {
                        environment.Host.LogMessage(string.Format(LocalizableStrings.AddRefPostActionAddPackageRef, projectFile, referenceToAdd));
                    }
                    else
                    {
                        environment.Host.LogMessage(string.Format(LocalizableStrings.AddRefPostActionAddPackageRefWithVersion, projectFile, referenceToAdd, version));
                    }
                    commandResult = addReferenceCommand.Execute();
                }
                else if (string.Equals(referenceType, "framework", StringComparison.OrdinalIgnoreCase))
                {
                    environment.Host.LogMessage(string.Format(LocalizableStrings.AddRefPostActionFrameworkNotSupported, referenceToAdd));
                    return(false);
                }
                else
                {
                    environment.Host.LogMessage(string.Format(LocalizableStrings.AddRefPostActionUnsupportedRefType, referenceType));
                    return(false);
                }

                if (commandResult.ExitCode != 0)
                {
                    environment.Host.LogMessage(string.Format(LocalizableStrings.AddRefPostActionFailed, referenceToAdd, projectFile));
                    environment.Host.LogMessage(string.Format(LocalizableStrings.CommandOutput, commandResult.StdOut + Environment.NewLine + Environment.NewLine + commandResult.StdErr));
                    environment.Host.LogMessage(string.Empty);
                    return(false);
                }
                else
                {
                    environment.Host.LogMessage(string.Format(LocalizableStrings.AddRefPostActionSucceeded, referenceToAdd, projectFile));
                    return(true);
                }
            }
            else if (nearestProjectFilesFound.Count == 0)
            {
                // no projects found. Error.
                environment.Host.LogMessage(LocalizableStrings.AddRefPostActionUnresolvedProjFile);
                return(false);
            }
            else
            {
                // multiple projects at the same level. Error.
                environment.Host.LogMessage(LocalizableStrings.AddRefPostActionUnresolvedProjFile);
                environment.Host.LogMessage(LocalizableStrings.AddRefPostActionProjFileListHeader);
                foreach (string projectFile in nearestProjectFilesFound)
                {
                    environment.Host.LogMessage(string.Format("\t{0}", projectFile));
                }

                return(false);
            }
        }
Esempio n. 29
0
        private bool DisplayInstructionsForAction(IPostAction action)
        {
            IPostActionProcessor instructionProcessor = new InstructionDisplayPostActionProcessor();

            return(ProcessAction(action, instructionProcessor));
        }
        public bool Process(IEngineEnvironmentSettings environment, IPostAction action, ICreationEffects2 creationEffects, ICreationResult templateCreationResult, string outputBasePath)
        {
            if (string.IsNullOrEmpty(outputBasePath))
            {
                environment.Host.LogMessage(string.Format(LocalizableStrings.AddProjToSlnPostActionUnresolvedSlnFile));
                return(false);
            }

            IReadOnlyList <string> nearestSlnFilesFould = FindSolutionFilesAtOrAbovePath(environment.Host.FileSystem, outputBasePath);

            if (nearestSlnFilesFould.Count != 1)
            {
                environment.Host.LogMessage(LocalizableStrings.AddProjToSlnPostActionUnresolvedSlnFile);
                return(false);
            }

            IReadOnlyList <string> projectFiles;

            if (action.Args.TryGetValue("projectFiles", out string configProjectFiles))
            {
                JToken        config      = JToken.Parse(configProjectFiles);
                List <string> allProjects = new List <string>();

                if (config is JArray arr)
                {
                    foreach (JToken globText in arr)
                    {
                        if (globText.Type != JTokenType.String)
                        {
                            continue;
                        }

                        foreach (string path in GetTargetForSource(creationEffects, globText.ToString()))
                        {
                            if (Path.GetExtension(path).EndsWith("proj", StringComparison.OrdinalIgnoreCase))
                            {
                                allProjects.Add(path);
                            }
                        }
                    }
                }
                else if (config.Type == JTokenType.String)
                {
                    foreach (string path in GetTargetForSource(creationEffects, config.ToString()))
                    {
                        if (Path.GetExtension(path).EndsWith("proj", StringComparison.OrdinalIgnoreCase))
                        {
                            allProjects.Add(path);
                        }
                    }
                }

                if (allProjects.Count == 0)
                {
                    environment.Host.LogMessage(LocalizableStrings.AddProjToSlnPostActionNoProjFiles);
                    return(false);
                }

                projectFiles = allProjects;
            }
            else
            {
                //If the author didn't opt in to the new behavior by specifying "projectFiles", use the old behavior
                return(Process(environment, action, templateCreationResult, outputBasePath));
            }

            string solutionFolder      = GetSolutionFolder(action);
            Dotnet addProjToSlnCommand = Dotnet.AddProjectsToSolution(nearestSlnFilesFould[0], projectFiles, solutionFolder);

            addProjToSlnCommand.CaptureStdOut();
            addProjToSlnCommand.CaptureStdErr();
            environment.Host.LogMessage(string.Format(LocalizableStrings.AddProjToSlnPostActionRunning, addProjToSlnCommand.Command));
            Dotnet.Result commandResult = addProjToSlnCommand.Execute();

            if (commandResult.ExitCode != 0)
            {
                environment.Host.LogMessage(string.Format(LocalizableStrings.AddProjToSlnPostActionFailed, string.Join(" ", projectFiles), nearestSlnFilesFould[0], solutionFolder));
                environment.Host.LogMessage(string.Format(LocalizableStrings.CommandOutput, commandResult.StdOut + Environment.NewLine + Environment.NewLine + commandResult.StdErr));
                environment.Host.LogMessage(string.Empty);
                return(false);
            }
            else
            {
                environment.Host.LogMessage(string.Format(LocalizableStrings.AddProjToSlnPostActionSucceeded, string.Join(" ", projectFiles), nearestSlnFilesFould[0], solutionFolder));
                return(true);
            }
        }