private static IEnumerable <string> GetCompileFullPaths(XElement compile, string includeOrRemovePattern, string csProjRoot) { var matcher = new Matcher(StringComparison.OrdinalIgnoreCase); matcher.AddIncludePatterns(includeOrRemovePattern.Split(';')); var exclude = compile?.Attribute("Exclude")?.Value; if (exclude != null) { matcher.AddExcludePatterns(exclude.Split(';')); } foreach (var path in matcher.GetResultsInFullPath(csProjRoot)) { yield return(path); } }
Matcher GetMatcher() { var matcher = new Matcher(StringComparison.CurrentCultureIgnoreCase); if (Includes != null && Includes.Length != 0) { matcher.AddIncludePatterns(Includes); } else { matcher.AddInclude("**/*"); } if (Excludes != null && Excludes.Length != 0) { matcher.AddExcludePatterns(Excludes); } return(matcher); }
internal IEnumerable <FilePath> GetFiles() { if (!_includes.Any()) { return(new FilePath[0]); } var matcher = new Matcher(_caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); matcher.AddIncludePatterns(_includes); if (_excludes.Any()) { matcher.AddExcludePatterns(_excludes); } var result = matcher.Execute(_directoryInfoWrapper); return(result.HasMatches ? result.Files.Select(x => new FilePath(Path.Combine(_directoryInfoWrapper.FullName, x.Path))) : new FilePath[0]); }
public int OnExecute(IConsole console) { try { var enc = Util.GetEncodingFromName(FileNameEncoding, Encoding.UTF8); var matcher = new Matcher(StringComparison.OrdinalIgnoreCase); if (Includes != null && Includes.Length != 0) { matcher.AddIncludePatterns(Includes); } else { matcher.AddInclude("**/*"); } if (Excludes != null && Excludes.Length != 0) { matcher.AddExcludePatterns(Excludes); } var outdir = string.IsNullOrEmpty(OutputDirectory) ? Directory.GetCurrentDirectory() : OutputDirectory; using (var istm = TarUtil.GetCompressionStream(Util.OpenInputStream(InputPath), CompressionFormat, TarStreamDirection.Input)) using (var tstm = new TarInputStream(istm, enc)) { while (true) { var entry = tstm.GetNextEntry(); if (entry == null) { break; } var m = matcher.Match(entry.Name); if (!m.HasMatches) { continue; } if (ListOnly) { console.WriteLine($"{entry.Name}"); continue; } var entryKey = Util.ReplaceRegexString(entry.Name, ReplaceFrom, ReplaceTo); if (entry.IsDirectory) { var destdir = Path.Combine(outdir, entryKey); if (!Directory.Exists(destdir)) { Directory.CreateDirectory(destdir); } } else { var destfi = new FileInfo(Path.Combine(outdir, entryKey)); console.Error.WriteLine($"extracting {entry.Name} to {destfi.FullName}"); if (!destfi.Directory.Exists) { destfi.Directory.Create(); } using (var deststm = File.Create(destfi.FullName)) { if (entry.Size != 0) { var buf = new byte[4096]; while (true) { var bytesread = tstm.Read(buf, 0, buf.Length); if (bytesread == 0) { break; } deststm.Write(buf, 0, bytesread); } } } destfi.LastWriteTime = entry.ModTime; } } } return(0); } catch (Exception e) { console.Error.WriteLine($"failed to decompressing tar archive:{e}"); return(1); } }
private static Task <int> ExecuteAsync(CancellationToken cancellationToken) { var includePattern = _includesOption.Values; var excludePattern = _excludesOption.Values; // When no include pattern is specified, we decide to include all recursive ('**') if (!includePattern.Any()) { includePattern.Add("**"); } var matcher = new Matcher(StringComparison.OrdinalIgnoreCase); matcher.AddIncludePatterns(includePattern); matcher.AddExcludePatterns(excludePattern); var stopwatch = Stopwatch.StartNew(); var items = matcher.Execute(_pathArgument.Value); int totalItems = items.Count; TimeSpan getItemsElapsed = stopwatch.Elapsed; void ExecuteWithProgressBar(Action <string> itemAction, Action <DirectoryInfo, Func <bool> > rootPathAction) { var options = new ProgressBarOptions { ProgressCharacter = '─', CollapseWhenFinished = false }; using var progressBar = new ProgressBar(totalItems, "Start remove items...", options); var i = 0; foreach (string path in items.OrderByDescending(x => x.Length)) { string shrinkedPath = PathFormatter.ShrinkPath(path, Console.BufferWidth - 44); progressBar.Message = $"Remove item {i + 1} of {totalItems}: {shrinkedPath}"; itemAction(path); progressBar.Tick($"Removed item {i + 1} of {totalItems}: {shrinkedPath}"); ++i; } var rootPathDirectoryInfo = new DirectoryInfo(matcher.RootPath); var rootPathCheck = new Func <bool>(() => rootPathDirectoryInfo.Exists && rootPathDirectoryInfo.GetFileSystemInfos("*", SearchOption.AllDirectories).Length == 0); if ((_skipPathOption.HasValue() || !rootPathCheck()) && (_skipPathOption.HasValue() || !_tryRunOption.HasValue())) { return; } using ChildProgressBar childProgressBar = progressBar.Spawn(1, "child actions", options); { string shrinkedPath = PathFormatter.ShrinkPath(matcher.RootPath, Console.BufferWidth - 44); childProgressBar.Message = $"Remove empty root path: {shrinkedPath}"; rootPathAction(rootPathDirectoryInfo, rootPathCheck); childProgressBar.Tick($"Removed empty root path: {shrinkedPath}"); } } void ExecuteQuiet(Action <string> itemAction, Action <DirectoryInfo, Func <bool> > rootPathAction) { foreach (string path in items.OrderByDescending(x => x.Length)) { itemAction(path); } var rootPathDirectoryInfo = new DirectoryInfo(matcher.RootPath); var rootPathCheck = new Func <bool>(() => rootPathDirectoryInfo.Exists && rootPathDirectoryInfo.GetFileSystemInfos("*", SearchOption.AllDirectories).Length == 0); if (!_skipPathOption.HasValue() && rootPathCheck() || !_skipPathOption.HasValue() && _tryRunOption.HasValue()) { rootPathAction(rootPathDirectoryInfo, rootPathCheck); } } if (totalItems > 0) { var retryPolicy = Policy.Handle <Exception>().OrResult <bool>(r => r).WaitAndRetry(25, c => TimeSpan.FromMilliseconds(250)); var itemAction = new Action <string>(path => { if (_tryRunOption.HasValue()) { Thread.Sleep(1); } else { if (PathExtensions.IsDirectory(path)) { var di = new DirectoryInfo(path); retryPolicy.Execute(() => { di.Refresh(); if (di.Exists) { di.Attributes = FileAttributes.Normal; di.Delete(true); } di.Refresh(); return(di.Exists); }); } else { var fi = new FileInfo(path); retryPolicy.Execute(() => { fi.Refresh(); if (fi.Exists) { fi.Attributes = FileAttributes.Normal; fi.Delete(); } fi.Refresh(); return(fi.Exists); }); } } }); var rootPathAction = new Action <DirectoryInfo, Func <bool> >((di, check) => { if (_tryRunOption.HasValue()) { Thread.Sleep(1); } else { retryPolicy.Execute(() => { di.Refresh(); if (check()) { di.Attributes = FileAttributes.Normal; di.Delete(); } di.Refresh(); return(check()); }); } }); if (!_listItemsOption.HasValue() && !_quietOption.HasValue()) { ExecuteWithProgressBar(itemAction, rootPathAction); } else if (_listItemsOption.HasValue() && !_quietOption.HasValue()) { foreach (string path in items.OrderByDescending(x => x.Length)) { Console.WriteLine(path); } if (!_skipPathOption.HasValue()) { Console.WriteLine(matcher.RootPath); } } else if (!_listItemsOption.HasValue() && _quietOption.HasValue()) { ExecuteQuiet(itemAction, rootPathAction); } } stopwatch.Stop(); TimeSpan completeElapsed = stopwatch.Elapsed; if (_listItemsOption.HasValue() || _quietOption.HasValue()) { return(Task.FromResult(Ok)); } PrintSummary(totalItems, completeElapsed, getItemsElapsed); return(Task.FromResult(Ok)); }
public void Execute() { if (Shared.Instance.Debug) { using (Color(ConsoleColor.DarkGray)) { Console.WriteLine("Patterns:"); foreach (var pattern in Patterns) { Console.WriteLine(pattern); } } } // Console.WriteLine("Replace to " + ReplaceTo); foreach (var pattern in Patterns) { var pattern2 = ImprovePattern(pattern); _regexes.Add(new Regex(pattern2, RegexOptions.Compiled | RegexOptions.Multiline)); } if (string.IsNullOrWhiteSpace(Dir)) { throw new Exception("Directory not defined"); } if (!Directory.Exists(Dir)) { throw new Exception("Directory does not exists"); } if (Files.Count == 0) { if (Recursive) { Files.Add("**/*"); } else { // STDIN Files.Add("-"); } } var groupedContext = GroupMatchesByContext ? new Dictionary<ColoredMessage, CaptureResult>() : null; if (Files.Count == 1 && (File.Exists(Files[0]) || Files[0] == "-")) { // single Process(file: Files[0], printFileName: false); } else { var di = new DirectoryInfo(Dir); var includes = Files .Select(x => new { IsFullPath = Path.GetFullPath(x) == x, Pattern = x, }) .Select(x => x.IsFullPath ? x.Pattern.Substring(di.FullName.Length + 1) : (Recursive ? (x.Pattern.StartsWith("**/") ? x.Pattern : "**/" + x.Pattern) : x.Pattern) ) ; var excludes = FilesSelectorOptions.ExcludeGlobs .Select(x => new { IsFullPath = Path.GetFullPath(x) == x, Pattern = x, }) .Select(x => x.IsFullPath ? x.Pattern.Substring(di.FullName.Length + 1) : x.Pattern ) ; var matcher = new Matcher(); matcher.AddIncludePatterns(includes); matcher.AddExcludePatterns(excludes); var res = matcher.Execute(new DirectoryInfoWrapper(di)); foreach (var filePatternMatch in res.Files.OrderBy(x => x.Path)) { var file = filePatternMatch.Path; if (Path.AltDirectorySeparatorChar != Path.DirectorySeparatorChar) { file = file.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); } Process(file, printFileName: true, groupedContext); } } if (groupedContext != null) { foreach (var kvp in groupedContext.OrderBy(x=>x.Value.FileNames.First())) { Console.WriteLine(); if (kvp.Value.FileNames.Count > 1) { using (Color(ConsoleColor.Magenta)) { Console.WriteLine($"{kvp.Value.FileNames.Count} files:"); } } foreach (var file in kvp.Value.FileNames) { PrintFileName(file); } kvp.Key.ToConsole(); } /* if (groupedContext.Count > 1) { // using (Color(ConsoleColor.Gray)) { Console.WriteLine(); Console.WriteLine($"{groupedContext.Count} groups of similar context"); } } */ } }