Ejemplo n.º 1
0
        private IEnumerable <TemplateSearchData> TryGetTemplatesInPack(IDownloadedPackInfo packInfo, IReadOnlyList <IAdditionalDataProducer> additionalDataProducers)
        {
            ITemplateEngineHost host = TemplateEngineHostHelper.CreateHost(HostIdentifierBase + packInfo.Name);

            using EngineEnvironmentSettings environmentSettings = new EngineEnvironmentSettings(host, virtualizeSettings: true);
            Scanner scanner = new Scanner(environmentSettings);

            try
            {
                using var scanResult = scanner.Scan(packInfo.Path, scanForComponents: false);
                if (scanResult.Templates.Any())
                {
                    foreach (IAdditionalDataProducer dataProducer in additionalDataProducers)
                    {
#pragma warning disable CS0612 // Type or member is obsolete
                        dataProducer.CreateDataForTemplatePack(packInfo, scanResult.Templates, environmentSettings);
#pragma warning restore CS0612 // Type or member is obsolete
                    }

                    return(scanResult.Templates.Select(t => new TemplateSearchData(t, t.ProduceAdditionalData(additionalDataProducers, environmentSettings))));
                }
                return(Array.Empty <TemplateSearchData>());
            }
            catch (TaskCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to read package {0}::{1}, details: {2}. The package will be skipped.", packInfo.Name, packInfo.Version, ex);
                return(Array.Empty <TemplateSearchData>());
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Creates the instance.
        /// </summary>
        /// <param name="host">caller <see cref="ITemplateEngineHost"/>.</param>
        /// <param name="virtualizeConfiguration">if true, settings will be stored in memory and will be disposed with instance.</param>
        /// <param name="loadDefaultComponents">if true, the default components (providers, installers, generator) will be loaded. Same as calling <see cref="LoadDefaultComponents()"/> after instance is created.</param>
        /// <param name="hostSettingsLocation">the file path to store host specific settings. Use null for default location.
        /// Note: this parameter changes only directory of host and host version specific settings. Global settings path remains unchanged.</param>
        public Bootstrapper(ITemplateEngineHost host, bool virtualizeConfiguration, bool loadDefaultComponents = true, string?hostSettingsLocation = null)
        {
            _host = host ?? throw new ArgumentNullException(nameof(host));

            if (string.IsNullOrWhiteSpace(hostSettingsLocation))
            {
                _engineEnvironmentSettings = new EngineEnvironmentSettings(host, virtualizeSettings: virtualizeConfiguration);
            }
            else
            {
                string       hostSettingsDir        = Path.Combine(hostSettingsLocation, host.HostIdentifier);
                string       hostVersionSettingsDir = Path.Combine(hostSettingsLocation, host.HostIdentifier, host.Version);
                IEnvironment environment            = new DefaultEnvironment();
                IPathInfo    pathInfo = new DefaultPathInfo(environment, host, hostSettingsDir: hostSettingsDir, hostVersionSettingsDir: hostVersionSettingsDir);
                _engineEnvironmentSettings = new EngineEnvironmentSettings(
                    host,
                    virtualizeSettings: virtualizeConfiguration,
                    environment: environment,
                    pathInfo: pathInfo);
            }

            _templateCreator         = new TemplateCreator(_engineEnvironmentSettings);
            _templatePackagesManager = new Edge.Settings.TemplatePackageManager(_engineEnvironmentSettings);
            if (loadDefaultComponents)
            {
                LoadDefaultComponents();
            }
        }
Ejemplo n.º 3
0
        private CodeGen(string locationId, string hostVersion)
        {
            var host = CreateHost(locationId, hostVersion);

            Settings = new EngineEnvironmentSettings(host, x => new SettingsLoader(x));
            Creator  = new TemplateCreator(Settings);
        }
Ejemplo n.º 4
0
        private void TryCleanup(EngineEnvironmentSettings environment)
        {
            Paths paths = new Paths(environment);

            try
            {
                paths.Delete(paths.User.BaseDir);
            }
            catch
            {
                // do nothing.
            }

            // remove the temporary hive
            string hiveDir = Directory.GetParent(paths.User.BaseDir).FullName;

            try
            {
                paths.Delete(hiveDir);
            }
            catch
            {
                // do nothing.
            }
        }
Ejemplo n.º 5
0
        internal void CanParseMultiChoiceTemplateOptions(string command, string parameterName, string parameterValues, string?defaultIfNoOptionValue, string?expectedValue)
        {
            var template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group")
                           .WithChoiceParameter(parameterName, parameterValues.Split("|"), defaultIfNoOptionValue: defaultIfNoOptionValue, allowMultipleValues: true);

            TemplateGroup templateGroup = TemplateGroup.FromTemplateList(
                CliTemplateInfo.FromTemplateInfo(new[] { template }, A.Fake <IHostSpecificDataLoader>()))
                                          .Single();

            ITemplateEngineHost        host           = TestHost.GetVirtualHost();
            IEngineEnvironmentSettings settings       = new EngineEnvironmentSettings(host, virtualizeSettings: true);
            TemplatePackageManager     packageManager = A.Fake <TemplatePackageManager>();

            NewCommand             myCommand           = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());
            var                    parseResult         = myCommand.Parse($" new {command}");
            InstantiateCommandArgs args                = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult));
            TemplateCommand        templateCommand     = new TemplateCommand(myCommand, settings, packageManager, templateGroup, templateGroup.Templates.Single());
            Parser                 parser              = ParserFactory.CreateParser(templateCommand);
            ParseResult            templateParseResult = parser.Parse(args.RemainingArguments ?? Array.Empty <string>());
            var                    templateArgs        = new TemplateCommandArgs(templateCommand, myCommand, templateParseResult);

            if (string.IsNullOrWhiteSpace(expectedValue))
            {
                Assert.False(templateArgs.TemplateParameters.ContainsKey(parameterName));
            }
            else
            {
                Assert.True(templateArgs.TemplateParameters.ContainsKey(parameterName));
                Assert.Equal(expectedValue, templateArgs.TemplateParameters[parameterName]);
            }
        }
        public ScrapeComparer(ComparisonConfig config)
        {
            _config = config;
            ITemplateEngineHost host = TemplateEngineHostHelper.CreateHost("Comparison");

            _environmentSettings = new EngineEnvironmentSettings(host, virtualizeSettings: true);
        }
Ejemplo n.º 7
0
        public Task FailedToResolveTemplate_WhenMultipleLanguagesAreFound()
        {
            IReadOnlyList <ITemplateInfo> templatesToSearch = new List <ITemplateInfo>()
            {
                new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.L1", groupIdentity: "Console.App.Test").WithTag("language", "L1"),
                new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.L2", groupIdentity: "Console.App.Test").WithTag("language", "L2"),
                new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.L3", groupIdentity: "Console.App.Test").WithTag("language", "L3")
            };

            TemplateGroup templateGroup = TemplateGroup.FromTemplateList(CliTemplateInfo.FromTemplateInfo(templatesToSearch, A.Fake <IHostSpecificDataLoader>())).Single();

            ITemplateEngineHost        host     = TestHost.GetVirtualHost();
            IEngineEnvironmentSettings settings = new EngineEnvironmentSettings(host, virtualizeSettings: true);

            NewCommand myCommand         = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());
            var        parseResult       = myCommand.Parse($" new console");
            var        args              = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult));
            var        matchingTemplates = InstantiateCommand.GetMatchingTemplates(args, settings, A.Fake <TemplatePackageManager>(), templateGroup);

            Assert.Equal(3, matchingTemplates.Count());
            StringWriter output   = new StringWriter();
            Reporter     reporter = new Reporter(new AnsiConsole(output));

            Assert.False(InstantiateCommand.VerifyMatchingTemplates(settings, matchingTemplates, reporter, out _));
            return(Verifier.Verify(output.ToString(), _verifySettings.Settings));
        }
Ejemplo n.º 8
0
        public void HasTypeMismatch_HasGroupLanguageMatch()
        {
            List <ITemplateInfo> templatesToSearch = new List <ITemplateInfo>();

            templatesToSearch.Add(
                new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T1", groupIdentity: "Console.App.Test")
                .WithTag("language", "L1")
                .WithTag("type", "project")
                .WithBaselineInfo("app", "standard"));

            templatesToSearch.Add(
                new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T2", groupIdentity: "Console.App.Test")
                .WithTag("language", "L2")
                .WithTag("type", "project")
                .WithBaselineInfo("app", "standard"));

            TemplateGroup templateGroup = TemplateGroup.FromTemplateList(CliTemplateInfo.FromTemplateInfo(templatesToSearch, A.Fake <IHostSpecificDataLoader>())).Single();

            ITemplateEngineHost        host     = TestHost.GetVirtualHost();
            IEngineEnvironmentSettings settings = new EngineEnvironmentSettings(host, virtualizeSettings: true);

            NewCommand myCommand         = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());
            var        parseResult       = myCommand.Parse($"new console --language L2 --type item");
            var        args              = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult));
            var        matchingTemplates = InstantiateCommand.GetMatchingTemplates(args, settings, A.Fake <TemplatePackageManager>(), templateGroup);

            Assert.Equal(0, matchingTemplates.Count());
        }
Ejemplo n.º 9
0
        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 PackCheckResult TryGetTemplatesInPack(IDownloadedPackInfo packInfo, IReadOnlyList <IAdditionalDataProducer> additionalDataProducers, HashSet <string> alreadySeenTemplateIdentities)
        {
            ITemplateEngineHost host = CreateHost(packInfo);

            using EngineEnvironmentSettings environmentSettings = new EngineEnvironmentSettings(host, virtualizeSettings: true);

            PackCheckResult checkResult;

            try
            {
                if (TryInstallPackage(packInfo.Path, environmentSettings, out IReadOnlyList <ITemplateInfo> installedTemplates))
                {
                    IReadOnlyList <ITemplateInfo> filteredInstalledTemplates = installedTemplates.Where(t => !alreadySeenTemplateIdentities.Contains(t.Identity)).ToList();
                    checkResult = new PackCheckResult(packInfo, filteredInstalledTemplates);
                    ProduceAdditionalDataForPack(additionalDataProducers, checkResult, environmentSettings);
                }
                else
                {
                    IReadOnlyList <ITemplateInfo> foundTemplates = new List <ITemplateInfo>();
                    checkResult = new PackCheckResult(packInfo, foundTemplates);
                }
            }
            catch
            {
                IReadOnlyList <ITemplateInfo> foundTemplates = new List <ITemplateInfo>();
                checkResult = new PackCheckResult(packInfo, foundTemplates);
            }
            return(checkResult);
        }
Ejemplo n.º 11
0
        public void CanCompleteTypes()
        {
            var template1 = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group")
                            .WithTag("type", "project");

            var template2 = new MockTemplateInfo("foo", identity: "foo.2", groupIdentity: "foo.group")
                            .WithTag("type", "solution");

            var templateGroups = TemplateGroup.FromTemplateList(
                CliTemplateInfo.FromTemplateInfo(new[] { template1, template2 }, A.Fake <IHostSpecificDataLoader>()));

            ITemplateEngineHost        host           = TestHost.GetVirtualHost();
            IEngineEnvironmentSettings settings       = new EngineEnvironmentSettings(host, virtualizeSettings: true);
            TemplatePackageManager     packageManager = A.Fake <TemplatePackageManager>();

            NewCommand             myCommand         = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());
            var                    parseResult       = myCommand.Parse($" new foo --type ");
            InstantiateCommandArgs args              = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult));
            var                    completionContext = parseResult.GetCompletionContext() as TextCompletionContext;

            Assert.NotNull(completionContext);

            var result = InstantiateCommand.GetTemplateCompletions(args, templateGroups, settings, packageManager, completionContext !).Select(l => l.Label);

            Assert.Equal(new[] { "project", "solution" }, result);
        }
Ejemplo n.º 12
0
        public Task CanShowTemplateOptions_MultipleTemplate_MultipleParams()
        {
            var template1 = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group", precedence: 0)
                            .WithChoiceParameter("choice", new[] { "val1", "val2" }, description: "my description", defaultValue: "def-val-not-shown", defaultIfNoOptionValue: "def-val-not-shown")
                            .WithParameter("bool", paramType: "boolean", description: "my bool", defaultValue: "false", defaultIfNoOptionValue: "false");
            var template2 = new MockTemplateInfo("foo", identity: "foo.2", groupIdentity: "foo.group", precedence: 2)
                            .WithChoiceParameter("choice", new[] { "val1", "val3" }, description: "my description", defaultValue: "def-val", defaultIfNoOptionValue: "def-val-no-arg")
                            .WithParameter("int", paramType: "integer", description: "my int", defaultValue: "0", defaultIfNoOptionValue: "10");
            TemplateGroup templateGroup = TemplateGroup.FromTemplateList(
                CliTemplateInfo.FromTemplateInfo(new[] { template1, template2 }, A.Fake <IHostSpecificDataLoader>()))
                                          .Single();

            ITemplateEngineHost        host           = TestHost.GetVirtualHost();
            IEngineEnvironmentSettings settings       = new EngineEnvironmentSettings(host, virtualizeSettings: true);
            TemplatePackageManager     packageManager = A.Fake <TemplatePackageManager>();

            NewCommand myCommand = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());

            TemplateCommand templateCommand1 = new TemplateCommand(myCommand, settings, packageManager, templateGroup, templateGroup.Templates[0]);
            TemplateCommand templateCommand2 = new TemplateCommand(myCommand, settings, packageManager, templateGroup, templateGroup.Templates[1]);

            StringWriter sw          = new StringWriter();
            HelpContext  helpContext = new HelpContext(new HelpBuilder(LocalizationResources.Instance), myCommand, sw);

            InstantiateCommand.ShowTemplateSpecificOptions(new[] { templateCommand2, templateCommand1 }, helpContext);
            return(Verifier.Verify(sw.ToString(), _verifySettings.Settings));
        }
Ejemplo n.º 13
0
        internal void Create_CanEvaluateTemplateToRun(string command, string templateSet, string?defaultLanguage, string?expectedIdentitiesStr)
        {
            TemplateGroup templateGroup = TemplateGroup.FromTemplateList(
                CliTemplateInfo.FromTemplateInfo(_testSets[templateSet], A.Fake <IHostSpecificDataLoader>()))
                                          .Single();

            string[] expectedIdentities = expectedIdentitiesStr?.Split("|") ?? Array.Empty <string>();

            var defaultParams = new Dictionary <string, string>();

            if (defaultLanguage != null)
            {
                defaultParams["prefs:language"] = defaultLanguage;
            }

            ITemplateEngineHost        host     = TestHost.GetVirtualHost(defaultParameters: defaultParams);
            IEngineEnvironmentSettings settings = new EngineEnvironmentSettings(host, virtualizeSettings: true);

            NewCommand myCommand          = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());
            var        parseResult        = myCommand.Parse($"new create {command}");
            var        instantiateCommand = (InstantiateCommand)parseResult.CommandResult.Command;
            var        args             = new InstantiateCommandArgs(instantiateCommand, parseResult);
            var        templateCommands = InstantiateCommand.GetTemplateCommand(args, settings, A.Fake <TemplatePackageManager>(), templateGroup);

            Assert.Equal(expectedIdentities.Count(), templateCommands.Count);
            Assert.Equal(expectedIdentities.OrderBy(s => s), templateCommands.Select(templateCommand => templateCommand.Template.Identity).OrderBy(s => s));
        }
Ejemplo n.º 14
0
        public ScrapeComparer(ComparisonConfig config)
        {
            _config = config;
            ITemplateEngineHost host = TemplateEngineHostHelper.CreateHost("Comparison");

            _environmentSettings = new EngineEnvironmentSettings(host, x => new SettingsLoader(x));
        }
Ejemplo n.º 15
0
        internal void Create_CanDetectParseErrorsChoiceTemplateOptions(
            string command,
            string parameterName,
            string parameterValues,
            bool isRequired,
            string?defaultValue,
            string?defaultIfNoOptionValue,
            string expectedError)
        {
            var template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group")
                           .WithChoiceParameter(parameterName, parameterValues.Split("|"), isRequired, defaultValue, defaultIfNoOptionValue);

            TemplateGroup templateGroup = TemplateGroup.FromTemplateList(
                CliTemplateInfo.FromTemplateInfo(new[] { template }, A.Fake <IHostSpecificDataLoader>()))
                                          .Single();

            ITemplateEngineHost        host           = TestHost.GetVirtualHost();
            IEngineEnvironmentSettings settings       = new EngineEnvironmentSettings(host, virtualizeSettings: true);
            TemplatePackageManager     packageManager = A.Fake <TemplatePackageManager>();

            NewCommand myCommand          = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());
            var        parseResult        = myCommand.Parse($" new create {command}");
            var        instantiateCommand = (InstantiateCommand)parseResult.CommandResult.Command;
            var        args = new InstantiateCommandArgs(instantiateCommand, parseResult);

            TemplateCommand templateCommand     = new TemplateCommand(instantiateCommand, settings, packageManager, templateGroup, templateGroup.Templates.Single());
            Parser          parser              = ParserFactory.CreateParser(templateCommand);
            ParseResult     templateParseResult = parser.Parse(args.RemainingArguments ?? Array.Empty <string>());

            Assert.True(templateParseResult.Errors.Any());
            Assert.Equal(expectedError, templateParseResult.Errors.Single().Message);
        }
Ejemplo n.º 16
0
        public void DefaultLanguageDisambiguates()
        {
            List <ITemplateInfo> templatesToSearch = new List <ITemplateInfo>();

            templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.L1", groupIdentity: "Console.App.Test").WithTag("language", "L1"));
            templatesToSearch.Add(new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.L2", groupIdentity: "Console.App.Test").WithTag("language", "L2"));

            TemplateGroup templateGroup = TemplateGroup.FromTemplateList(CliTemplateInfo.FromTemplateInfo(templatesToSearch, A.Fake <IHostSpecificDataLoader>())).Single();

            var defaultParams = new Dictionary <string, string>();

            defaultParams["prefs:language"] = "L1";

            ITemplateEngineHost        host     = TestHost.GetVirtualHost(defaultParameters: defaultParams);
            IEngineEnvironmentSettings settings = new EngineEnvironmentSettings(host, virtualizeSettings: true);

            NewCommand myCommand         = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());
            var        parseResult       = myCommand.Parse($" new console");
            var        args              = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult));
            var        matchingTemplates = InstantiateCommand.GetMatchingTemplates(args, settings, A.Fake <TemplatePackageManager>(), templateGroup);

            Assert.Equal(2, matchingTemplates.Count());
            StringWriter output   = new StringWriter();
            Reporter     reporter = new Reporter(new AnsiConsole(output));

            Assert.True(InstantiateCommand.VerifyMatchingTemplates(settings, matchingTemplates, reporter, out IEnumerable <TemplateCommand>?filtered));
            Assert.Equal(1, filtered?.Count());
            Assert.Equal("Console.App.L1", filtered?.Single().Template.Identity);
            Assert.Empty(output.ToString());
        }
Ejemplo n.º 17
0
        internal void CanParseAllowScriptsOption(string command, AllowRunScripts?result)
        {
            var template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group")
                           .WithPostActions(ProcessStartPostActionProcessor.ActionProcessorId);

            TemplateGroup templateGroup = TemplateGroup.FromTemplateList(
                CliTemplateInfo.FromTemplateInfo(new[] { template }, A.Fake <IHostSpecificDataLoader>()))
                                          .Single();

            ITemplateEngineHost        host           = TestHost.GetVirtualHost();
            IEngineEnvironmentSettings settings       = new EngineEnvironmentSettings(host, virtualizeSettings: true);
            TemplatePackageManager     packageManager = A.Fake <TemplatePackageManager>();

            NewCommand             myCommand   = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());
            var                    parseResult = myCommand.Parse(command);
            InstantiateCommandArgs args        = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult));

            TemplateCommand templateCommand     = new TemplateCommand(myCommand, settings, packageManager, templateGroup, templateGroup.Templates.Single());
            Parser          parser              = ParserFactory.CreateParser(templateCommand);
            ParseResult     templateParseResult = parser.Parse(args.RemainingArguments ?? Array.Empty <string>());

            TemplateCommandArgs templateArgs = new TemplateCommandArgs(templateCommand, myCommand, templateParseResult);

            Assert.Equal(result, templateArgs.AllowScripts);
        }
Ejemplo n.º 18
0
        private ITemplateEngineHost LoadHostWithLocalizationTemplates(out SettingsLoader settingsLoaderOut)
        {
            var thisDir             = Path.GetDirectoryName(typeof(LocalizationTests).Assembly.Location);
            var testTemplatesFolder = Path.Combine(thisDir, "..", "..", "..", "..", "..",
                                                   "test", "Microsoft.TemplateEngine.TestTemplates", "test_templates", "TemplateWithLocalization");

            testTemplatesFolder = new DirectoryInfo(testTemplatesFolder).FullName;

            ITemplateEngineHost host = new TestHost
            {
                HostIdentifier = "TestRunner",
                Version        = "1.0.0.0",
                Locale         = "en-US",
                FallbackHostTemplateConfigNames = Array.Empty <string>(),
            };

            SettingsLoader settingsLoader = null;
            var            envSettings    = new EngineEnvironmentSettings(host, x => settingsLoader = new SettingsLoader(x));

            host.VirtualizeDirectory(Path.Combine(Environment.ExpandEnvironmentVariables("%USERPROFILE%"),
                                                  ".templateengine", "TestRunner"));
            settingsLoader.Components.Register(typeof(RunnableProjectGenerator));

            settingsLoader.UserTemplateCache.Scan(testTemplatesFolder);
            settingsLoader.Save();
            settingsLoaderOut = settingsLoader;
            return(host);
        }
Ejemplo n.º 19
0
        internal static Func <IDownloadedPackInfo, PreFilterResult> SetupPackFilter()
        {
            Func <IDownloadedPackInfo, PreFilterResult> filter = (packInfo) =>
            {
                using EngineEnvironmentSettings environmentSettings = new EngineEnvironmentSettings(_host, virtualizeSettings: true);
                foreach (IMountPointFactory factory in environmentSettings.Components.OfType <IMountPointFactory>())
                {
                    if (factory.TryMount(environmentSettings, null, packInfo.Path, out IMountPoint? mountPoint))
                    {
                        bool hasTemplateJson = mountPoint !.Root.EnumerateFiles("template.json", SearchOption.AllDirectories).Any();
                        mountPoint.Dispose();

                        if (hasTemplateJson)
                        {
                            return(new PreFilterResult(_FilterId, isFiltered: false));
                        }

                        break;  // this factory mounted the pack. No more checking is needed.
                    }
                }

                return(new PreFilterResult(_FilterId, isFiltered: true, "Package did not contain any template.json files"));
            };

            return(filter);
        }
Ejemplo n.º 20
0
        public PackCheckResult TryGetTemplatesInPack(IInstalledPackInfo packInfo, IReadOnlyList <IAdditionalDataProducer> additionalDataProducers, HashSet <string> alreadySeenTemplateIdentities, bool persistHive = false)
        {
            ITemplateEngineHost       host        = CreateHost(packInfo);
            EngineEnvironmentSettings environment = new EngineEnvironmentSettings(host, x => new SettingsLoader(x));
            PackCheckResult           checkResult;

            try
            {
                if (TryInstallPackage(packInfo.Path, environment, out IReadOnlyList <ITemplateInfo> installedTemplates))
                {
                    IReadOnlyList <ITemplateInfo> filteredInstalledTemplates = installedTemplates.Where(t => !alreadySeenTemplateIdentities.Contains(t.Identity)).ToList();
                    checkResult = new PackCheckResult(packInfo, filteredInstalledTemplates);
                    ProduceAdditionalDataForPack(additionalDataProducers, checkResult, environment);
                }
                else
                {
                    IReadOnlyList <ITemplateInfo> foundTemplates = new List <ITemplateInfo>();
                    checkResult = new PackCheckResult(packInfo, foundTemplates);
                }
            }
            catch
            {
                IReadOnlyList <ITemplateInfo> foundTemplates = new List <ITemplateInfo>();
                checkResult = new PackCheckResult(packInfo, foundTemplates);
            }

            if (!persistHive)
            {
                TryCleanup(environment);
            }

            return(checkResult);
        }
Ejemplo n.º 21
0
        void Initialize()
        {
            host            = new CustomTemplateEngineHost();
            settings        = new EngineEnvironmentSettings(host, s => new SettingsLoader(s));
            paths           = new Paths(settings);
            templateCreator = new TemplateCreator(settings);

            DeleteCache();
        }
Ejemplo n.º 22
0
        public void NupkgReinstallDoesntRemoveTemplates()
        {
            const string nupkgToInstallName = "TestNupkgInstallTemplate.0.0.1.nupkg";
            const string checkTemplateName  = "nupkginstall";   // this is the short name of the template in the nupkg that gets installed.

            ITemplateEngineHost host = CreateHostWithVirtualizedHive(HostIdentifier, HostVersion);

            Assert.NotNull(host);

            ITelemetryLogger telemetryLogger = new TelemetryLogger(null, false);
            int initializeResult             = New3Command.Run(CommandName, host, telemetryLogger, null, new string[] { });

            Assert.Equal(0, initializeResult);

            string codebase      = typeof(NupkgInstallTests).GetTypeInfo().Assembly.CodeBase;
            Uri    cb            = new Uri(codebase);
            string asmPath       = cb.LocalPath;
            string dir           = Path.GetDirectoryName(asmPath);
            string pathToInstall = Path.Combine(dir, "TemplateInstallTests", "TestTemplates", nupkgToInstallName);

            Assert.True(File.Exists(pathToInstall), $"directory didnt exist: {pathToInstall}");

            string[] installArgs = new[]
            {
                "--install",
                pathToInstall
            };

            // install the test pack
            int firstInstallResult = New3Command.Run(CommandName, host, telemetryLogger, null, installArgs);

            Assert.Equal(0, firstInstallResult);

            EngineEnvironmentSettings environemnt    = new EngineEnvironmentSettings(host, x => new SettingsLoader(x));
            SettingsLoader            settingsLoader = (SettingsLoader)environemnt.SettingsLoader;
            IHostSpecificDataLoader   hostDataLoader = new MockHostSpecificDataLoader();

            // check that the template was installed from the first install.
            IReadOnlyCollection <ITemplateMatchInfo> allTemplates = TemplateListResolver.PerformAllTemplatesQuery(settingsLoader.UserTemplateCache.TemplateInfo, hostDataLoader);

            Assert.Contains(checkTemplateName, allTemplates.Select(t => t.Info.ShortName));

            // install the same test pack again
            int secondInstallResult = New3Command.Run(CommandName, host, telemetryLogger, null, installArgs);

            Assert.Equal(0, secondInstallResult);

            settingsLoader.Reload();

            // check that the template is still installed after the second install.
            IReadOnlyCollection <ITemplateMatchInfo> allTemplatesAfterSecondInstall = TemplateListResolver.PerformAllTemplatesQuery(settingsLoader.UserTemplateCache.TemplateInfo, hostDataLoader);

            Assert.Contains(checkTemplateName, allTemplatesAfterSecondInstall.Select(t => t.Info.ShortName));
        }
Ejemplo n.º 23
0
        protected TestBase()
        {
            ITemplateEngineHost host = new TestHost
            {
                HostIdentifier = "TestRunner",
                Version        = "1.0.0.0",
                Locale         = "en-US"
            };

            EnvironmentSettings = new EngineEnvironmentSettings(host, s => null);
            host.VirtualizeDirectory(Environment.ExpandEnvironmentVariables("%USERPROFILE%/.templateengine"));
        }
Ejemplo n.º 24
0
        public Bootstrapper(ITemplateEngineHost host, Action <IEngineEnvironmentSettings, IInstaller> onFirstRun, bool virtualizeConfiguration)
        {
            _host = host;
            EnvironmentSettings = new EngineEnvironmentSettings(host, x => new SettingsLoader(x));
            Installer           = new Installer(EnvironmentSettings);
            _onFirstRun         = onFirstRun;
            _paths           = new Paths(EnvironmentSettings);
            _templateCreator = new TemplateCreator(EnvironmentSettings);

            if (virtualizeConfiguration)
            {
                EnvironmentSettings.Host.VirtualizeDirectory(_paths.User.BaseDir);
            }
        }
Ejemplo n.º 25
0
 public New3Command(string commandName, ITemplateEngineHost host, Action <IEngineEnvironmentSettings, IInstaller> onFirstRun, ExtendedCommandParser app, CommandArgument templateName)
 {
     host = new ExtendedTemplateEngineHost(host, this);
     EnvironmentSettings = new EngineEnvironmentSettings(host, x => new SettingsLoader(x));
     Installer           = new Installer(EnvironmentSettings);
     _templateCreator    = new TemplateCreator(EnvironmentSettings);
     _templateCache      = new TemplateCache(EnvironmentSettings);
     _aliasRegistry      = new AliasRegistry(EnvironmentSettings);
     CommandName         = commandName;
     _paths = new Paths(EnvironmentSettings);
     _app   = app;
     _templateNameArgument = templateName;
     _onFirstRun           = onFirstRun;
 }
Ejemplo n.º 26
0
        protected IEngineEnvironmentSettings CreateEnvironmentSettings(GlobalArgs args, ParseResult parseResult)
        {
            //reparse to get output option if present
            //it's kept private so it is not reused for any other purpose except initializing host
            //for template instantiaton it has to be reparsed
            string?outputPath = ParseOutputOption(parseResult);
            IEngineEnvironmentSettings environmentSettings = new EngineEnvironmentSettings(
                new CliTemplateEngineHost(_hostBuilder(parseResult), outputPath),
                settingsLocation: args.DebugCustomSettingsLocation,
                virtualizeSettings: args.DebugVirtualizeSettings,
                environment: new CliEnvironment());

            return(environmentSettings);
        }
Ejemplo n.º 27
0
        private EngineEnvironmentSettings GetEngineEnvironmentSettings()
        {
            var envSettings = new EngineEnvironmentSettings(
                new DefaultTemplateEngineHost("Initializr", "v1.0", string.Empty),
                (IEngineEnvironmentSettings settings) => new InitializrSettingsLoader(settings, _hivePath),
                _hivePath);
            var cachePath = Path.Combine(_hivePath, "templatecache.json");

            if (!File.Exists(cachePath))
            {
                Console.WriteLine("File doesnt exist " + cachePath);
                ((InitializrSettingsLoader)envSettings.SettingsLoader).RebuildCacheFromSettingsIfNotCurrent(true);
            }

            return(envSettings);
        }
Ejemplo n.º 28
0
        private bool TryInstallPackage(string packageFile, EngineEnvironmentSettings environment, out IReadOnlyList <ITemplateInfo> installedTemplates)
        {
            ((SettingsLoader)(environment.SettingsLoader)).UserTemplateCache.Scan(packageFile);
            environment.SettingsLoader.Save();

            if (((SettingsLoader)environment.SettingsLoader).UserTemplateCache.TemplateInfo.Count > 0)
            {
                installedTemplates = ((SettingsLoader)environment.SettingsLoader).UserTemplateCache.TemplateInfo;
            }
            else
            {
                installedTemplates = new List <ITemplateInfo>();
            }

            return(installedTemplates.Count > 0);
        }
Ejemplo n.º 29
0
        public Task CannotCreateCommandForInvalidParameter()
        {
            var template = new MockTemplateInfo("foo", identity: "foo.1", groupIdentity: "foo.group")
                           .WithParameters("have:colon", "n1", "n2");

            var paramSymbolInfo = new Dictionary <string, string>()
            {
                { "longName", "name" },
                { "shortName", "n" }
            };
            var symbolInfo = new Dictionary <string, IReadOnlyDictionary <string, string> >
            {
                { "n1", paramSymbolInfo },
                { "n2", paramSymbolInfo }
            };

            var hostDataLoader = A.Fake <IHostSpecificDataLoader>();

            A.CallTo(() => hostDataLoader.ReadHostSpecificTemplateData(template)).Returns(new HostSpecificTemplateData(symbolInfo));

            TemplateGroup templateGroup = TemplateGroup.FromTemplateList(
                CliTemplateInfo.FromTemplateInfo(new[] { template }, hostDataLoader))
                                          .Single();

            ITemplateEngineHost        host           = TestHost.GetVirtualHost();
            IEngineEnvironmentSettings settings       = new EngineEnvironmentSettings(host, virtualizeSettings: true);
            TemplatePackageManager     packageManager = A.Fake <TemplatePackageManager>();

            NewCommand             myCommand   = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());
            var                    parseResult = myCommand.Parse($" new foo");
            InstantiateCommandArgs args        = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult));

            try
            {
                _ = new TemplateCommand(myCommand, settings, packageManager, templateGroup, templateGroup.Templates.Single());
            }
            catch (InvalidTemplateParametersException e)
            {
                Assert.Equal(2, e.ParameterErrors.Count);
                Assert.Equal(templateGroup.Templates.Single(), e.Template);

                return(Verifier.Verify(e.Message, _verifySettings.Settings));
            }

            Assert.True(false, "should not land here");
            return(Task.FromResult(1));
        }
Ejemplo n.º 30
0
        // invalid params:
        // [0] name / value - Kind
        // [1] canonical
        // [2] input format
        // [3] param value
        // [4] error message
        internal void CanEvaluateInvalidParameters(string command, MockTemplateInfo[] templates, string?[][] expectedInvalidParams)
        {
            TemplateGroup templateGroup = TemplateGroup.FromTemplateList(
                CliTemplateInfo.FromTemplateInfo(templates, A.Fake <IHostSpecificDataLoader>()))
                                          .Single();

            ITemplateEngineHost        host     = TestHost.GetVirtualHost();
            IEngineEnvironmentSettings settings = new EngineEnvironmentSettings(host, virtualizeSettings: true);
            TemplatePackageManager     templatePackageManager = A.Fake <TemplatePackageManager>();

            NewCommand myCommand        = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());
            var        parseResult      = myCommand.Parse($" new {command}");
            var        args             = InstantiateCommandArgs.FromNewCommandArgs(new NewCommandArgs(myCommand, parseResult));
            var        templateCommands = InstantiateCommand.GetTemplateCommand(args, settings, A.Fake <TemplatePackageManager>(), templateGroup);

            Assert.Empty(templateCommands);

            var templateMatchInfos = InstantiateCommand.CollectTemplateMatchInfo(args, settings, templatePackageManager, templateGroup);
            var invalidOptions     = InstantiateCommand.GetInvalidOptions(templateMatchInfos);

            Assert.Equal(expectedInvalidParams.Length, invalidOptions.Count);

            foreach (var invalidParam in expectedInvalidParams)
            {
                InvalidTemplateOptionResult.Kind expectedErrorKind = invalidParam[0] == "name"
                    ? InvalidTemplateOptionResult.Kind.InvalidName
                    : InvalidTemplateOptionResult.Kind.InvalidValue;

                string?expectedCanonicalName  = invalidParam[1];
                string expectedInputFormat    = invalidParam[2] ?? throw new Exception("Input Format cannot be null");
                string?expectedSpecifiedValue = invalidParam[3];
                string?expectedErrorMessage   = null;
                if (invalidParam.Length == 5)
                {
                    expectedErrorMessage = invalidParam[4];
                }

                var actualParam = invalidOptions.Single(param => param.InputFormat == expectedInputFormat);

                Assert.Equal(expectedErrorKind, actualParam.ErrorKind);
                Assert.Equal(expectedCanonicalName, actualParam.TemplateOption?.TemplateParameter.Name);
                Assert.Equal(expectedInputFormat, actualParam.InputFormat);
                Assert.Equal(expectedSpecifiedValue, actualParam.SpecifiedValue);
                Assert.Equal(expectedErrorMessage, actualParam.ErrorMessage);
            }
        }