public void CheckTemplateSourcesRelativeToTemplateRootMultipleDirsUnderMountPoint(bool shouldAllPathsBeValid, string source)
        {
            const string pathFromMountPointRootToTemplateRoot = "MountRoot/Stuff/TemplateRoot/";
            string       pathToTemplateConfig = pathFromMountPointRootToTemplateRoot + ".template.config/template.json";

            string sourcePath = FileSystemHelpers.GetNewVirtualizedPath(EngineEnvironmentSettings);
            IDictionary <string, string> templateSourceFiles = new Dictionary <string, string>();

            string templateConfig = String.Format(TemplateConfigWithSourcePlaceholder, source);

            templateSourceFiles.Add(pathToTemplateConfig, templateConfig);

            string sampleContentDir = pathFromMountPointRootToTemplateRoot + "things/stuff/_._";

            templateSourceFiles.Add(sampleContentDir, "");    // directories under the template root - valid source locations.
            templateSourceFiles.Add("ExistingDir/_._", "");
            templateSourceFiles.Add("MountRoot/Subdir/_._", "");
            TestTemplateSetup setup = new TestTemplateSetup(EngineEnvironmentSettings, sourcePath, templateSourceFiles);

            setup.WriteSource();

            RunnableProjectGenerator generator = new RunnableProjectGenerator();

            IFile                   templateFile            = setup.FileInfoForSourceFile(pathToTemplateConfig);
            JObject                 srcObject               = generator.ReadJObjectFromIFile(templateFile);
            SimpleConfigModel       templateModel           = SimpleConfigModel.FromJObject(templateFile.MountPoint.EnvironmentSettings, srcObject);
            RunnableProjectTemplate runnableProjectTemplate = new RunnableProjectTemplate(srcObject, generator, templateFile, templateModel, null, null);

            bool allPathsAreValid = generator.AreAllTemplatePathsValid(templateModel, runnableProjectTemplate);

            Assert.Equal(shouldAllPathsBeValid, allPathsAreValid);
        }
        public void CheckTemplateSourcesRelativeToTemplateRootMultipleDirsUnderMountPoint(bool shouldAllPathsBeValid, string source)
        {
            string                   templateConfig = string.Format(TemplateConfigWithSourcePlaceholder, source);
            SimpleConfigModel        baseConfig     = SimpleConfigModel.FromJObject(JObject.Parse(templateConfig));
            RunnableProjectGenerator generator      = new RunnableProjectGenerator();

            const string pathFromMountPointRootToTemplateRoot = "MountRoot/Stuff/TemplateRoot/";
            string       pathToTemplateConfig = pathFromMountPointRootToTemplateRoot + ".template.config/template.json";

            string sourcePath = FileSystemHelpers.GetNewVirtualizedPath(_engineEnvironmentSettings);
            IDictionary <string, string> templateSourceFiles = new Dictionary <string, string>();

            templateSourceFiles.Add(pathToTemplateConfig, templateConfig);

            string sampleContentDir = pathFromMountPointRootToTemplateRoot + "things/stuff/_._";

            templateSourceFiles.Add(sampleContentDir, "");    // directories under the template root - valid source locations.
            templateSourceFiles.Add("ExistingDir/_._", "");
            templateSourceFiles.Add("MountRoot/Subdir/_._", "");
            TestTemplateSetup setup = new TestTemplateSetup(_engineEnvironmentSettings, sourcePath, templateSourceFiles);

            setup.WriteSource();

            IFile templateFile = setup.FileInfoForSourceFile(pathToTemplateConfig);
            RunnableProjectConfig templateModel = new RunnableProjectConfig(_engineEnvironmentSettings, generator, baseConfig, templateFile);

            if (shouldAllPathsBeValid)
            {
                Assert.Empty(templateModel.ValidateTemplateSourcePaths());
            }
            else
            {
                Assert.NotEmpty(templateModel.ValidateTemplateSourcePaths());
            }
        }
Exemple #3
0
        public async void CreateAsyncTest_ConditionWithUnquotedChoiceLiteral(string templateConfig, string expectedResult)
        {
            //
            // Template content preparation
            //

            string sourceSnippet = @"
//#if( ChoiceParam == FirstChoice )
FIRST
//#elseif (ChoiceParam == SecondChoice )
SECOND
//#elseif (ChoiceParam == ThirdChoice )
THIRD
//#else
UNKNOWN
//#endif
";

            IDictionary <string, string?> templateSourceFiles = new Dictionary <string, string?>();

            // template.json
            templateSourceFiles.Add(TestFileSystemHelper.DefaultConfigRelativePath, templateConfig);

            //content
            templateSourceFiles.Add("sourcFile", sourceSnippet);

            //
            // Dependencies preparation and mounting
            //

            IEngineEnvironmentSettings environment = _environmentSettingsHelper.CreateEnvironment();
            string sourceBasePath = FileSystemHelpers.GetNewVirtualizedPath(environment);
            string targetDir      = FileSystemHelpers.GetNewVirtualizedPath(environment);

            TestFileSystemHelper.WriteTemplateSource(environment, sourceBasePath, templateSourceFiles);
            IMountPoint?sourceMountPoint            = TestFileSystemHelper.CreateMountPoint(environment, sourceBasePath);
            RunnableProjectGenerator rpg            = new RunnableProjectGenerator();
            SimpleConfigModel        configModel    = SimpleConfigModel.FromJObject(JObject.Parse(templateConfig));
            IRunnableProjectConfig   runnableConfig = new RunnableProjectConfig(environment, rpg, configModel, sourceMountPoint.FileInfo(TestFileSystemHelper.DefaultConfigRelativePath));
            IParameterSet            parameters     = new ParameterSet(runnableConfig);
            ITemplateParameter       choiceParameter;

            Assert.True(parameters.TryGetParameterDefinition("ChoiceParam", out choiceParameter), "ChoiceParam expected to be extracted from template config");
            parameters.ResolvedValues[choiceParameter] = "SecondChoice";
            IDirectory sourceDir = sourceMountPoint !.DirectoryInfo("/") !;

            //
            // Running the actual scenario: template files processing and generating output (including macros processing)
            //

            await rpg.CreateAsync(environment, runnableConfig, sourceDir, parameters, targetDir, CancellationToken.None);

            //
            // Veryfying the outputs
            //

            string resultContent = environment.Host.FileSystem.ReadAllText(Path.Combine(targetDir, "sourcFile")).Trim();

            Assert.Equal(expectedResult, resultContent);
        }
        public TemplateEngineHost() : base(VSHost, FindTemplateHostVersion(), VSHostLocale)
        {
            MountPointFactory = new FileSystemMountPointFactory();
            Settings          = new EngineEnvironmentSettings(this, settings => new TemplateSettingsLoader(settings));
            Orchestrator      = new RunnableProjectOrchestrator(new Orchestrator());
            TemplateCreator   = new TemplateCreator(Settings);
            Generator         = new RunnableProjectGenerator();

            MountPointManager = new MountPointManager(Settings, ComponentManager);


            HostDefaults = new Dictionary <string, string>
            {
                ["HostIdentifier"] = HostIdentifier,
                ["Locale"]         = Locale,
                ["Version"]        = Version
            };

            UserTemplates = SettingsLoader.UserTemplateCache.TemplateInfo;

            MountPoints = new List <IMountPoint>();

            foreach (var mountPointInfo in SettingsLoader.MountPoints)
            {
                if (MountPointFactory.TryMount(MountPointManager, mountPointInfo, out var mountPoint))
                {
                    MountPoints.Add(mountPoint);
                }
            }
        }
        public void CheckTemplateRootRelativeToInstallPath(string pathToTemplateJson, bool shouldAllPathsBeValid)
        {
            SimpleConfigModel        baseConfig = SimpleConfigModel.FromJObject(JObject.Parse(BasicTemplateConfig));
            RunnableProjectGenerator generator  = new RunnableProjectGenerator();

            string sourcePath = FileSystemHelpers.GetNewVirtualizedPath(_engineEnvironmentSettings);
            IDictionary <string, string> templateSourceFiles = new Dictionary <string, string>();

            templateSourceFiles.Add(pathToTemplateJson, BasicTemplateConfig);
            TestTemplateSetup setup = new TestTemplateSetup(_engineEnvironmentSettings, sourcePath, templateSourceFiles);

            setup.WriteSource();

            IFile templateFile = setup.FileInfoForSourceFile(pathToTemplateJson);
            RunnableProjectConfig templateModel = new RunnableProjectConfig(_engineEnvironmentSettings, generator, baseConfig, templateFile);

            if (shouldAllPathsBeValid)
            {
                Assert.Empty(templateModel.ValidateTemplateSourcePaths());
            }
            else
            {
                Assert.NotEmpty(templateModel.ValidateTemplateSourcePaths());
            }
        }
        internal static ParameterSetter TestParameterSetter(IEngineEnvironmentSettings environmentSettings, IParameterSet parameters)
        {
            ParameterSetter setter = (p, value) =>
            {
                ((RunnableProjectGenerator.ParameterSet)parameters).AddParameter(p);
                parameters.ResolvedValues[p] = RunnableProjectGenerator.InternalConvertParameterValueToType(environmentSettings, p, value, out bool valueResolutionError);
            };

            return(setter);
        }
        public void SplitConfigReadFailsIfAReferencedFileIsMissing()
        {
            string            sourcePath = FileSystemHelpers.GetNewVirtualizedPath(_engineEnvironmentSettings);
            TestTemplateSetup setup      = SetupSplitConfigWithAMissingReferencedFile(_engineEnvironmentSettings, sourcePath);
            IGenerator        generator  = new RunnableProjectGenerator();

            IFileSystemInfo templateConfigFileInfo = setup.InfoForSourceFile(TestFileSystemHelper.DefaultConfigRelativePath);
            bool            result = generator.TryGetTemplateFromConfigInfo(templateConfigFileInfo, out ITemplate template, null, null);

            Assert.False(result, "Template config should not be readable - missing additional file.");
            Assert.Null(template);
        }
        public void SplitConfigCantReferenceFileOutsideBasePath()
        {
            string            sourcePath = FileSystemHelpers.GetNewVirtualizedPath(_engineEnvironmentSettings);
            TestTemplateSetup setup      = SetupSplitConfigWithAFileOutsideMountPoint(_engineEnvironmentSettings, sourcePath);

            IGenerator      generator = new RunnableProjectGenerator();
            IFileSystemInfo templateConfigFileInfo = setup.InfoForSourceFile(TemplateConfigTestHelpers.DefaultConfigRelativePath);
            bool            result = generator.TryGetTemplateFromConfigInfo(templateConfigFileInfo, out ITemplate template, null, null);

            Assert.False(result, "Template config should not be readable - additional file is outside the base path.");
            Assert.Null(template);
        }
        // Warning: if there are unknown macro "types", they are quietly ignored here.
        // This applies to both the regular and deferred macros.
        internal IEnumerable <IOperationProvider> ProcessMacros(IEngineEnvironmentSettings environmentSettings, IReadOnlyList <IMacroConfig> macroConfigs, IVariableCollection variables, IParameterSet parameters)
        {
            EnsureMacros(environmentSettings.Components);
            EnsureDeferredMacros(environmentSettings.Components);

            ParameterSetter setter = (p, value) =>
            {
                ((RunnableProjectGenerator.ParameterSet)parameters).AddParameter(p);
                parameters.ResolvedValues[p] = RunnableProjectGenerator.InternalConvertParameterValueToType(environmentSettings, p, value, out bool valueResolutionError);
                // TODO: consider checking the valueResolutionError and act on it, if needed.
                // Should be safe to ignore, params should be verified by the time this occurs.
            };

            IList <IMacroConfig> allMacroConfigs = new List <IMacroConfig>(macroConfigs);
            IList <GeneratedSymbolDeferredMacroConfig> deferredConfigList = new List <GeneratedSymbolDeferredMacroConfig>();

            // run the macros that are already setup, stash the deferred ones for afterwards
            foreach (IMacroConfig config in allMacroConfigs)
            {
                if (config is GeneratedSymbolDeferredMacroConfig deferredConfig)
                {
                    deferredConfigList.Add(deferredConfig);
                    continue;
                }

                if (_macroObjects.TryGetValue(config.Type, out IMacro macroObject))
                {
                    macroObject.EvaluateConfig(environmentSettings, variables, config, parameters, setter);
                }
            }

            List <Tuple <IMacro, IMacroConfig> > deferredConfigs = new List <Tuple <IMacro, IMacroConfig> >();

            // Set up all deferred macro configurations - this must be done separately from running them
            //  as certain generation types may require (like generating port numbers) that a shared resource
            //  be held in a particular state to influence the production of other values
            foreach (GeneratedSymbolDeferredMacroConfig deferredConfig in deferredConfigList)
            {
                IDeferredMacro deferredMacroObject;
                if (_deferredMacroObjects.TryGetValue(deferredConfig.Type, out deferredMacroObject))
                {
                    deferredConfigs.Add(Tuple.Create((IMacro)deferredMacroObject, deferredMacroObject.CreateConfig(environmentSettings, deferredConfig)));
                }
            }

            foreach (Tuple <IMacro, IMacroConfig> config in deferredConfigs)
            {
                config.Item1.EvaluateConfig(environmentSettings, variables, config.Item2, parameters, setter);
            }

            return(Array.Empty <IOperationProvider>());
        }
        // Warning: if there are unknown macro "types", they are quietly ignored here.
        // This applies to both the regular and deferred macros.
        public IEnumerable <IOperationProvider> ProcessMacros(IEngineEnvironmentSettings environmentSettings, IComponentManager componentManager, IReadOnlyList <IMacroConfig> macroConfigs, IVariableCollection variables, IParameterSet parameters)
        {
            EnsureMacros(componentManager);
            EnsureDeferredMacros(componentManager);

            ParameterSetter setter = (p, value) =>
            {
                ((RunnableProjectGenerator.ParameterSet)parameters).AddParameter(p);
                parameters.ResolvedValues[p] = RunnableProjectGenerator.InternalConvertParameterValueToType(environmentSettings, p, value, out bool valueResolutionError);
                // TODO: consider checking the valueResolutionError and act on it, if needed.
                // Should be safe to ignore, params should be verified by the time this occurs.
            };

            IList <IMacroConfig> allMacroConfigs = new List <IMacroConfig>(macroConfigs);
            IList <GeneratedSymbolDeferredMacroConfig> deferredConfigList = new List <GeneratedSymbolDeferredMacroConfig>();

            // run the macros that are already setup, stash the deferred ones for afterwards
            foreach (IMacroConfig config in allMacroConfigs)
            {
                if (config is GeneratedSymbolDeferredMacroConfig deferredConfig)
                {
                    deferredConfigList.Add(deferredConfig);
                    continue;
                }

                if (_macroObjects.TryGetValue(config.Type, out IMacro macroObject))
                {
                    macroObject.EvaluateConfig(environmentSettings, variables, config, parameters, setter);
                }
            }

            // run the deferred macros
            foreach (GeneratedSymbolDeferredMacroConfig deferredConfig in deferredConfigList)
            {
                IDeferredMacro deferredMacroObject;
                if (_deferredMacroObjects.TryGetValue(deferredConfig.Type, out deferredMacroObject))
                {
                    deferredMacroObject.EvaluateDeferredConfig(environmentSettings, variables, deferredConfig, parameters, setter);
                }
            }

            return(Empty <IOperationProvider> .List.Value);
        }
        public void SplitConfigTest()
        {
            string            sourcePath = FileSystemHelpers.GetNewVirtualizedPath(_engineEnvironmentSettings);
            TestTemplateSetup setup      = SetupSplitConfigTestTemplate(_engineEnvironmentSettings, sourcePath);

            IGenerator      generator = new RunnableProjectGenerator();
            IFileSystemInfo templateConfigFileInfo = setup.InfoForSourceFile("templateSource/.template.config/template.json");

            generator.TryGetTemplateFromConfigInfo(templateConfigFileInfo, out ITemplate template, null, null);

            IDictionary <string, ITemplateParameter> parameters = template.Parameters.ToDictionary(p => p.Name, p => p);

            Assert.Equal(5, parameters.Count);  // 5 in the configs + 1 for 'name' (implicit)
            Assert.True(parameters.ContainsKey("type"));
            Assert.True(parameters.ContainsKey("language"));
            Assert.True(parameters.ContainsKey("RuntimeFrameworkVersion"));
            Assert.True(parameters.ContainsKey("Framework"));
            Assert.True(parameters.ContainsKey("MyThing"));
        }
        // Warning: if there are unknown macro "types", they are quietly ignored here.
        // This applies to both the regular and deferred macros.
        public IEnumerable <IOperationProvider> ProcessMacros(IComponentManager componentManager, IReadOnlyList <IMacroConfig> macroConfigs, IVariableCollection variables, IParameterSet parameters)
        {
            EnsureMacros(componentManager);
            EnsureDeferredMacros(componentManager);

            ParameterSetter setter = (p, value) =>
            {
                ((RunnableProjectGenerator.ParameterSet)parameters).AddParameter(p);
                parameters.ResolvedValues[p] = RunnableProjectGenerator.InternalConvertParameterValueToType(p, value);
            };

            IList <IMacroConfig> allMacroConfigs = new List <IMacroConfig>(macroConfigs);
            IList <GeneratedSymbolDeferredMacroConfig> deferredConfigList = new List <GeneratedSymbolDeferredMacroConfig>();

            // run the macros that are already setup, stash the deferred ones for afterwards
            foreach (IMacroConfig config in allMacroConfigs)
            {
                if (config is GeneratedSymbolDeferredMacroConfig)
                {
                    deferredConfigList.Add(config as GeneratedSymbolDeferredMacroConfig);
                    continue;
                }

                IMacro macroObject;
                if (_macroObjects.TryGetValue(config.Type, out macroObject))
                {
                    macroObject.EvaluateConfig(variables, config, parameters, setter);
                }
            }

            // run the deferred macros
            foreach (GeneratedSymbolDeferredMacroConfig deferredConfig in deferredConfigList)
            {
                IDeferredMacro deferredMacroObject;
                if (_deferredMacroObjects.TryGetValue(deferredConfig.Type, out deferredMacroObject))
                {
                    deferredMacroObject.EvaluateDeferredConfig(variables, deferredConfig, parameters, setter);
                }
            }

            return(Empty <IOperationProvider> .List.Value);
        }
        public void CheckTemplateRootRelativeToInstallPath(string pathToTemplateJson, bool shouldAllPathsBeValid)
        {
            string sourcePath = FileSystemHelpers.GetNewVirtualizedPath(EngineEnvironmentSettings);
            IDictionary <string, string> templateSourceFiles = new Dictionary <string, string>();

            templateSourceFiles.Add(pathToTemplateJson, BasicTemplateConfig);
            TestTemplateSetup setup = new TestTemplateSetup(EngineEnvironmentSettings, sourcePath, templateSourceFiles);

            setup.WriteSource();

            RunnableProjectGenerator generator = new RunnableProjectGenerator();

            IFile                   templateFile            = setup.FileInfoForSourceFile(pathToTemplateJson);
            JObject                 srcObject               = generator.ReadJObjectFromIFile(templateFile);
            SimpleConfigModel       templateModel           = SimpleConfigModel.FromJObject(templateFile.MountPoint.EnvironmentSettings, srcObject);
            RunnableProjectTemplate runnableProjectTemplate = new RunnableProjectTemplate(srcObject, generator, templateFile, templateModel, null, null);

            bool allPathsAreValid = generator.AreAllTemplatePathsValid(templateModel, runnableProjectTemplate);

            Assert.Equal(shouldAllPathsBeValid, allPathsAreValid);
        }
Exemple #14
0
        public void CanReadPostActions()
        {
            var jsonToBe = new
            {
                name        = "TestTemplate",
                identity    = "id",
                shortName   = "test",
                postActions = new[]
                {
                    new
                    {
                        actionId = Guid.NewGuid(),
                    },
                    new
                    {
                        actionId = Guid.NewGuid(),
                    },
                }
            };
            IEngineEnvironmentSettings environmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true);
            string sourceBasePath = environmentSettings.GetNewVirtualizedPath();

            string templateConfigDir = Path.Combine(sourceBasePath, RunnableProjectGenerator.TemplateConfigDirectoryName);
            string filePath          = Path.Combine(templateConfigDir, RunnableProjectGenerator.TemplateConfigFileName);

            environmentSettings.Host.FileSystem.CreateDirectory(templateConfigDir);
            environmentSettings.Host.FileSystem.WriteAllText(filePath, JsonConvert.SerializeObject(jsonToBe));

            IMountPoint mountPoint             = environmentSettings.MountPath(sourceBasePath);
            RunnableProjectGenerator generator = new RunnableProjectGenerator();
            var templates = generator.GetTemplatesAndLangpacksFromDir(mountPoint, out _);

            Assert.Single(templates);
            var template = templates[0];

            Assert.Equal(new[] { jsonToBe.postActions[0].actionId, jsonToBe.postActions[1].actionId }, template.PostActions);
        }
        public void SetConfigTimestampUtc()
        {
            string templateJson       = @"
{
  ""name"": ""TestTemplate"",
  ""identity"": ""TestTemplate"",
  ""shortName"": ""testt"",
  ""symbols"": {
    ""mySymbol"": {
      ""type"": ""parameter"",
      ""replaces"": ""whatever"",
      ""forms"": {
        ""global"": [ ""fakeName"" ],
      }
    }
  }
}
";
            var    pathToTemplateJson = "templateSource/.template.config/template.json";
            string sourcePath         = FileSystemHelpers.GetNewVirtualizedPath(EngineEnvironmentSettings);
            IDictionary <string, string> templateSourceFiles = new Dictionary <string, string>();

            templateSourceFiles.Add(pathToTemplateJson, templateJson);
            TestTemplateSetup setup = new TestTemplateSetup(EngineEnvironmentSettings, sourcePath, templateSourceFiles);

            setup.WriteSource();

            RunnableProjectGenerator generator = new RunnableProjectGenerator();
            var templateFile = setup.InfoForSourceFile(pathToTemplateJson);

            generator.TryGetTemplateFromConfigInfo(templateFile, out ITemplate template, null, null);

            var templateWithTimestamp = Assert.IsAssignableFrom <ITemplateWithTimestamp>(template);

            Assert.NotNull(templateWithTimestamp.ConfigTimestampUtc);
        }
Exemple #16
0
        public async void CreateAsyncTest_MultiChoiceParamJoining()
        {
            //
            // Template content preparation
            //

            string templateConfig = @"
{
  ""identity"": ""test.template"",
  ""symbols"": {
    ""Platform"": {
      ""type"": ""parameter"",
      ""description"": ""The target framework for the project."",
      ""datatype"": ""choice"",
      ""allowMultipleValues"": true,
      ""choices"": [
        {
          ""choice"": ""Windows"",
          ""description"": ""Windows Desktop""
        },
        {
          ""choice"": ""WindowsPhone"",
          ""description"": ""Windows Phone""
        },
        {
          ""choice"": ""MacOS"",
          ""description"": ""Macintosh computers""
        },
        {
          ""choice"": ""iOS"",
          ""description"": ""iOS mobile""
        },
        {
          ""choice"": ""android"",
          ""description"": ""android mobile""
        },
        {
          ""choice"": ""nix"",
          ""description"": ""Linux distributions""
        }
      ],
      ""defaultValue"": ""MacOS|iOS""
    },
    ""joinedRename"": {
      ""type"": ""generated"",
      ""generator"": ""join"",
      ""replaces"": ""SupportedPlatforms"",
      ""parameters"": {
        ""symbols"": [
          {
            ""type"": ""ref"",
            ""value"": ""Platform""
          }
        ],
        ""separator"": "", "",
        ""removeEmptyValues"": true,
      }
    }
  }
}
";

            string sourceSnippet = @"
// This file is generated for platfrom: SupportedPlatforms
";

            string expectedSnippet = @"
// This file is generated for platfrom: MacOS, iOS
";

            IDictionary <string, string?> templateSourceFiles = new Dictionary <string, string?>();

            // template.json
            templateSourceFiles.Add(TestFileSystemHelper.DefaultConfigRelativePath, templateConfig);

            //content
            templateSourceFiles.Add("sourcFile", sourceSnippet);

            //
            // Dependencies preparation and mounting
            //

            IEngineEnvironmentSettings environment = _environmentSettingsHelper.CreateEnvironment();
            string sourceBasePath = FileSystemHelpers.GetNewVirtualizedPath(environment);
            string targetDir      = FileSystemHelpers.GetNewVirtualizedPath(environment);

            TestFileSystemHelper.WriteTemplateSource(environment, sourceBasePath, templateSourceFiles);
            IMountPoint?sourceMountPoint            = TestFileSystemHelper.CreateMountPoint(environment, sourceBasePath);
            RunnableProjectGenerator rpg            = new RunnableProjectGenerator();
            SimpleConfigModel        configModel    = SimpleConfigModel.FromJObject(JObject.Parse(templateConfig));
            IRunnableProjectConfig   runnableConfig = new RunnableProjectConfig(environment, rpg, configModel, sourceMountPoint.FileInfo(TestFileSystemHelper.DefaultConfigRelativePath));
            IParameterSet            parameters     = new ParameterSet(runnableConfig);
            ITemplateParameter       choiceParameter;

            Assert.True(parameters.TryGetParameterDefinition("Platform", out choiceParameter), "ChoiceParam expected to be extracted from template config");
            parameters.ResolvedValues[choiceParameter] = new MultiValueParameter(new[] { "MacOS", "iOS" });
            IDirectory sourceDir = sourceMountPoint !.DirectoryInfo("/") !;

            //
            // Running the actual scenario: template files processing and generating output (including macros processing)
            //

            await rpg.CreateAsync(environment, runnableConfig, sourceDir, parameters, targetDir, CancellationToken.None);

            //
            // Veryfying the outputs
            //

            string resultContent = environment.Host.FileSystem.ReadAllText(Path.Combine(targetDir, "sourcFile"));

            Assert.Equal(expectedSnippet, resultContent);
        }
Exemple #17
0
        public async void CreateAsyncTest_GuidsMacroProcessingCaseSensitivity()
        {
            //
            // Template content preparation
            //

            Guid              inputTestGuid         = new Guid("12aa8f4e-a4aa-4ac1-927c-94cb99485ef1");
            string            contentFileNamePrefix = "content - ";
            SimpleConfigModel config = new SimpleConfigModel()
            {
                Identity = "test",
                Guids    = new List <Guid>()
                {
                    inputTestGuid
                }
            };

            IDictionary <string, string?> templateSourceFiles = new Dictionary <string, string?>();

            // template.json
            templateSourceFiles.Add(TestFileSystemHelper.DefaultConfigRelativePath, config.ToJObject().ToString());

            //content
            foreach (string guidFormat in GuidMacroConfig.DefaultFormats.Select(c => c.ToString()))
            {
                templateSourceFiles.Add(contentFileNamePrefix + guidFormat, inputTestGuid.ToString(guidFormat));
            }

            //
            // Dependencies preparation and mounting
            //

            IEngineEnvironmentSettings environment = _environmentSettingsHelper.CreateEnvironment();
            string sourceBasePath        = FileSystemHelpers.GetNewVirtualizedPath(environment);
            string targetDir             = FileSystemHelpers.GetNewVirtualizedPath(environment);
            RunnableProjectGenerator rpg = new RunnableProjectGenerator();

            TestFileSystemHelper.WriteTemplateSource(environment, sourceBasePath, templateSourceFiles);
            IMountPoint?           sourceMountPoint = TestFileSystemHelper.CreateMountPoint(environment, sourceBasePath);
            IRunnableProjectConfig runnableConfig   = new RunnableProjectConfig(environment, rpg, config, sourceMountPoint.FileInfo(TestFileSystemHelper.DefaultConfigRelativePath));
            IParameterSet          parameters       = new ParameterSet(runnableConfig);
            IDirectory             sourceDir        = sourceMountPoint !.DirectoryInfo("/") !;

            //
            // Running the actual scenario: template files processing and generating output (including macros processing)
            //

            await rpg.CreateAsync(environment, runnableConfig, sourceDir, parameters, targetDir, CancellationToken.None);

            //
            // Veryfying the outputs
            //

            Guid expectedResultGuid = Guid.Empty;

            foreach (string guidFormat in GuidMacroConfig.DefaultFormats.Select(c => c.ToString()))
            {
                string resultContent = environment.Host.FileSystem.ReadAllText(Path.Combine(targetDir, contentFileNamePrefix + guidFormat));
                Guid   resultGuid;
                Assert.True(
                    Guid.TryParseExact(resultContent, guidFormat, out resultGuid),
                    $"Expected the result conent ({resultContent}) to be parseable by Guid format '{guidFormat}'");

                if (expectedResultGuid == Guid.Empty)
                {
                    expectedResultGuid = resultGuid;
                }
                else
                {
                    Assert.Equal(expectedResultGuid, resultGuid);
                }
            }
            Assert.NotEqual(inputTestGuid, expectedResultGuid);
        }
Exemple #18
0
        public async void CreateAsyncTest_MultiChoiceParamReplacingAndCondition()
        {
            //
            // Template content preparation
            //

            string templateConfig = @"
{
    ""identity"": ""test.template"",
    ""symbols"": {	
	    ""ChoiceParam"": {
	      ""type"": ""parameter"",
	      ""description"": ""sample switch"",
	      ""datatype"": ""choice"",
          ""allowMultipleValues"": true,
          ""enableQuotelessLiterals"": true,
	      ""choices"": [
		    {
		      ""choice"": ""FirstChoice"",
		      ""description"": ""First Sample Choice""
		    },
		    {
		      ""choice"": ""SecondChoice"",
		      ""description"": ""Second Sample Choice""
		    },
		    {
		      ""choice"": ""ThirdChoice"",
		      ""description"": ""Third Sample Choice""
		    }
	      ],
          ""defaultValue"": ""ThirdChoice"",
          ""replaces"": ""REPLACE_VALUE""
        }
    }
}
";

            string sourceSnippet = @"
MultiChoiceValue: REPLACE_VALUE
//#if( ChoiceParam == FirstChoice )
FIRST
//#endif
//#if (ChoiceParam == SecondChoice )
SECOND
//#endif
//#if (ChoiceParam == ThirdChoice )
THIRD
//#endif
";

            string expectedSnippet = @"
MultiChoiceValue: SecondChoice|ThirdChoice
SECOND
THIRD
";

            IDictionary <string, string?> templateSourceFiles = new Dictionary <string, string?>();

            // template.json
            templateSourceFiles.Add(TestFileSystemHelper.DefaultConfigRelativePath, templateConfig);

            //content
            templateSourceFiles.Add("sourcFile", sourceSnippet);

            //
            // Dependencies preparation and mounting
            //

            IEngineEnvironmentSettings environment = _environmentSettingsHelper.CreateEnvironment();
            string sourceBasePath = FileSystemHelpers.GetNewVirtualizedPath(environment);
            string targetDir      = FileSystemHelpers.GetNewVirtualizedPath(environment);

            TestFileSystemHelper.WriteTemplateSource(environment, sourceBasePath, templateSourceFiles);
            IMountPoint?sourceMountPoint            = TestFileSystemHelper.CreateMountPoint(environment, sourceBasePath);
            RunnableProjectGenerator rpg            = new RunnableProjectGenerator();
            SimpleConfigModel        configModel    = SimpleConfigModel.FromJObject(JObject.Parse(templateConfig));
            IRunnableProjectConfig   runnableConfig = new RunnableProjectConfig(environment, rpg, configModel, sourceMountPoint.FileInfo(TestFileSystemHelper.DefaultConfigRelativePath));
            IParameterSet            parameters     = new ParameterSet(runnableConfig);
            ITemplateParameter       choiceParameter;

            Assert.True(parameters.TryGetParameterDefinition("ChoiceParam", out choiceParameter), "ChoiceParam expected to be extracted from template config");
            parameters.ResolvedValues[choiceParameter] = new MultiValueParameter(new[] { "SecondChoice", "ThirdChoice" });
            IDirectory sourceDir = sourceMountPoint !.DirectoryInfo("/") !;

            //
            // Running the actual scenario: template files processing and generating output (including macros processing)
            //

            await rpg.CreateAsync(environment, runnableConfig, sourceDir, parameters, targetDir, CancellationToken.None);

            //
            // Veryfying the outputs
            //

            string resultContent = environment.Host.FileSystem.ReadAllText(Path.Combine(targetDir, "sourcFile"));

            Assert.Equal(expectedSnippet, resultContent);
        }
        public async void InstantiateAsync_ParamsProperlyHonored(string?parameterValue, string expectedOutput, bool instantiateShouldFail)
        {
            //
            // Template content preparation
            //

            string sourceSnippet = @"
//#if( ChoiceParam == FirstChoice )
FIRST
//#elseif (ChoiceParam == SecondChoice )
SECOND
//#elseif (ChoiceParam == ThirdChoice )
THIRD
//#else
UNKNOWN
//#endif
";
            IDictionary <string, string?> templateSourceFiles = new Dictionary <string, string?>();

            // template.json
            templateSourceFiles.Add(TestFileSystemHelper.DefaultConfigRelativePath, TemplateConfigQuotelessLiteralsEnabled);

            //content
            templateSourceFiles.Add("sourceFile", sourceSnippet);

            //
            // Dependencies preparation and mounting
            //

            IEngineEnvironmentSettings environment = _engineEnvironmentSettings;
            string sourceBasePath = FileSystemHelpers.GetNewVirtualizedPath(environment);

            TestFileSystemHelper.WriteTemplateSource(environment, sourceBasePath, templateSourceFiles);
            IMountPoint?sourceMountPoint = TestFileSystemHelper.CreateMountPoint(environment, sourceBasePath);
            RunnableProjectGenerator rpg = new RunnableProjectGenerator();
            // cannot use SimpleConfigModel dirrectly - due to missing easy way of creating ParameterSymbols
            SimpleConfigModel configModel = SimpleConfigModel.FromJObject(JObject.Parse(TemplateConfigQuotelessLiteralsEnabled));
            var runnableConfig            = new RunnableProjectConfig(environment, rpg, configModel, sourceMountPoint.FileInfo(TestFileSystemHelper.DefaultConfigRelativePath));

            TemplateCreator creator = new TemplateCreator(_engineEnvironmentSettings);

            string targetDir = FileSystemHelpers.GetNewVirtualizedPath(_engineEnvironmentSettings);

            IReadOnlyDictionary <string, string?> parameters = new Dictionary <string, string?>()
            {
                { "ChoiceParam", parameterValue }
            };

            var res = await creator.InstantiateAsync(
                templateInfo : runnableConfig,
                name : "tst",
                fallbackName : "tst2",
                inputParameters : parameters,
                outputPath : targetDir);

            if (instantiateShouldFail)
            {
                Assert.NotNull(res.ErrorMessage);
                Assert.Null(res.OutputBaseDirectory);
            }
            else
            {
                Assert.Null(res.ErrorMessage);
                Assert.NotNull(res.OutputBaseDirectory);
                string resultContent = _engineEnvironmentSettings.Host.FileSystem
                                       .ReadAllText(Path.Combine(res.OutputBaseDirectory !, "sourceFile")).Trim();
                Assert.Equal(expectedOutput, resultContent);
            }
        }
        public void PerformTemplateValidation_ChoiceValuesValidation(string paramDefintion, bool isMultichoice, bool expectedToBeValid)
        {
            //
            // Template content preparation
            //

            Guid    inputTestGuid         = new Guid("12aa8f4e-a4aa-4ac1-927c-94cb99485ef1");
            string  contentFileNamePrefix = "content - ";
            JObject choiceParam           = JObject.Parse(paramDefintion);

            choiceParam["AllowMultipleValues"] = isMultichoice;
            SimpleConfigModel config = new SimpleConfigModel()
            {
                Identity      = "test",
                Name          = "name",
                ShortNameList = new [] { "shortName" },
                Symbols       = new Dictionary <string, ISymbolModel>()
                {
                    { "ParamA", new ParameterSymbol(choiceParam, null) }
                }
            };

            IDictionary <string, string?> templateSourceFiles = new Dictionary <string, string?>();

            // template.json
            templateSourceFiles.Add(TestFileSystemHelper.DefaultConfigRelativePath, config.ToJObject().ToString());

            //content
            foreach (string guidFormat in GuidMacroConfig.DefaultFormats.Select(c => c.ToString()))
            {
                templateSourceFiles.Add(contentFileNamePrefix + guidFormat, inputTestGuid.ToString(guidFormat));
            }

            //
            // Dependencies preparation and mounting
            //

            List <(LogLevel, string)>  loggedMessages = new List <(LogLevel, string)>();
            InMemoryLoggerProvider     loggerProvider = new InMemoryLoggerProvider(loggedMessages);
            IEngineEnvironmentSettings environment    = _environmentSettingsHelper.CreateEnvironment(addLoggerProviders: new [] { loggerProvider });
            string sourceBasePath        = FileSystemHelpers.GetNewVirtualizedPath(environment);
            string targetDir             = FileSystemHelpers.GetNewVirtualizedPath(environment);
            RunnableProjectGenerator rpg = new RunnableProjectGenerator();

            TestFileSystemHelper.WriteTemplateSource(environment, sourceBasePath, templateSourceFiles);
            IMountPoint?          sourceMountPoint = TestFileSystemHelper.CreateMountPoint(environment, sourceBasePath);
            RunnableProjectConfig runnableConfig   = new RunnableProjectConfig(environment, rpg, config, sourceMountPoint.FileInfo(TestFileSystemHelper.DefaultConfigRelativePath));

            if (expectedToBeValid)
            {
                runnableConfig.PerformTemplateValidation();
                Assert.Empty(loggedMessages.Where(l => l.Item1 >= LogLevel.Warning));
            }
            else
            {
                var exc = Assert.Throws <TemplateValidationException>(runnableConfig.PerformTemplateValidation);
                Assert.Contains("The template configuration ", exc.Message);
                Assert.Contains(" is not valid.", exc.Message);
                Assert.Single(loggedMessages.Where(l => l.Item1 >= LogLevel.Warning));
                string errorMessage = loggedMessages.First(l => l.Item1 >= LogLevel.Warning).Item2;
                Assert.Contains(
                    "Choice parameter  is invalid. It allows multiple values ('AllowMultipleValues=true'), while some of the configured choices contain separator characters ('|', ','). Invalid choices: {First|Choice}",
                    errorMessage);
            }
        }