示例#1
0
#pragma warning restore xUnit1004 // Test methods should not be skipped
        public async Task CacheSkipInvalidTemplatesTest()
        {
            string cacheLocation  = TestUtils.CreateTemporaryFolder();
            string v2FileLocation = SetupInvalidTemplateCache(cacheLocation);

            var environment = A.Fake <IEnvironment>();

            var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(hostIdentifier: this.GetType().Name, virtualize: true, environment: environment);
            var templatePackageManager    = new TemplatePackageManager(engineEnvironmentSettings);

            engineEnvironmentSettings.Components.AddComponent(typeof(ITemplateSearchProviderFactory), new NuGetMetadataSearchProviderFactory());

            NewCommand        myCommand   = (NewCommand)NewCommandFactory.Create("new", _ => engineEnvironmentSettings.Host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());
            var               parseResult = myCommand.Parse($"new search --unknown");
            SearchCommandArgs args        = new SearchCommandArgs((SearchCommand)parseResult.CommandResult.Command, parseResult);

            var templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, default).ConfigureAwait(false);

            TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(engineEnvironmentSettings);
            CliSearchFiltersFactory   factory           = new CliSearchFiltersFactory(templatePackages);

            A.CallTo(() => environment.GetEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE")).Returns(v2FileLocation);
            var searchResults = await searchCoordinator.SearchAsync(
                factory.GetPackFilter(args),
                CliSearchFiltersFactory.GetMatchingTemplatesFilter(args),
                default).ConfigureAwait(false);

            Assert.Equal(1, searchResults.Count);
            Assert.Single(searchResults, result => result.Provider.Factory.DisplayName == "NuGet.org");
            var nugetSearchResults = searchResults.Single(result => result.Provider.Factory.DisplayName == "NuGet.org");

            Assert.Equal(0, nugetSearchResults.SearchHits.Count);
        }
 internal Func <TemplatePackageSearchData, bool> GetPackFilter(SearchCommandArgs commandArgs)
 {
     return(templatePackageSearchData =>
     {
         return AlreadyInstalledFilter(templatePackageSearchData) &&
         commandArgs.AppliedFilters
         .OfType <PackageFilterOptionDefinition>()
         .All(filter => filter.PackageMatchFilter(commandArgs.GetFilterValue(filter))(templatePackageSearchData));
     });
 }
示例#3
0
        public void Search_CanParseColumnsAll(string command)
        {
            ITemplateEngineHost host      = TestHost.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(includeTestTemplates: false));
            NewCommand          myCommand = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());

            var parseResult = myCommand.Parse(command);

            SearchCommandArgs args = new SearchCommandArgs((BaseSearchCommand)parseResult.CommandResult.Command, parseResult);

            Assert.True(args.DisplayAllColumns);
        }
示例#4
0
        public void Search_CanParseFilterOptionWithoutMainCriteria(string command, string expectedFilter)
        {
            FilterOptionDefinition expectedDef = _stringToFilterDefMap[expectedFilter];

            ITemplateEngineHost host      = TestHost.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(includeTestTemplates: false));
            NewCommand          myCommand = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());

            var parseResult        = myCommand.Parse(command);
            SearchCommandArgs args = new SearchCommandArgs((BaseSearchCommand)parseResult.CommandResult.Command, parseResult);

            Assert.Single(args.AppliedFilters);
            Assert.Contains("filter-value", args.GetFilterValue(expectedDef));
            Assert.Null(args.SearchNameCriteria);
        }
示例#5
0
        //[InlineData("new --search --columns author,type", new[] { "author", "type" })]
        public void Search_CanParseColumns(string command, string[] expectedColumns)
        {
            ITemplateEngineHost host      = TestHost.GetVirtualHost(additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(includeTestTemplates: false));
            NewCommand          myCommand = (NewCommand)NewCommandFactory.Create("new", _ => host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());

            var parseResult = myCommand.Parse(command);

            SearchCommandArgs args = new SearchCommandArgs((BaseSearchCommand)parseResult.CommandResult.Command, parseResult);

            Assert.False(args.DisplayAllColumns);
            Assert.NotEmpty(args.ColumnsToDisplay);
            Assert.Equal(expectedColumns.Length, args.ColumnsToDisplay?.Count);
            foreach (var column in expectedColumns)
            {
                Assert.Contains(column, args.ColumnsToDisplay);
            }
        }
示例#6
0
        public async Task CacheSearchTagFilterTest(string commandTemplate, string commandTag, int packMatchCount, int templateMatchCount)
        {
            string cacheLocation  = TestUtils.CreateTemporaryFolder();
            string v1FileLocation = SetupDiscoveryMetadata(cacheLocation, false);
            string v2FileLocation = SetupTemplateCache(cacheLocation, false);

            var environment = A.Fake <IEnvironment>();
            var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(
                virtualize: true,
                environment: environment,
                additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(includeTestTemplates: false));
            var templatePackageManager = new TemplatePackageManager(engineEnvironmentSettings);

            engineEnvironmentSettings.Components.AddComponent(typeof(ITemplateSearchProviderFactory), new NuGetMetadataSearchProviderFactory());

            NewCommand        myCommand   = (NewCommand)NewCommandFactory.Create("new", _ => engineEnvironmentSettings.Host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());
            var               parseResult = myCommand.Parse($"new search {commandTemplate} --tag {commandTag}");
            SearchCommandArgs args        = new SearchCommandArgs((SearchCommand)parseResult.CommandResult.Command, parseResult);

            var templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, default).ConfigureAwait(false);

            TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(engineEnvironmentSettings);
            CliSearchFiltersFactory   factory           = new CliSearchFiltersFactory(templatePackages);

            foreach (var location in new[] { v1FileLocation, v2FileLocation })
            {
                A.CallTo(() => environment.GetEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE")).Returns(location);
                var searchResults = await searchCoordinator.SearchAsync(
                    factory.GetPackFilter(args),
                    CliSearchFiltersFactory.GetMatchingTemplatesFilter(args),
                    default).ConfigureAwait(false);

                Assert.Equal(1, searchResults.Count);
                Assert.Single(searchResults, result => result.Provider.Factory.DisplayName == "NuGet.org");
                var nugetSearchResults = searchResults.Single(result => result.Provider.Factory.DisplayName == "NuGet.org");
                Assert.Equal(packMatchCount, nugetSearchResults.SearchHits.Count);
                if (packMatchCount != 0)
                {
                    Assert.Equal(templateMatchCount, nugetSearchResults.SearchHits.Sum(res => res.MatchedTemplates.Count));
                }
            }
        }
        internal static Func <TemplatePackageSearchData, IReadOnlyList <ITemplateInfo> > GetMatchingTemplatesFilter(SearchCommandArgs commandArgs)
        {
            return((templatePackageSearchData) =>
            {
                InMemoryHostSpecificDataLoader hostDataLoader = new InMemoryHostSpecificDataLoader(templatePackageSearchData);
                IEnumerable <TemplateSearchData> templates = templatePackageSearchData.Templates.Where(template => IsNotHiddenBySearchFile(template));
                IEnumerable <TemplateGroup> templateGroups = TemplateGroup.FromTemplateList(CliTemplateInfo.FromTemplateInfo(templates, hostDataLoader));
                IEnumerable <Func <TemplateGroup, MatchInfo?> > groupFilters = new[]
                {
                    CliFilters.NameTemplateGroupFilter(commandArgs.SearchNameCriteria)
                };

                IEnumerable <Func <ITemplateInfo, MatchInfo?> > templateFilters =
                    commandArgs.AppliedFilters
                    .OfType <TemplateFilterOptionDefinition>()
                    .Select(filter => filter.TemplateMatchFilter(commandArgs.GetFilterValue(filter)));

                IEnumerable <TemplateGroupMatchInfo> matchInformation =
                    templateGroups.Select(
                        group =>
                        TemplateGroupMatchInfo.ApplyFilters(
                            group,
                            groupFilters,
                            templateFilters,
                            //TODO: implement it for template options matching, for now the filter just returns empty collection.
                            CliFilters.EmptyTemplateParameterFilter()));

                return matchInformation
                .Where(group => group.IsGroupAndTemplateInfoAndParametersMatch)
                .SelectMany(group => group.TemplatesWithMatchingParameters)
                .ToList();
            });
        }
示例#8
0
        /// <summary>
        /// Executes searching for the templates in configured remote sources.
        /// Performs validation for the commands, search for the templates in configured remote source, displays the results in table format.
        /// </summary>
        /// <param name="environmentSettings">environment settings.</param>
        /// <param name="templatePackageManager"></param>
        /// <param name="commandArgs">new command data.</param>
        /// <param name="defaultLanguage">default language for the host.</param>
        /// <param name="cancellationToken"></param>
        /// <returns><see cref="NewCommandStatus.Success"/> when the templates were found and displayed;
        /// <see cref="NewCommandStatus.MissingRequiredOption"/> when the command validation fails;
        /// <see cref="NewCommandStatus.NotFound"/> when no templates found based on the filter criteria.
        /// </returns>
        internal static async Task <NewCommandStatus> SearchForTemplateMatchesAsync(
            IEngineEnvironmentSettings environmentSettings,
            TemplatePackageManager templatePackageManager,
            SearchCommandArgs commandArgs,
            string?defaultLanguage,
            CancellationToken cancellationToken)
        {
            if (!ValidateCommandInput(commandArgs))
            {
                return(NewCommandStatus.MissingRequiredOption);
            }

            Reporter.Output.WriteLine(LocalizableStrings.CliTemplateSearchCoordinator_Info_SearchInProgress);
            IReadOnlyList <IManagedTemplatePackage> templatePackages =
                await templatePackageManager.GetManagedTemplatePackagesAsync(force : false, cancellationToken : cancellationToken).ConfigureAwait(false);

            TemplateSearchCoordinator searchCoordinator    = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(environmentSettings);
            CliSearchFiltersFactory   searchFiltersFactory = new CliSearchFiltersFactory(templatePackages);

            IReadOnlyList <SearchResult>?searchResults = await searchCoordinator.SearchAsync(
                searchFiltersFactory.GetPackFilter(commandArgs),
                CliSearchFiltersFactory.GetMatchingTemplatesFilter(commandArgs),
                cancellationToken).ConfigureAwait(false);

            if (!searchResults.Any())
            {
                Reporter.Error.WriteLine(LocalizableStrings.CliTemplateSearchCoordinator_Error_NoSources.Bold().Red());
                return(NewCommandStatus.NotFound);
            }

            foreach (SearchResult result in searchResults)
            {
                if (!result.Success)
                {
                    Reporter.Error.WriteLine(string.Format(LocalizableStrings.CliTemplateSearchCoordinator_Info_MatchesFromSource, result.Provider.Factory.DisplayName));
                    Reporter.Error.WriteLine(string.Format(LocalizableStrings.CliTemplateSearchCoordinator_Error_SearchFailure, result.ErrorMessage).Red().Bold());
                    continue;
                }

                Reporter.Output.WriteLine(string.Format(LocalizableStrings.CliTemplateSearchCoordinator_Info_MatchesFromSource, result.Provider.Factory.DisplayName));
                if (result.SearchHits.Any())
                {
                    DisplayResultsForPack(result.SearchHits, environmentSettings, commandArgs, defaultLanguage);
                }
                else
                {
                    //TODO: implement it for template options matching
                    //IReadOnlyDictionary<string, string?>? appliedParameterMatches = TemplateCommandInput.GetTemplateParametersFromCommand(commandArgs);
                    // No templates found matching the following input parameter(s): {0}.
                    Reporter.Error.WriteLine(
                        string.Format(
                            LocalizableStrings.NoTemplatesMatchingInputParameters,
                            GetInputParametersString(commandArgs))
                        .Bold().Red());
                }
            }
            Reporter.Output.WriteLine();
            if (searchResults.Where(r => r.Success).SelectMany(r => r.SearchHits).Any())
            {
                string packageIdToShow = EvaluatePackageToShow(searchResults);
                Reporter.Output.WriteLine(LocalizableStrings.CliTemplateSearchCoordinator_Info_InstallHelp);
                Reporter.Output.WriteCommand(
                    Example
                    .For <NewCommand>(commandArgs.ParseResult)
                    .WithSubcommand <InstallCommand>()
                    .WithArgument(InstallCommand.NameArgument));
                Reporter.Output.WriteLine(LocalizableStrings.Generic_ExampleHeader);
                Reporter.Output.WriteCommand(
                    Example
                    .For <NewCommand>(commandArgs.ParseResult)
                    .WithSubcommand <InstallCommand>()
                    .WithArgument(InstallCommand.NameArgument, packageIdToShow));
                return(NewCommandStatus.Success);
            }
            return(NewCommandStatus.NotFound);
        }