Пример #1
0
        public static bool TryGetRuntimeValue(this IParameterSet parameters, IEngineEnvironmentSettings environmentSettings, string name, out object value, bool skipEnvironmentVariableSearch = false)
        {
            if (parameters.TryGetParameterDefinition(name, out ITemplateParameter param) &&
                parameters.ResolvedValues.TryGetValue(param, out object newValueObject) &&
                newValueObject != null)
            {
                value = newValueObject;
                return(true);
            }

            if ((environmentSettings.Host.TryGetHostParamDefault(name, out string newValue) && newValue != null) ||
                (!skipEnvironmentVariableSearch && environmentSettings.Environment.GetEnvironmentVariables().TryGetValue(name, out newValue) && newValue != null))
            {
                value = newValue;
                return(true);
            }

            value = null;
            return(false);
        }
        // For creating descriptors.
        public static bool TryCreateFromMountPoint(IEngineEnvironmentSettings environmentSettings, IMountPoint mountPoint, out IReadOnlyList <IInstallUnitDescriptor> descriptorList)
        {
            IInstallUnitDescriptorFactory defaultFactory = null;

            foreach (IInstallUnitDescriptorFactory factory in environmentSettings.SettingsLoader.Components.OfType <IInstallUnitDescriptorFactory>().ToList())
            {
                if (factory is DefaultInstallUnitDescriptorFactory)
                {
                    defaultFactory = factory;
                    continue;
                }

                if (factory.TryCreateFromMountPoint(mountPoint, out descriptorList))
                {
                    return(true);
                }
            }

            return(defaultFactory.TryCreateFromMountPoint(mountPoint, out descriptorList));
        }
Пример #3
0
        public async Task CannotInstall_NotExist()
        {
            MockInstallerFactory factory = new MockInstallerFactory();
            MockManagedTemplatePackageProvider provider = new MockManagedTemplatePackageProvider();
            IEngineEnvironmentSettings         engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true);

            FolderInstaller folderInstaller = new FolderInstaller(engineEnvironmentSettings, factory);

            InstallRequest request = new InstallRequest("not found");

            Assert.False(await folderInstaller.CanInstallAsync(request, CancellationToken.None).ConfigureAwait(false));

            InstallResult result = await folderInstaller.InstallAsync(request, provider, CancellationToken.None).ConfigureAwait(false);

            Assert.False(result.Success);
            Assert.Equal(request, result.InstallRequest);
            Assert.Equal(InstallerErrorCode.PackageNotFound, result.Error);
            result.ErrorMessage.Should().NotBeNullOrEmpty();
            result.TemplatePackage.Should().BeNull();
        }
Пример #4
0
        public void CanReadDescription(string fileContent, bool errorExpected, string?expectedDescription)
        {
            IEngineEnvironmentSettings environmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true);
            string tempFolder       = _environmentSettingsHelper.CreateTemporaryFolder();
            string localizationFile = string.Format(DefaultLocalizeConfigRelativePath, "de-DE");

            WriteFile(Path.Combine(tempFolder, localizationFile), fileContent, environmentSettings);

            using IMountPoint mountPoint = GetMountPointForPath(tempFolder, environmentSettings);
            if (!errorExpected)
            {
                var localizationModel = LocalizationModelDeserializer.Deserialize(mountPoint.FileInfo(localizationFile) !);
                Assert.NotNull(localizationModel);
                Assert.Equal(expectedDescription, localizationModel.Description);
            }
            else
            {
                Assert.ThrowsAny <Exception>(() => LocalizationModelDeserializer.Deserialize(mountPoint.FileInfo(localizationFile) !));
            }
        }
Пример #5
0
        public async Task CanProcessDifferentVersions(string configuredVersion, string hostVersion, bool expectedResult)
        {
            var config = new
            {
                identity    = "test",
                constraints = new
                {
                    host = new
                    {
                        type = "host",
                        args = new[]
                        {
                            new
                            {
                                hostName = "host1",
                                version  = configuredVersion
                            }
                        }
                    }
                }
            };

            var configModel = SimpleConfigModel.FromJObject(JObject.FromObject(config));
            IEngineEnvironmentSettings settings = A.Fake <IEngineEnvironmentSettings>();

            A.CallTo(() => settings.Host.HostIdentifier).Returns("host1");
            A.CallTo(() => settings.Host.Version).Returns(hostVersion);
            A.CallTo(() => settings.Components.OfType <ITemplateConstraintFactory>()).Returns(new[] { new HostConstraintFactory() });

            var constraintManager = new TemplateConstraintManager(settings);
            var evaluateResult    = await constraintManager.EvaluateConstraintAsync(configModel.Constraints.Single().Type, configModel.Constraints.Single().Args, default).ConfigureAwait(false);

            if (expectedResult)
            {
                Assert.Equal(TemplateConstraintResult.Status.Allowed, evaluateResult.EvaluationStatus);
            }
            else
            {
                Assert.Equal(TemplateConstraintResult.Status.Restricted, evaluateResult.EvaluationStatus);
            }
        }
Пример #6
0
        public void CanReadFilenameReplacementConfig()
        {
            string                     configContent  = @"
{
  ""identity"": ""test"",
  ""symbols"": {
	""testparam"": {
      ""type"": ""parameter"",
      ""datatype"": ""string"",
	  ""fileRename"": ""testparamfilereplacement""
    },
    ""testgenerated"": {
      ""type"": ""generated"",
      ""generator"": ""casing"",
      ""parameters"": {
        ""source"": ""name"",
        ""toLower"": true
      },
	  ""fileRename"": ""testgeneratedfilereplacement""
    },
    ""testgenerated2"": {
      ""type"": ""generated"",
      ""generator"": ""casing"",
      ""parameters"": {
        ""source"": ""name"",
        ""toLower"": true
      },
	  ""replace"": ""testgeneratedreplacement""
    },
  }
}
";
            SimpleConfigModel          configModel    = SimpleConfigModel.FromJObject(JObject.Parse(configContent));
            IEngineEnvironmentSettings environment    = _environmentSettingsHelper.CreateEnvironment();
            RunnableProjectConfig      runnableConfig =
                new RunnableProjectConfig(environment, A.Fake <IGenerator>(), configModel);

            Assert.Equal(2, runnableConfig.SymbolFilenameReplacements.Count);
            Assert.Equal("testparamfilereplacement", runnableConfig.SymbolFilenameReplacements.Single(x => x.VariableName.Contains("testparam")).OriginalValue.Value);
            Assert.Equal("testgeneratedfilereplacement", runnableConfig.SymbolFilenameReplacements.Single(x => x.VariableName == "testgenerated").OriginalValue.Value);
        }
        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);
        }
Пример #8
0
        public IMacroConfig CreateConfig(IEngineEnvironmentSettings environmentSettings, IMacroConfig rawConfig)
        {
            GeneratedSymbolDeferredMacroConfig deferredConfig = rawConfig as GeneratedSymbolDeferredMacroConfig;

            if (deferredConfig == null)
            {
                throw new InvalidCastException("Couldn't cast the rawConfig as a SwitchMacroConfig");
            }

            string evaluator = null;

            if (deferredConfig.Parameters.TryGetValue("evaluator", out JToken evaluatorToken))
            {
                evaluator = evaluatorToken.ToString();
            }

            string dataType = null;

            if (deferredConfig.Parameters.TryGetValue("datatype", out JToken dataTypeToken))
            {
                dataType = dataTypeToken.ToString();
            }

            List <KeyValuePair <string, string> > switchList = new List <KeyValuePair <string, string> >();

            if (deferredConfig.Parameters.TryGetValue("cases", out JToken switchListToken))
            {
                JArray switchJArray = (JArray)switchListToken;
                foreach (JToken switchInfo in switchJArray)
                {
                    JObject map       = (JObject)switchInfo;
                    string  condition = map.ToString("condition");
                    string  value     = map.ToString("value");
                    switchList.Add(new KeyValuePair <string, string>(condition, value));
                }
            }

            IMacroConfig realConfig = new SwitchMacroConfig(deferredConfig.VariableName, evaluator, dataType, switchList);

            return(realConfig);
        }
        public void CopyOnlyWithoutIncludeDoesntHappen()
        {
            IEngineEnvironmentSettings environment = TemplateConfigTestHelpers.GetTestEnvironment();
            string sourceBasePath = FileSystemHelpers.GetNewVirtualizedPath(environment);

            TestTemplateSetup setup     = SetupCopyOnlyTemplate(environment, sourceBasePath);
            string            targetDir = FileSystemHelpers.GetNewVirtualizedPath(environment);
            IReadOnlyDictionary <string, IReadOnlyList <IFileChange> > allChanges = setup.GetFileChanges(targetDir);

            // one source, should cause one set of changes
            Assert.Equal(1, allChanges.Count);

            if (!allChanges.TryGetValue("./", out IReadOnlyList <IFileChange> changes))
            {
                Assert.True(false, "no changes for source './'");
            }

            Assert.Equal(1, changes.Count);
            Assert.Equal(ChangeKind.Create, changes[0].ChangeKind);
            Assert.True(string.Equals(changes[0].TargetRelativePath, "something.txt"), "didn't copy the correct file");
        }
Пример #10
0
        public Task <ICreationResult> CreateAsync(
            IEngineEnvironmentSettings environmentSettings,
            ITemplate templateData,
            IParameterSet parameters,
            string targetDirectory,
            CancellationToken cancellationToken)
        {
            RunnableProjectConfig templateConfig = (RunnableProjectConfig)templateData;

            if (templateData.TemplateSourceRoot is null)
            {
                throw new InvalidOperationException($"{nameof(templateData.TemplateSourceRoot)} cannot be null to continue.");
            }
            return(CreateAsync(
                       environmentSettings,
                       templateConfig,
                       templateData.TemplateSourceRoot,
                       parameters,
                       targetDirectory,
                       cancellationToken));
        }
Пример #11
0
        public NuGetInstaller(IInstallerFactory factory, IEngineEnvironmentSettings settings, string installPath)
        {
            Factory = factory ?? throw new ArgumentNullException(nameof(factory));
            _environmentSettings = settings ?? throw new ArgumentNullException(nameof(settings));
            _logger = settings.Host.LoggerFactory.CreateLogger <NuGetInstaller>();

            if (string.IsNullOrWhiteSpace(installPath))
            {
                throw new ArgumentException($"{nameof(installPath)} should not be null or empty", nameof(installPath));
            }
            if (!_environmentSettings.Host.FileSystem.DirectoryExists(installPath))
            {
                _environmentSettings.Host.FileSystem.CreateDirectory(installPath);
            }
            _installPath = installPath;

            NuGetApiPackageManager packageManager = new NuGetApiPackageManager(settings);

            _packageDownloader = packageManager;
            _updateChecker     = packageManager;
        }
Пример #12
0
        public static bool TryReadDiscoveryMetadata(IEngineEnvironmentSettings environment, ISearchCacheConfig config, out TemplateDiscoveryMetadata discoveryMetadata)
        {
            Paths  paths        = new Paths(environment);
            string pathToConfig = Path.Combine(paths.User.BaseDir, config.TemplateDiscoveryFileName);
            string cacheText    = paths.ReadAllText(pathToConfig);

            JObject cacheObject = JObject.Parse(cacheText);

            // add the reader calls, build the model objects
            if (TryReadVersion(cacheObject, out string version) &&
                TryReadTemplateList(cacheObject, version, out IReadOnlyList <ITemplateInfo> templateList) &&
                TryReadPackToTemplateMap(cacheObject, out IReadOnlyDictionary <string, PackToTemplateEntry> packToTemplateMap) &&
                TryReadAdditionalData(cacheObject, config.AdditionalDataReaders, out IReadOnlyDictionary <string, object> additionalDta))
            {
                discoveryMetadata = new TemplateDiscoveryMetadata(version, templateList, packToTemplateMap, additionalDta);
                return(true);
            }

            discoveryMetadata = null;
            return(false);
        }
Пример #13
0
        public void EvaluateConfig(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, IMacroConfig rawConfig, IParameterSet parameters, ParameterSetter setter)
        {
            string           value  = null;
            RegexMacroConfig config = rawConfig as RegexMacroConfig;

            if (config == null)
            {
                throw new InvalidCastException("Couldn't cast the rawConfig as RegexMacroConfig");
            }

            if (!vars.TryGetValue(config.SourceVariable, out object working))
            {
                if (parameters.TryGetRuntimeValue(environmentSettings, config.SourceVariable, out object resolvedValue, true))
                {
                    value = resolvedValue.ToString();
                }
                else
                {
                    value = string.Empty;
                }
            }
Пример #14
0
        public void EvaluateConfig(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, IMacroConfig rawConfig, IParameterSet parameters, ParameterSetter setter)
        {
            RandomMacroConfig config = rawConfig as RandomMacroConfig;

            if (config == null)
            {
                throw new InvalidCastException("Couldn't cast the rawConfig as RandomMacroConfig");
            }

            Random rnd   = new Random();
            int    value = rnd.Next(config.Low, config.High);

            Parameter p = new Parameter
            {
                IsVariable = true,
                Name       = config.VariableName
            };

            vars[config.VariableName] = value.ToString();
            setter(p, value.ToString());
        }
Пример #15
0
        public async Task GetLatestVersion_Success()
        {
            MockInstallerFactory factory = new MockInstallerFactory();
            MockManagedTemplatePackageProvider provider = new MockManagedTemplatePackageProvider();
            IEngineEnvironmentSettings         engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true);

            FolderInstaller folderInstaller = new FolderInstaller(engineEnvironmentSettings, factory);

            FolderManagedTemplatePackage      source  = new FolderManagedTemplatePackage(engineEnvironmentSettings, folderInstaller, provider, Path.GetRandomFileName());
            IReadOnlyList <CheckUpdateResult> results = await folderInstaller.GetLatestVersionAsync(new[] { source }, provider, CancellationToken.None).ConfigureAwait(false);

            Assert.Single(results);
            CheckUpdateResult result = results.Single();

            Assert.True(result.Success);
            Assert.Equal(source, result.TemplatePackage);
            Assert.Equal(InstallerErrorCode.Success, result.Error);
            result.ErrorMessage.Should().BeNullOrEmpty();
            result.LatestVersion.Should().BeNullOrEmpty();
            Assert.True(result.IsLatestVersion);
        }
Пример #16
0
        public async Task Update_Success()
        {
            MockInstallerFactory factory = new MockInstallerFactory();
            MockManagedTemplatePackageProvider provider = new MockManagedTemplatePackageProvider();
            IEngineEnvironmentSettings         engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true);

            FolderInstaller folderInstaller = new FolderInstaller(engineEnvironmentSettings, factory);

            FolderManagedTemplatePackage source = new FolderManagedTemplatePackage(engineEnvironmentSettings, folderInstaller, provider, Path.GetRandomFileName(), DateTime.UtcNow);
            //add a delay so update updates last changed time
            await Task.Delay(100).ConfigureAwait(false);

            UpdateRequest updateRequest = new UpdateRequest(source, "1.0.0");
            UpdateResult  result        = await folderInstaller.UpdateAsync(updateRequest, provider, CancellationToken.None).ConfigureAwait(false);

            Assert.True(result.Success);
            Assert.Equal(updateRequest, result.UpdateRequest);
            Assert.Equal(InstallerErrorCode.Success, result.Error);
            Assert.Equal(source.MountPointUri, result.TemplatePackage.MountPointUri);
            Assert.NotEqual(source.LastChangeTime, result.TemplatePackage.LastChangeTime);
        }
Пример #17
0
        public void CanReadFilenameReplacementConfig()
        {
            string configContent = @"
{
  ""symbols"": {
	""testparam"": {
      ""type"": ""parameter"",
      ""datatype"": ""string"",
	  ""fileRename"": ""testparamfilereplacement""
    },
    ""testgenerated"": {
      ""type"": ""generated"",
      ""generator"": ""casing"",
      ""parameters"": {
        ""source"": ""name"",
        ""toLower"": true
      },
	  ""fileRename"": ""testgeneratedfilereplacement""
    },
    ""testgenerated2"": {
      ""type"": ""generated"",
      ""generator"": ""casing"",
      ""parameters"": {
        ""source"": ""name"",
        ""toLower"": true
      },
	  ""replace"": ""testgeneratedreplacement""
    },

  }
}
";
            IEngineEnvironmentSettings environment = TemplateConfigTestHelpers.GetTestEnvironment();
            JObject           configJson           = JObject.Parse(configContent);
            SimpleConfigModel config = SimpleConfigModel.FromJObject(environment, configJson);

            Assert.Equal(2, config.SymbolFilenameReplacements.Count);
            Assert.Equal("testparamfilereplacement", config.SymbolFilenameReplacements.Single(x => x.VariableName.Contains("testparam")).OriginalValue.Value);
            Assert.Equal("testgeneratedfilereplacement", config.SymbolFilenameReplacements.Single(x => x.VariableName == "testgenerated").OriginalValue.Value);
        }
        public static bool TryParse(IEngineEnvironmentSettings environmentSettings, JObject descriptorObj, out IInstallUnitDescriptor parsedDescriptor)
        {
            if (descriptorObj == null)
            {
                parsedDescriptor = null;
                return(false);
            }

            if (!descriptorObj.TryGetValue(nameof(IInstallUnitDescriptor.FactoryId), StringComparison.OrdinalIgnoreCase, out JToken factoryIdToken) ||
                (factoryIdToken == null) ||
                (factoryIdToken.Type != JTokenType.String) ||
                !Guid.TryParse(factoryIdToken.ToString(), out Guid factoryId) ||
                !environmentSettings.SettingsLoader.Components.TryGetComponent(factoryId, out IInstallUnitDescriptorFactory factory))
            {
                parsedDescriptor = null;
                return(false);
            }

            Dictionary <string, string> details = new Dictionary <string, string>();

            foreach (JProperty property in descriptorObj.PropertiesOf(nameof(IInstallUnitDescriptor.Details)))
            {
                if (property.Value.Type != JTokenType.String)
                {
                    parsedDescriptor = null;
                    return(false);
                }

                details[property.Name] = property.Value.ToString();
            }

            if (factory.TryCreateFromDetails(details, out IInstallUnitDescriptor descriptor))
            {
                parsedDescriptor = descriptor;
                return(true);
            }

            parsedDescriptor = null;
            return(false);
        }
Пример #19
0
        public void EvaluateConfig(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, IMacroConfig rawConfig, IParameterSet parameters, ParameterSetter setter)
        {
            NowMacroConfig config = rawConfig as NowMacroConfig;

            if (config == null)
            {
                throw new InvalidCastException("Couldn't cast the rawConfig as NowMacroConfig");
            }

            DateTime time  = config.Utc ? DateTime.UtcNow : DateTime.Now;
            string   value = time.ToString(config.Format);

            Parameter p;

            if (parameters.TryGetParameterDefinition(config.VariableName, out ITemplateParameter existingParam))
            {
                // If there is an existing parameter with this name, it must be reused so it can be referenced by name
                // for other processing, for example: if the parameter had value forms defined for creating variants.
                // When the param already exists, use its definition, but set IsVariable = true for consistency.
                p            = (Parameter)existingParam;
                p.IsVariable = true;

                if (string.IsNullOrEmpty(p.DataType))
                {
                    p.DataType = config.DataType;
                }
            }
            else
            {
                p = new Parameter
                {
                    IsVariable = true,
                    Name       = config.VariableName,
                    DataType   = config.DataType
                };
            }

            vars[config.VariableName] = value;
            setter(p, value);
        }
        internal static Task <CreationResultStatus> CoordinateAmbiguousTemplateResolutionDisplayAsync(
            TemplateResolutionResult resolutionResult,
            IEngineEnvironmentSettings environmentSettings,
            INewCommandInput commandInput,
            string?defaultLanguage)
        {
            switch (resolutionResult.ResolutionStatus)
            {
            case TemplateResolutionResult.Status.NoMatch:
                Reporter.Error.WriteLine(
                    string.Format(LocalizableStrings.NoTemplatesMatchingInputParameters, GetInputParametersString(commandInput)).Bold().Red());
                Reporter.Error.WriteLine(string.Format(LocalizableStrings.ListTemplatesCommand, commandInput.CommandName).Bold().Red());
                Reporter.Error.WriteLine(string.Format(LocalizableStrings.SearchTemplatesCommand, commandInput.CommandName, commandInput.TemplateName).Bold().Red());
                return(Task.FromResult(CreationResultStatus.NotFound));

            case TemplateResolutionResult.Status.AmbiguousLanguageChoice:
                Reporter.Error.WriteLine(LocalizableStrings.AmbiguousTemplateGroupListHeader.Bold().Red());
                DisplayTemplateList(resolutionResult.TemplateGroups, environmentSettings, commandInput, defaultLanguage, useErrorOutput: true);
                Reporter.Error.WriteLine(LocalizableStrings.AmbiguousLanguageHint.Bold().Red());
                return(Task.FromResult(CreationResultStatus.NotFound));

            case TemplateResolutionResult.Status.AmbiguousTemplateGroupChoice:
                Reporter.Error.WriteLine(LocalizableStrings.AmbiguousTemplateGroupListHeader.Bold().Red());
                DisplayTemplateList(resolutionResult.TemplateGroups, environmentSettings, commandInput, defaultLanguage, useErrorOutput: true);
                Reporter.Error.WriteLine(LocalizableStrings.AmbiguousTemplateGroupListHint.Bold().Red());
                return(Task.FromResult(CreationResultStatus.NotFound));

            case TemplateResolutionResult.Status.AmbiguousParameterValueChoice:
                environmentSettings.Host.LogDiagnosticMessage(LocalizableStrings.Authoring_AmbiguousChoiceParameterValue, "Authoring");
                return(Task.FromResult(DisplayInvalidParameterError(resolutionResult.UnambiguousTemplateGroup, commandInput)));

            case TemplateResolutionResult.Status.AmbiguousTemplateChoice:
                environmentSettings.Host.LogDiagnosticMessage(LocalizableStrings.Authoring_AmbiguousBestPrecedence, "Authoring");
                return(DisplayAmbiguousPrecedenceErrorAsync(resolutionResult.UnambiguousTemplateGroup, environmentSettings, commandInput));

            case TemplateResolutionResult.Status.InvalidParameter:
                return(Task.FromResult(DisplayInvalidParameterError(resolutionResult.UnambiguousTemplateGroup, commandInput)));
            }
            return(Task.FromResult(CreationResultStatus.CreateFailed));
        }
Пример #21
0
        public void CanReadNonChoiceSymbol(
            string fileContent,
            bool errorExpected,
            string expectedSymbolNamesStr,
            string expectedSymbolDisplayNamesStr,
            string expectedDescriptionsStr)
        {
            IEngineEnvironmentSettings environmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true);
            string tempFolder       = _environmentSettingsHelper.CreateTemporaryFolder();
            string localizationFile = string.Format(DefaultLocalizeConfigRelativePath, "de-DE");

            WriteFile(Path.Combine(tempFolder, localizationFile), fileContent, environmentSettings);

            using IMountPoint mountPoint = GetMountPointForPath(tempFolder, environmentSettings);
            if (!errorExpected)
            {
                var localizationModel = LocalizationModelDeserializer.Deserialize(mountPoint.FileInfo(localizationFile) !);
                Assert.NotNull(localizationModel);

                if (string.IsNullOrEmpty(expectedSymbolNamesStr))
                {
                    Assert.Empty(localizationModel.ParameterSymbols);
                    return;
                }
                var expectedSymbolNames  = expectedSymbolNamesStr.Split('|');
                var expectedDisplayNames = expectedSymbolDisplayNamesStr.Split('|');
                var expectedDescriptions = expectedDescriptionsStr.Split('|');

                for (int i = 0; i < expectedSymbolNames.Length; i++)
                {
                    Assert.True(localizationModel.ParameterSymbols.ContainsKey(expectedSymbolNames[i]));
                    Assert.Equal(expectedDisplayNames[i] == "(null)" ? null : expectedDisplayNames[i], localizationModel.ParameterSymbols[expectedSymbolNames[i]].DisplayName);
                    Assert.Equal(expectedDescriptions[i] == "(null)" ? null : expectedDescriptions[i], localizationModel.ParameterSymbols[expectedSymbolNames[i]].Description);
                }
            }
            else
            {
                Assert.ThrowsAny <Exception>(() => LocalizationModelDeserializer.Deserialize(mountPoint.FileInfo(localizationFile) !));
            }
        }
        /// <summary>
        /// Performs the dry-run of the template instantiation to evaluate the primary outputs, post actions to be applied and file changes to be made when executing the template with specified parameters.
        /// </summary>
        /// <param name="environmentSettings">environment settings</param>
        /// <param name="templateData">the template to be executed</param>
        /// <param name="parameters">the parameters to be used on template execution</param>
        /// <param name="componentManager">the instance of component manager</param>
        /// <param name="targetDirectory">the output path for the template</param>
        /// <returns>the primary outputs, post actions and file changes that will be made when executing the template with specified parameters.</returns>
        public ICreationEffects GetCreationEffects(IEngineEnvironmentSettings environmentSettings, ITemplate templateData, IParameterSet parameters, IComponentManager componentManager, string targetDirectory)
        {
            RunnableProjectTemplate template = (RunnableProjectTemplate)templateData;

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

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

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

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

            GlobalRunSpec       runSpec = new GlobalRunSpec(template.TemplateSourceRoot, componentManager, parameters, variables, template.Config.OperationConfig, template.Config.SpecialOperationConfig, template.Config.LocalizationOperations, template.Config.IgnoreFileNames);
            List <IFileChange2> changes = new List <IFileChange2>();

            foreach (FileSourceMatchInfo source in template.Config.Sources)
            {
                runSpec.SetupFileSource(source);
                string target = Path.Combine(targetDirectory, source.Target);
                IReadOnlyList <IFileChange2> fileChanges = orchestrator.GetFileChanges(runSpec, template.TemplateSourceRoot.DirectoryInfo(source.Source), target);

                //source and target paths in the file changes are returned relative to source passed
                //GetCreationEffects method should return the source paths relative to template source root (location of .template.config folder) and target paths relative to output path and not relative to certain source
                //add source and target used to file changes to be returned as the result
                changes.AddRange(
                    fileChanges.Select(
                        fileChange => new FileChange(
                            Path.Combine(source.Source, fileChange.SourceRelativePath),
                            Path.Combine(source.Target, fileChange.TargetRelativePath),
                            fileChange.ChangeKind,
                            fileChange.Contents)));
            }

            return(new CreationEffects2
            {
                FileChanges = changes,
                CreationResult = GetCreationResult(environmentSettings, template, variables)
            });
        }
        // 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);
            }
        }
Пример #24
0
        public static CreationResultStatus DisplayAliasValues(IEngineEnvironmentSettings environment, INewCommandInput commandInput, AliasRegistry aliasRegistry, string commandName)
        {
            IReadOnlyDictionary <string, IReadOnlyList <string> > aliasesToShow;

            if (!string.IsNullOrEmpty(commandInput.ShowAliasesAliasName))
            {
                if (aliasRegistry.AllAliases.TryGetValue(commandInput.ShowAliasesAliasName, out IReadOnlyList <string> aliasValue))
                {
                    aliasesToShow = new Dictionary <string, IReadOnlyList <string> >()
                    {
                        { commandInput.ShowAliasesAliasName, aliasValue }
                    };
                }
                else
                {
                    Reporter.Output.WriteLine(string.Format(LocalizableStrings.AliasShowErrorUnknownAlias, commandInput.ShowAliasesAliasName, commandName));
                    return(CreationResultStatus.InvalidParamValues);
                }
            }
            else
            {
                aliasesToShow = aliasRegistry.AllAliases;
                Reporter.Output.WriteLine(LocalizableStrings.AliasShowAllAliasesHeader);
            }

            HelpFormatter <KeyValuePair <string, IReadOnlyList <string> > > formatter =
                new HelpFormatter <KeyValuePair <string, IReadOnlyList <string> > >(
                    environment,
                    commandInput,
                    aliasesToShow,
                    columnPadding: 2,
                    headerSeparator: '-',
                    blankLineBetweenRows: false)
                .DefineColumn(t => t.Key, LocalizableStrings.AliasName, showAlways: true)
                .DefineColumn(t => string.Join(" ", t.Value), LocalizableStrings.AliasValue, showAlways: true);

            Reporter.Output.WriteLine(formatter.Layout());
            return(CreationResultStatus.Success);
        }
Пример #25
0
        // Creates and returns the processor used to create the file rename mapping.
        private static IProcessor SetupRenameProcessor(IEngineEnvironmentSettings environmentSettings, IReadOnlyDictionary <string, string> substringReplacementMap, IReadOnlyDictionary <string, string> fileRenames)
        {
            List <IOperationProvider> operations = new List <IOperationProvider>();

            foreach (KeyValuePair <string, string> replacement in fileRenames)
            {
                IOperationProvider replacementOperation = new Replacement(replacement.Key.TokenConfig(), replacement.Value, null, true);
                operations.Add(replacementOperation);
            }

            foreach (KeyValuePair <string, string> replacement in substringReplacementMap)
            {
                IOperationProvider replacementOperation = new Replacement(replacement.Key.TokenConfig(), replacement.Value, null, true);
                operations.Add(replacementOperation);
            }

            IVariableCollection variables = new VariableCollection();
            EngineConfig        config    = new EngineConfig(environmentSettings, variables);
            IProcessor          processor = Processor.Create(config, operations);

            return(processor);
        }
        /// <summary>
        /// Returns absolute path to files or folders resolved from <paramref name="maskedPath"/>.
        /// </summary>
        /// <remarks>
        /// Example of <paramref name="maskedPath"/> would be "C:\Users\username\packages\*.nupkg".<br/>
        /// Wildcards are supported only in file name.
        /// Supported wildcards and rules are identical as for <see cref="searchPattern"/> for <see cref="Directory.EnumerateDirectories(string, string)"/>.
        /// </remarks>
        /// <param name="maskedPath">This parameter can contain a wildcard (*) character in the filename.</param>
        /// <param name="environmentSettings"></param>
        /// <returns>List of absolute paths to files or folders that match <paramref name="maskedPath"/>.</returns>
        public static IEnumerable <string> ExpandMaskedPath(string maskedPath, IEngineEnvironmentSettings environmentSettings)
        {
            if (maskedPath.IndexOfAny(Path.GetInvalidPathChars()) != -1)
            {
                yield return(maskedPath);

                yield break;
            }
            var matches = DetermineDirectoriesToScan(maskedPath, environmentSettings).ToList();

            //This can happen when user specifies "PackageId"
            if (matches.Count == 0)
            {
                yield return(maskedPath);

                yield break;
            }
            foreach (var path in matches)
            {
                yield return(Path.GetFullPath(path));
            }
        }
Пример #27
0
        public void EvaluateConfig(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, IMacroConfig rawConfig, IParameterSet parameters, ParameterSetter setter)
        {
            EvaluateMacroConfig config = rawConfig as EvaluateMacroConfig;

            if (config == null)
            {
                throw new InvalidCastException("Couldn't cast the rawConfig as EvaluateMacroConfig");
            }

            ConditionEvaluator evaluator = EvaluatorSelector.Select(config.Evaluator, Cpp2StyleEvaluatorDefinition.Evaluate);

            byte[]          data   = Encoding.UTF8.GetBytes(config.Value);
            int             len    = data.Length;
            int             pos    = 0;
            IProcessorState state  = new GlobalRunSpec.ProcessorState(environmentSettings, vars, data, Encoding.UTF8);
            bool            result = evaluator(state, ref len, ref pos, out bool faulted);

            Parameter p;

            if (parameters.TryGetParameterDefinition(config.VariableName, out ITemplateParameter existingParam))
            {
                // If there is an existing parameter with this name, it must be reused so it can be referenced by name
                // for other processing, for example: if the parameter had value forms defined for creating variants.
                // When the param already exists, use its definition, but set IsVariable = true for consistency.
                p            = (Parameter)existingParam;
                p.IsVariable = true;
            }
            else
            {
                p = new Parameter
                {
                    IsVariable = true,
                    Name       = config.VariableName
                };
            }

            vars[config.VariableName] = result.ToString();
            setter(p, result.ToString());
        }
Пример #28
0
        public void CanValidatePostActionWithoutLocalization()
        {
            IEngineEnvironmentSettings environmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true);
            string tempFolder       = _environmentSettingsHelper.CreateTemporaryFolder();
            string localizationFile = string.Format(DefaultLocalizeConfigRelativePath, "de-DE");

            WriteFile(Path.Combine(tempFolder, localizationFile), "{ \"postActions/pa0/description\": \"localizedDescription\" }", environmentSettings);

            using IMountPoint mountPoint = GetMountPointForPath(tempFolder, environmentSettings);

            SimpleConfigModel baseConfig = new SimpleConfigModel()
            {
                Identity         = "Test",
                PostActionModels = new List <PostActionModel>
                {
                    new PostActionModel()
                    {
                        Id          = "",
                        Description = "text",
                        ActionId    = Guid.NewGuid()
                    },
                    new PostActionModel()
                    {
                        Id          = "pa0",
                        Description = "text",
                        ActionId    = Guid.NewGuid()
                    },
                }
            };

            var runnableProjectConfig = new RunnableProjectConfig(environmentSettings, A.Fake <IGenerator>(), baseConfig);
            var localizationModel     = LocalizationModelDeserializer.Deserialize(mountPoint.FileInfo(localizationFile) !);

            Assert.True(runnableProjectConfig.VerifyLocalizationModel(localizationModel));

            runnableProjectConfig.ConfigurationModel.Localize(localizationModel);
            runnableProjectConfig.PostActionModels.Single(model => model.Id == "pa0" && model.Description == "localizedDescription");
            runnableProjectConfig.PostActionModels.Single(model => model.Id != "pa0" && model.Description == "text");
        }
Пример #29
0
        internal static IReadOnlyDictionary <string, string> AugmentFileRenames(
            IEngineEnvironmentSettings environmentSettings,
            string?sourceName,
            IFileSystemInfo configFile,
            string sourceDirectory,
            ref string targetDirectory,
            object?resolvedNameParamValue,
            IParameterSet parameterSet,
            Dictionary <string, string> fileRenames,
            IReadOnlyList <IReplacementTokens>?symbolBasedFileRenames = null)
        {
            Dictionary <string, string> allRenames = new Dictionary <string, string>(StringComparer.Ordinal);

            IProcessor sourceRenameProcessor = SetupRenameProcessor(environmentSettings, fileRenames);
            IProcessor symbolRenameProcessor = SetupSymbolBasedRenameProcessor(environmentSettings, sourceName, ref targetDirectory, resolvedNameParamValue, parameterSet, symbolBasedFileRenames);

            IDirectory?sourceBaseDirectoryInfo = configFile.Parent?.Parent?.DirectoryInfo(sourceDirectory.TrimEnd('/'));

            if (sourceBaseDirectoryInfo is null)
            {
                return(allRenames);
            }

            foreach (IFileSystemInfo fileSystemEntry in sourceBaseDirectoryInfo.EnumerateFileSystemInfos("*", SearchOption.AllDirectories))
            {
                string sourceTemplateRelativePath = fileSystemEntry.PathRelativeTo(sourceBaseDirectoryInfo);

                // first apply the sources renames, then apply the symbol renames to that result.
                string renameFromSourcesValue = ApplyRenameProcessorToFilename(sourceRenameProcessor, sourceTemplateRelativePath);
                string renameFinalTargetValue = ApplyRenameProcessorToFilename(symbolRenameProcessor, renameFromSourcesValue);

                if (!string.Equals(sourceTemplateRelativePath, renameFinalTargetValue, StringComparison.Ordinal))
                {
                    allRenames[sourceTemplateRelativePath] = renameFinalTargetValue;
                }
            }

            return(allRenames);
        }
Пример #30
0
        public static VariableCollection VariableCollectionFromParameters(IEngineEnvironmentSettings environmentSettings, IParameterSet parameters, string format)
        {
            VariableCollection vc = new VariableCollection();

            foreach (ITemplateParameter param in parameters.ParameterDefinitions)
            {
                string key = string.Format(format ?? "{0}", param.Name);

                if (!parameters.ResolvedValues.TryGetValue(param, out object value))
                {
                    if (param.Priority != TemplateParameterPriority.Optional && param.Priority != TemplateParameterPriority.Suggested)
                    {
                        while (environmentSettings.Host.OnParameterError(param, null, "ParameterValueNotSpecified", out string val))
                        {
                        }

                        parameters.ResolvedValues[param] = value;
                    }
                }
                else if (value == null)
                {
                    if (param.Priority != TemplateParameterPriority.Optional && param.Priority != TemplateParameterPriority.Suggested)
                    {
                        while (environmentSettings.Host.OnParameterError(param, null, "ParameterValueNull", out string val))
                        {
                        }

                        parameters.ResolvedValues[param] = value;
                    }
                }
                else
                {
                    vc[key] = value;
                }
            }

            return(vc);
        }