示例#1
1
        public void Main(string[] args)
        {
            var matcher = new Matcher();
            matcher.AddInclude(@"**\*.cs");
            matcher.AddExclude(OutputFileName);

            var inputFiles = new List<string>();
            var latestChange = DateTime.MinValue;
            foreach (var f in matcher.GetResultsInFullPath(_projectDir))
            {
                inputFiles.Add(f);
                var change = File.GetLastWriteTimeUtc(f);
                if (change > latestChange)
                    latestChange = change;
            }

            var outputFile = Path.Combine(_projectDir, OutputFileName);
            if (!File.Exists(outputFile) || latestChange > File.GetLastWriteTimeUtc(outputFile))
            {
                Console.WriteLine("Rewriting async methods in " + _projectDir);
                var asyncCode = new Rewriter().RewriteAndMerge(inputFiles.ToArray());
                File.WriteAllText(outputFile, asyncCode);
            }
            else
            {
                Console.WriteLine("Skipping async rewriting, generated code up to date");
            }
        }
示例#2
1
		public virtual PatternMatchingResult Execute(DirectoryInfoBase directoryInfo)
		{
			var files = new List<FilePatternMatch>();
			foreach (var includePattern in _includePatterns)
			{
				var matcher = new Matcher();
				matcher.AddInclude(includePattern);
				matcher.AddExcludePatterns(_excludePatterns);
				var result = matcher.Execute(directoryInfo);
				if (result.Files.Any())
				{
					files.AddRange(result.Files);
				}
			}
			return new PatternMatchingResult(files);
		}
示例#3
0
        public static IEnumerable <(string Path, string Stem)> GetFileList(string basedir, string[] includes, string[] excludes, bool ignoreCase)
        {
            var matcher = new Microsoft.Extensions.FileSystemGlobbing.Matcher(ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture);

            if (excludes != null)
            {
                foreach (var exclude in excludes)
                {
                    matcher.AddExclude(exclude);
                }
            }
            if (includes != null && includes.Length != 0)
            {
                foreach (var include in includes)
                {
                    matcher.AddInclude(include);
                }
            }
            else
            {
                matcher.AddInclude("**/*");
            }
            var di        = new DirectoryInfo(basedir);
            var diwrapper = new DirectoryInfoWrapper(di);
            var result    = matcher.Execute(diwrapper);

            if (!result.HasMatches)
            {
                return(Array.Empty <(string, string)>());
            }
            else
            {
                return(result.Files.Select(x => (x.Path, x.Stem)));
            }
        }
示例#4
0
文件: Listener.cs 项目: int19h/PTVS
        private void AddPattern(FileSystemWatcher pattern)
        {
            // Add to our matcher
            _matcher.AddInclude(pattern.GlobPattern);

            // Ignoring kind for now. Just tell about everything.
        }
示例#5
0
文件: Listener.cs 项目: bschnurr/PTVS
        private void AddPattern(VisualStudio.LanguageServer.Protocol.FileSystemWatcher pattern)
        {
            // Add to our matcher
            _matcher.AddInclude(pattern.GlobPattern);

            // Ignoring kind for now. Just tell about everything.
        }
示例#6
0
 /// <summary>
 /// Adds multiple patterns to include in <see cref="Matcher" />. See <seealso cref="Matcher.AddInclude(string)" />
 /// </summary>
 /// <param name="matcher">The matcher to which the include patterns are added</param>
 /// <param name="includePatternsGroups">A list of globbing patterns</param>
 public static void AddIncludePatterns(this Matcher matcher, params IEnumerable <string>[] includePatternsGroups)
 {
     foreach (IEnumerable <string> group in includePatternsGroups)
     {
         foreach (string pattern in group)
         {
             matcher.AddInclude(pattern);
         }
     }
 }
        /// <summary>
        /// 获取配置
        /// </summary>
        /// <returns></returns>
        public IConfigurationRoot GetConfigurationRoot()
        {
            if (_configuration == null)
            {
                if (!Directory.Exists(_configRootFullPath))
                {
                    Directory.CreateDirectory(_configRootFullPath);
                }
                var configurationBuilder = new ConfigurationBuilder()
                                           .SetBasePath(_configRootFullPath);

                foreach (var jsonConfig in _configOptions.Json)
                {
                    var jsonFileMatcher = new Microsoft.Extensions.FileSystemGlobbing.Matcher();
                    var jsonFiles       = jsonFileMatcher
                                          .AddInclude(jsonConfig.Include)
                                          .AddExclude(jsonConfig.Exclude)
                                          .GetResultsInFullPath(_configRootFullPath);

                    foreach (var jsonFile in jsonFiles)
                    {
                        configurationBuilder.AddJsonFile(jsonFile, jsonConfig.Optional, jsonConfig.ReloadOnChange);
                    }
                }

                if (_configOptions.Consul?.Enable ?? false)
                {
                    if (_configOptions.Consul.Name == null)
                    {
                        throw new ArgumentException("Name is required when reading from consul");
                    }
                    _consulCancellationTokenSource = new CancellationTokenSource();
                    configurationBuilder.AddConsul($"{_configOptions.Consul.Name}.{_env.EnvironmentName}", _consulCancellationTokenSource.Token);
                }

                _configuration = configurationBuilder.Build();
            }

            return(_configuration);
        }
示例#8
0
        public bool Build()
        {
            var projectFilesFinder = new Matcher();

            // Resolve all the project names
            var projectFilesToBuild = new List<string>();
            foreach (var pattern in _buildOptions.ProjectPatterns)
            {
                if (pattern.Contains("*"))
                {
                    // Requires globbing
                    projectFilesFinder.AddInclude(NormalizeGlobbingPattern(pattern));
                }
                else
                {
                    projectFilesToBuild.Add(pattern);
                }
            }

            var rootDirectory = Directory.GetCurrentDirectory();
            var patternSearchFolder = new DirectoryInfoWrapper(new DirectoryInfo(rootDirectory));
            var globbingProjects = projectFilesFinder.Execute(patternSearchFolder).Files.Select(file =>
                Path.Combine(rootDirectory, file.Path));
            projectFilesToBuild.AddRange(globbingProjects);

            var sw = Stopwatch.StartNew();

            var globalSucess = true;
            foreach (var project in projectFilesToBuild)
            {
                var buildSuccess = BuildInternal(project);
                globalSucess &= buildSuccess;
            }

            _buildOptions.Reports.Information.WriteLine($"Total build time elapsed: { sw.Elapsed }");
            _buildOptions.Reports.Information.WriteLine($"Total projects built: { projectFilesToBuild.Count }");

            return globalSucess;
        }
示例#9
0
文件: Globber.cs 项目: ibebbs/Wyam
        // Initially based on code from Reliak.FileSystemGlobbingExtensions (https://github.com/reliak/Reliak.FileSystemGlobbingExtensions)
        public static IEnumerable<IFile> GetFiles(IDirectory directory, IEnumerable<string> patterns)
        {
            Matcher matcher = new Matcher(StringComparison.Ordinal);

            // Expand braces
            IEnumerable<string> expandedPatterns = patterns
                .SelectMany(ExpandBraces)
                .Select(f => f.Replace("\\{", "{").Replace("\\}", "}")); // Unescape braces

            // Add the patterns, any that start with ! are exclusions
            foreach (string expandedPattern in expandedPatterns)
            {
                bool isExclude = expandedPattern[0] == '!';
                string finalPattern = isExclude ? expandedPattern.Substring(1) : expandedPattern;
                finalPattern = finalPattern
                    .Replace("\\!", "!") // Unescape negation
                    .Replace("\\", "/"); // Normalize slashes

                // No support for absolute paths
                if (System.IO.Path.IsPathRooted(finalPattern))
                {
                    throw new ArgumentException($"Rooted globbing patterns are not supported ({expandedPattern})", nameof(patterns));
                }

                // Add exclude or include pattern to matcher
                if (isExclude)
                {
                    matcher.AddExclude(finalPattern);
                }
                else
                {
                    matcher.AddInclude(finalPattern);
                }
            }

            DirectoryInfoBase directoryInfo = new DirectoryInfo(directory);
            PatternMatchingResult result = matcher.Execute(directoryInfo);
            return result.Files.Select(match => directory.GetFile(match.Path));
        }
示例#10
0
        /// <summary>
        /// Enumerate all the PowerShell (ps1, psm1, psd1) files in the workspace in a recursive manner.
        /// </summary>
        /// <returns>An enumerator over the PowerShell files found in the workspace.</returns>
        public IEnumerable <string> EnumeratePSFiles(
            string[] excludeGlobs,
            string[] includeGlobs,
            int maxDepth,
            bool ignoreReparsePoints
            )
        {
            if (WorkspacePath == null || !Directory.Exists(WorkspacePath))
            {
                yield break;
            }

            var matcher = new Microsoft.Extensions.FileSystemGlobbing.Matcher();

            foreach (string pattern in includeGlobs)
            {
                matcher.AddInclude(pattern);
            }
            foreach (string pattern in excludeGlobs)
            {
                matcher.AddExclude(pattern);
            }

            var fsFactory = new WorkspaceFileSystemWrapperFactory(
                WorkspacePath,
                maxDepth,
                Utils.IsNetCore ? s_psFileExtensionsCoreFramework : s_psFileExtensionsFullFramework,
                ignoreReparsePoints,
                logger
                );
            var fileMatchResult = matcher.Execute(fsFactory.RootDirectory);

            foreach (FilePatternMatch item in fileMatchResult.Files)
            {
                yield return(Path.Combine(WorkspacePath, item.Path));
            }
        }
        public void Discover(ShapeTableBuilder builder)
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Start discovering shapes");
            }

            var harvesterInfos = _harvesters
                .Select(harvester => new { harvester, subPaths = harvester.SubPaths() })
                .ToList();

            var activeFeatures = _featureManager.GetEnabledFeaturesAsync().Result.ToList();
            var activeExtensions = Once(activeFeatures).ToList();

            var matcher = new Matcher();
            foreach (var extension in _shapeTemplateViewEngines.SelectMany(x => x.TemplateFileExtensions))
            {
                matcher.AddInclude(string.Format("*.{0}", extension));
            }

            var hits = activeExtensions.Select(extensionDescriptor =>
            {
                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation("Start discovering candidate views filenames");
                }

                var pathContexts = harvesterInfos.SelectMany(harvesterInfo => harvesterInfo.subPaths.Select(subPath =>
                {
                    var basePath = _fileSystem.Combine(extensionDescriptor.Location, extensionDescriptor.Id);
                    var virtualPath = _fileSystem.Combine(basePath, subPath);
                    var files = _fileSystem.ListFiles(virtualPath, matcher).ToReadOnlyCollection();

                    return new { harvesterInfo.harvester, basePath, subPath, virtualPath, files };
                })).ToList();

                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation("Done discovering candidate views filenames");
                }
                var fileContexts = pathContexts.SelectMany(pathContext => _shapeTemplateViewEngines.SelectMany(ve =>
                {
                    return pathContext.files.Select(
                        file => new
                        {
                            fileName = Path.GetFileNameWithoutExtension(file.Name),
                            fileVirtualPath = "~/" + _fileSystem.Combine(pathContext.virtualPath, file.Name),
                            pathContext
                        });
                }));

                var shapeContexts = fileContexts.SelectMany(fileContext =>
                {
                    var harvestShapeInfo = new HarvestShapeInfo
                    {
                        SubPath = fileContext.pathContext.subPath,
                        FileName = fileContext.fileName,
                        TemplateVirtualPath = fileContext.fileVirtualPath
                    };
                    var harvestShapeHits = fileContext.pathContext.harvester.HarvestShape(harvestShapeInfo);
                    return harvestShapeHits.Select(harvestShapeHit => new { harvestShapeInfo, harvestShapeHit, fileContext });
                });

                return shapeContexts.Select(shapeContext => new { extensionDescriptor, shapeContext }).ToList();
            }).SelectMany(hits2 => hits2);


            foreach (var iter in hits)
            {
                // templates are always associated with the namesake feature of module or theme
                var hit = iter;
                var featureDescriptors = iter.extensionDescriptor.Features.Where(fd => fd.Id == hit.extensionDescriptor.Id);
                foreach (var featureDescriptor in featureDescriptors)
                {
                    if (_logger.IsEnabled(LogLevel.Debug))
                    {
                        _logger.LogDebug("Binding {0} as shape [{1}] for feature {2}",
                        hit.shapeContext.harvestShapeInfo.TemplateVirtualPath,
                        iter.shapeContext.harvestShapeHit.ShapeType,
                        featureDescriptor.Id);
                    }
                    builder.Describe(iter.shapeContext.harvestShapeHit.ShapeType)
                        .From(new Feature { Descriptor = featureDescriptor })
                        .BoundAs(
                            hit.shapeContext.harvestShapeInfo.TemplateVirtualPath,
                            shapeDescriptor => displayContext => RenderAsync(shapeDescriptor, displayContext, hit.shapeContext.harvestShapeInfo, hit.shapeContext.harvestShapeHit));
                }
            }

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Done discovering shapes");
            }
        }
示例#12
0
 public string CompressDirectory(string path) {
     Matcher matcher = new Matcher(StringComparison.OrdinalIgnoreCase);
     matcher.AddInclude("*.*");
     return CompressDirectory(path, matcher, new Progress<string>((p) => { }), CancellationToken.None);
 }
示例#13
-1
        private async Task<IEnumerable<RecipeDescriptor>> HarvestRecipesAsync(ExtensionDescriptor extension)
        {
            var recipeLocation = _fileSystem.Combine(extension.Location, extension.Id, "Recipes");

            var recipeOptions = _recipeOptions.Value;

            List<RecipeDescriptor> recipeDescriptors = new List<RecipeDescriptor>();

            foreach(var recipeFileExtension in recipeOptions.RecipeFileExtensions)
            {
                var fileMatcher = new Matcher(System.StringComparison.OrdinalIgnoreCase);
                fileMatcher.AddInclude(recipeFileExtension.Key);

                var recipeFiles = _fileSystem.ListFiles(recipeLocation, fileMatcher);

                recipeDescriptors.AddRange(await recipeFiles.InvokeAsync(recipeFile => {
                    var recipeParser = _recipeParsers.First(x => x.GetType() == recipeFileExtension.Value);
                    using (var stream = recipeFile.CreateReadStream()) {
                        var recipe = recipeParser.ParseRecipe(stream);
                        recipe.Location = recipeFile.PhysicalPath.Replace(_fileSystem.RootPath, "").TrimStart(System.IO.Path.DirectorySeparatorChar);
                        return Task.FromResult(recipe);
                    }
                }, Logger));
            }

            return recipeDescriptors;
        }