public bool Process(IPostAction actionConfig, ICreationResult templateCreationResult, string outputBasePath)
 {
     Reporter.Output.WriteLine(actionConfig.Description);
     Reporter.Output.WriteLine(actionConfig.ManualInstructions);
     Reporter.Output.WriteLine();
     return(true);
 }
        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);
        }
Example #3
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);
            }
        }
 public TemplateCreationResult(string message, CreationResultStatus status, string templateFullName, ICreationResult creationOutputs, string outputBaseDir)
 {
     Message             = message;
     Status              = status;
     TemplateFullName    = templateFullName;
     ResultInfo          = creationOutputs;
     OutputBaseDirectory = outputBaseDir;
 }
Example #5
0
 IEnumerable <TemplatePackageReference> GetPackageReferences(ICreationResult result)
 {
     foreach (var postAction in result.PostActions)
     {
         var packageReference = CreatePackageReference(postAction);
         if (packageReference != null)
         {
             yield return(packageReference);
         }
     }
 }
 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));
 }
Example #7
0
        async Task InstallNuGetPackages(Project project, ICreationResult result)
        {
            var packageReferences = GetPackageReferences(result).ToList();

            if (!packageReferences.Any())
            {
                return;
            }

            foreach (ItemTemplatePackageInstaller installer in AddinManager.GetExtensionObjects("/MonoDevelop/Ide/ItemTemplatePackageInstallers"))
            {
                await installer.Run(project, packageReferences);
            }
        }
        public void RunStarted(object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            DTE dte = ServiceProvider.GlobalProvider.GetService(typeof(SDTE)) as DTE;

            if (dte == null)
            {
                throw new WizardCancelledException("Unable to get DTE");
            }

            Bootstrapper bootstrapper = CreateBoostrapper();

            if (!replacementsDictionary.TryGetValue("$WizardData$", out string wizardData))
            {
                throw new WizardCancelledException("Wizard data not found: Expected a string containing the identity of the template to create");
            }

            wizardData = wizardData.Trim();
            IFilteredTemplateInfo match = bootstrapper.ListTemplates(true, x =>
            {
                if (string.Equals(x.Identity, wizardData, StringComparison.OrdinalIgnoreCase))
                {
                    return(new MatchInfo {
                        Kind = MatchKind.Exact, Location = MatchLocation.Name
                    });
                }

                return(null);
            }).FirstOrDefault(x => x.IsMatch);

            if (match == null)
            {
                throw new WizardCancelledException($"Wizard data malformed: no template found with identity {wizardData}");
            }

            ITemplateInfo info = match.Info;
            // TODO: Determine where to get the baseline name from, as needed. baselineName is a placeholder so template engine builds.
            string          baselineName = null;
            ICreationResult result       = bootstrapper.CreateAsync(info, replacementsDictionary[""], replacementsDictionary[""], ExtractParametersFromReplacementsDictionary(replacementsDictionary), SkipUpdatesCheck, baselineName).Result;

            foreach (ICreationPath path in result.PrimaryOutputs)
            {
                dte.Solution.AddFromFile(path.Path);
            }
        }
Example #9
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);
            }
        }
        protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath)
        {
            if (!actionConfig.Args.TryGetValue("executable", out string?executable) || string.IsNullOrWhiteSpace(executable))
            {
                Reporter.Error.WriteLine(LocalizableStrings.PostAction_ProcessStartProcessor_Error_ConfigMissingExecutable);
                return(false);
            }
            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;
            }
            bool redirectStandardError = true;

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

            try
            {
                string command = executable;
                if (!string.IsNullOrWhiteSpace(args))
                {
                    command = command + " " + args;
                }
                Reporter.Output.WriteLine(string.Format(LocalizableStrings.RunningCommand, command));
                string resolvedExecutablePath = ResolveExecutableFilePath(environment.Host.FileSystem, executable, outputBasePath);

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

                if (commandResult == null)
                {
                    Reporter.Error.WriteLine(LocalizableStrings.CommandFailed);
                    Reporter.Verbose.WriteLine("Unable to start sub-process.");
                    return(false);
                }

                commandResult.WaitForExit();

                if (commandResult.ExitCode != 0)
                {
                    Reporter.Error.WriteLine(LocalizableStrings.CommandFailed);
                    Reporter.Error.WriteCommandOutput(commandResult);
                    Reporter.Error.WriteLine(string.Empty);
                    return(false);
                }
                else
                {
                    Reporter.Output.WriteLine(LocalizableStrings.CommandSucceeded);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Reporter.Error.WriteLine(LocalizableStrings.CommandFailed);
                Reporter.Error.WriteLine(ex.Message);
                Reporter.Error.WriteLine(string.Empty);
                Reporter.Verbose.WriteLine(string.Format(LocalizableStrings.Generic_Details, ex.ToString()));
                return(false);
            }
        }
Example #11
0
        public async Task <TemplateCreationResult> InstantiateAsync(ITemplateInfo templateInfo, string name, string fallbackName, string outputPath, IReadOnlyDictionary <string, string> inputParameters, bool skipUpdateCheck, bool forceCreation, string baselineName)
        {
            // SettingsLoader.LoadTemplate is where the loc info should be read!!!
            // templateInfo knows enough to get at the loc, if any
            ITemplate template = _environmentSettings.SettingsLoader.LoadTemplate(templateInfo, baselineName);

            try
            {
                if (template == null)
                {
                    return(new TemplateCreationResult("Could not load template", CreationResultStatus.NotFound, templateInfo.Name));
                }

                string realName = name ?? fallbackName ?? template.DefaultName;

                if (string.IsNullOrEmpty(realName))
                {
                    return(new TemplateCreationResult("--name", CreationResultStatus.MissingMandatoryParam, template.Name));
                }

                if (template.IsNameAgreementWithFolderPreferred && string.IsNullOrEmpty(outputPath))
                {
                    outputPath = name;
                }

                ICreationResult creationResult = null;
                string          targetDir      = outputPath ?? _environmentSettings.Host.FileSystem.GetCurrentDirectory();

                try
                {
                    _paths.CreateDirectory(targetDir);
                    Stopwatch         sw = Stopwatch.StartNew();
                    IComponentManager componentManager = _environmentSettings.SettingsLoader.Components;

                    // setup separate sets of parameters to be used for GetCreationEffects() and by CreateAsync().
                    if (!TryCreateParameterSet(template, realName, inputParameters, out IParameterSet effectParams, out TemplateCreationResult resultIfParameterCreationFailed))
                    {
                        return(resultIfParameterCreationFailed);
                    }

                    IReadOnlyList <IFileChange> changes            = template.Generator.GetCreationEffects(_environmentSettings, template, effectParams, componentManager, targetDir).FileChanges;
                    IReadOnlyList <IFileChange> destructiveChanges = changes.Where(x => x.ChangeKind != ChangeKind.Create).ToList();

                    if (!forceCreation && destructiveChanges.Count > 0)
                    {
                        if (!_environmentSettings.Host.OnPotentiallyDestructiveChangesDetected(changes, destructiveChanges))
                        {
                            return(new TemplateCreationResult("Cancelled", CreationResultStatus.Cancelled, template.Name));
                        }
                    }

                    if (!TryCreateParameterSet(template, realName, inputParameters, out IParameterSet creationParams, out resultIfParameterCreationFailed))
                    {
                        return(resultIfParameterCreationFailed);
                    }

                    creationResult = await template.Generator.CreateAsync(_environmentSettings, template, creationParams, componentManager, targetDir).ConfigureAwait(false);

                    sw.Stop();
                    _environmentSettings.Host.LogTiming("Content generation time", sw.Elapsed, 0);
                    return(new TemplateCreationResult(string.Empty, CreationResultStatus.Success, template.Name, creationResult, targetDir));
                }
                catch (ContentGenerationException cx)
                {
                    string message = cx.Message;
                    if (cx.InnerException != null)
                    {
                        message += Environment.NewLine + cx.InnerException.Message;
                    }

                    return(new TemplateCreationResult(message, CreationResultStatus.CreateFailed, template.Name));
                }
                catch (Exception ex)
                {
                    return(new TemplateCreationResult(ex.Message, CreationResultStatus.CreateFailed, template.Name));
                }
            }
            finally
            {
                ReleaseMountPoints(template);
            }
        }
        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));
            System.Diagnostics.Process commandResult = System.Diagnostics.Process.Start(new ProcessStartInfo
            {
                RedirectStandardError  = true,
                RedirectStandardOutput = redirectStandardOutput,
                UseShellExecute        = false,
                CreateNoWindow         = false,
                WorkingDirectory       = outputBasePath,
                FileName  = actionConfig.Args["executable"],
                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);
        }
Example #13
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);
        }
        // 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);
            }
        }
        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);
        }
 protected abstract bool ProcessInternal(
     IEngineEnvironmentSettings environment,
     IPostAction action,
     ICreationEffects creationEffects,
     ICreationResult templateCreationResult,
     string outputBasePath);
        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);
            }
        }
        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);
        }
        protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects creationEffects, 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)
                {
                    try
                    {
                        Process?commandResult = System.Diagnostics.Process.Start(new ProcessStartInfo
                        {
                            RedirectStandardError  = false,
                            RedirectStandardOutput = false,
                            UseShellExecute        = false,
                            CreateNoWindow         = false,
                            WorkingDirectory       = outputBasePath,
                            FileName  = "/bin/sh",
                            Arguments = $"-c \"chmod {entry.Key} {file}\""
                        });

                        if (commandResult == null)
                        {
                            Reporter.Error.WriteLine(string.Format(LocalizableStrings.UnableToSetPermissions, entry.Key, file));
                            Reporter.Verbose.WriteLine("Unable to start sub-process.");
                            allSucceeded = false;
                            continue;
                        }

                        commandResult.WaitForExit();

                        if (commandResult.ExitCode != 0)
                        {
                            Reporter.Error.WriteLine(string.Format(LocalizableStrings.UnableToSetPermissions, entry.Key, file));
                            allSucceeded = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        Reporter.Error.WriteLine(string.Format(LocalizableStrings.UnableToSetPermissions, entry.Key, file));
                        Reporter.Verbose.WriteLine(string.Format(LocalizableStrings.Generic_Details, ex.ToString()));
                        allSucceeded = false;
                    }
                }
            }

            return(allSucceeded);
        }
Example #20
0
        public async Task <TemplateCreationResult> InstantiateAsync(ITemplateInfo templateInfo, string name, string fallbackName, string outputPath, IReadOnlyDictionary <string, string> inputParameters, bool skipUpdateCheck, bool forceCreation)
        {
            // SettingsLoader.LoadTemplate is where the loc info should be read!!!
            // templateInfo knows enough to get at the loc, if any
            ITemplate template = _environmentSettings.SettingsLoader.LoadTemplate(templateInfo);

            if (template == null)
            {
                return(new TemplateCreationResult("Could not load template", CreationResultStatus.NotFound, templateInfo.Name));
            }

            string realName = name ?? fallbackName ?? template.DefaultName;

            if (string.IsNullOrEmpty(realName))
            {
                return(new TemplateCreationResult("--name", CreationResultStatus.MissingMandatoryParam, template.Name));
            }

            // there should never be param errors here. If there are, the template is malformed, or the host gave an invalid value.
            IParameterSet templateParams = SetupDefaultParamValuesFromTemplateAndHost(template, realName, out IList <string> defaultParamsWithInvalidValues);

            if (defaultParamsWithInvalidValues.Any())
            {
                // TODO: create a separate status for this specific error.
                // OR, better yet: sanity check templates at install time.
                string message = string.Join(", ", defaultParamsWithInvalidValues);
                return(new TemplateCreationResult(message, CreationResultStatus.InvalidParamValues, template.Name));
            }

            ResolveUserParameters(template, templateParams, inputParameters, out IReadOnlyList <string> userParamsWithInvalidValues);
            if (userParamsWithInvalidValues.Any())
            {
                string message = string.Join(", ", userParamsWithInvalidValues);
                return(new TemplateCreationResult(message, CreationResultStatus.InvalidParamValues, template.Name));
            }

            bool missingParams = CheckForMissingRequiredParameters(templateParams, out IList <string> missingParamNames);

            if (missingParams)
            {
                return(new TemplateCreationResult(string.Join(", ", missingParamNames), CreationResultStatus.MissingMandatoryParam, template.Name));
            }

            if (template.IsNameAgreementWithFolderPreferred && string.IsNullOrEmpty(outputPath))
            {
                outputPath = name;
            }

            ICreationResult creationResult = null;
            string          targetDir      = outputPath ?? _environmentSettings.Host.FileSystem.GetCurrentDirectory();

            try
            {
                _paths.CreateDirectory(targetDir);
                Stopwatch         sw = Stopwatch.StartNew();
                IComponentManager componentManager = _environmentSettings.SettingsLoader.Components;

                IReadOnlyList <IFileChange> changes            = template.Generator.GetCreationEffects(_environmentSettings, template, templateParams, componentManager, targetDir).FileChanges;
                IReadOnlyList <IFileChange> destructiveChanges = changes.Where(x => x.ChangeKind != ChangeKind.Create).ToList();

                if (!forceCreation && destructiveChanges.Count > 0)
                {
                    if (!_environmentSettings.Host.OnPotentiallyDestructiveChangesDetected(changes, destructiveChanges))
                    {
                        return(new TemplateCreationResult("Cancelled", CreationResultStatus.Cancelled, template.Name));
                    }
                }

                creationResult = await template.Generator.CreateAsync(_environmentSettings, template, templateParams, componentManager, targetDir).ConfigureAwait(false);

                sw.Stop();
                _environmentSettings.Host.OnTimingCompleted("Content generation time", sw.Elapsed);
                return(new TemplateCreationResult(string.Empty, CreationResultStatus.Success, template.Name, creationResult, outputPath));
            }
            catch (ContentGenerationException cx)
            {
                string message = cx.Message;
                if (cx.InnerException != null)
                {
                    message += Environment.NewLine + cx.InnerException.Message;
                }

                return(new TemplateCreationResult(message, CreationResultStatus.CreateFailed, template.Name));
            }
            catch (Exception ex)
            {
                return(new TemplateCreationResult(ex.Message, CreationResultStatus.CreateFailed, template.Name));
            }
        }
        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);
        }
Example #22
0
        public bool Process(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects2 creationEffects, ICreationResult templateCreationResult, string outputBasePath)
        {
            bool allSucceeded = true;
            IEnumerable <string> targetFiles = null;

            if (actionConfig.Args.TryGetValue("files", out string specificFilesString))
            {
                JToken config = JToken.Parse(specificFilesString);

                if (config.Type == JTokenType.String)
                {
                    targetFiles = specificFilesString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).SelectMany(x => GetTargetForSource(creationEffects, x));
                }
                else if (config is JArray arr)
                {
                    List <string> allFiles = new List <string>();
                    foreach (JToken child in arr)
                    {
                        if (child.Type != JTokenType.String)
                        {
                            continue;
                        }

                        allFiles.AddRange(GetTargetForSource(creationEffects, child.ToString()));
                    }

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

            if (targetFiles is null)
            {
                environment.Host.LogMessage(string.Format(LocalizableStrings.CouldntDetermineFilesToRestore));
                return(false);
            }

            foreach (string targetRelativePath in targetFiles)
            {
                string pathToRestore = !string.IsNullOrEmpty(outputBasePath) ? Path.Combine(outputBasePath, targetRelativePath) : targetRelativePath;

                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));
                Dotnet        restoreCommand = Dotnet.Restore(pathToRestore).ForwardStdErr().ForwardStdOut();
                Dotnet.Result commandResult  = restoreCommand.Execute();

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

            return(allSucceeded);
        }
        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);
        }
Example #24
0
 internal CreationEffects2(IReadOnlyList <IFileChange2> fileChanges, ICreationResult creationResult)
 {
     FileChanges    = fileChanges ?? throw new System.ArgumentNullException(nameof(fileChanges));
     CreationResult = creationResult ?? throw new System.ArgumentNullException(nameof(creationResult));
 }
        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));
        }
Example #26
0
        public bool Process(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationResult templateCreationResult, string outputBasePath)
        {
            if (actionConfig.Args == null || !actionConfig.Args.TryGetValue("reference", out string referenceToAdd))
            {
                environment.Host.LogMessage(LocalizableStrings.AddRefPostActionMisconfigured);
                return(true);
            }

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

            if (string.IsNullOrEmpty(outputBasePath))
            {
                environment.Host.LogMessage(string.Format(LocalizableStrings.AddRefPostActionUnresolvedProjFile, referenceToAdd));
            }

            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);

            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
                {
                    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(string.Format(LocalizableStrings.AddRefPostActionUnresolvedProjFile, referenceToAdd));
                return(false);
            }
            else
            {
                // multiple projects at the same level. Error.
                environment.Host.LogMessage(string.Format(LocalizableStrings.AddRefPostActionUnresolvedProjFile, referenceToAdd));
                environment.Host.LogMessage(LocalizableStrings.AddRefPostActionProjFileListHeader);
                foreach (string projectFile in nearestProjectFilesFound)
                {
                    environment.Host.LogMessage(string.Format("\t{0}", projectFile));
                }

                return(false);
            }
        }
        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);
            }
        }
        protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath)
        {
            IReadOnlyList <string>?projectsToProcess = GetConfiguredFiles(action.Args, creationEffects, "targetFiles", outputBasePath);

            if (projectsToProcess is null)
            {
                //If the author didn't opt in to the new behavior by specifying "targetFiles", search for project file in current output directory or above.
                HashSet <string> extensionLimiters = new HashSet <string>(StringComparer.Ordinal);
                if (action.Args.TryGetValue("projectFileExtensions", out string?projectFileExtensions))
                {
                    if (projectFileExtensions.Contains("/") || projectFileExtensions.Contains("\\") || projectFileExtensions.Contains("*"))
                    {
                        // these must be literals
                        Reporter.Error.WriteLine(LocalizableStrings.PostAction_AddReference_Error_ActionMisconfigured);
                        return(false);
                    }

                    extensionLimiters.UnionWith(projectFileExtensions.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
                }
                projectsToProcess = FindProjFileAtOrAbovePath(environment.Host.FileSystem, outputBasePath, extensionLimiters);
                if (projectsToProcess.Count > 1)
                {
                    // multiple projects at the same level. Error.
                    Reporter.Error.WriteLine(LocalizableStrings.PostAction_AddReference_Error_UnresolvedProjFile);
                    Reporter.Error.WriteLine(LocalizableStrings.PostAction_AddReference_Error_ProjFileListHeader);
                    foreach (string projectFile in projectsToProcess)
                    {
                        Reporter.Error.WriteLine(string.Format("\t{0}", projectFile));
                    }
                    return(false);
                }
            }
            if (projectsToProcess is null || !projectsToProcess.Any())
            {
                // no projects found. Error.
                Reporter.Error.WriteLine(LocalizableStrings.PostAction_AddReference_Error_UnresolvedProjFile);
                return(false);
            }

            bool success = true;

            foreach (string projectFile in projectsToProcess)
            {
                success &= AddReference(environment, action, projectFile, outputBasePath);

                if (!success)
                {
                    return(false);
                }
            }
            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)))
                {
                    continue;
                }

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

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

            return(allSucceeded);
        }
        public Task Create(ITemplate templateData, IParameterSet parameters, IComponentManager componentManager, out ICreationResult creationResult)
        {
            RunnableProjectTemplate template = (RunnableProjectTemplate)templateData;

            ProcessMacros(componentManager, template.Config.OperationConfig, parameters);

            IVariableCollection variables = VariableCollection.SetupVariables(parameters, template.Config.OperationConfig.VariableSetup);

            template.Config.Evaluate(parameters, variables, template.ConfigFile);

            IOrchestrator basicOrchestrator          = new Core.Util.Orchestrator();
            RunnableProjectOrchestrator orchestrator = new RunnableProjectOrchestrator(basicOrchestrator);

            GlobalRunSpec runSpec = new GlobalRunSpec(template.ConfigFile.Parent, componentManager, parameters, variables, template.Config.OperationConfig, template.Config.SpecialOperationConfig, template.Config.LocalizationOperations, template.Config.PlaceholderFilename);

            foreach (FileSource source in template.Config.Sources)
            {
                runSpec.SetupFileSource(source);
                string target = Path.Combine(Directory.GetCurrentDirectory(), source.Target);
                orchestrator.Run(runSpec, template.ConfigFile.Parent.DirectoryInfo(source.Source), target);
            }

            // todo: add anything else we'd want to report to the broker
            creationResult = new CreationResult()
            {
                PostActions    = PostAction.ListFromModel(template.Config.PostActionModel, variables),
                PrimaryOutputs = CreationPath.ListFromModel(template.Config.PrimaryOutputs, variables)
            };

            return(Task.FromResult(true));
        }