void AddToOutputIfNonMinFileDoesNotExist(FileMatch fileMatch) { var sourceFileExists = filenames.Contains(fileMatch.BasicName + fileMatch.FileExtension); if (!sourceFileExists) { outputFile.Add(fileMatch.OriginalFile); } }
void AddToOutputIfDebugFileDoesNotExist(FileMatch fileMatch) { var debugFileExists = filenames.Contains(fileMatch.BasicName + ".debug" + fileMatch.FileExtension) || filenames.Contains(fileMatch.BasicName + "-debug" + fileMatch.FileExtension); if (!debugFileExists) { outputFile.Add(fileMatch.OriginalFile); } }
public static IEnumerable<string> FilterFiles(string directory, bool recursive, FileMatch isMatch) { SearchOption option = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; foreach (string filename in Directory.EnumerateFiles(directory, "*", option)) { if (isMatch(filename)) yield return filename; } }
void AddFileToOutput(FileMatch fileMatch) { if (fileMatch.IsMinContentMode) { AddToOutputIfNonMinFileDoesNotExist(fileMatch); } else if (fileMatch.IsDebugContentMode) { outputFile.Add(fileMatch.OriginalFile); } else { AddToOutputIfDebugFileDoesNotExist(fileMatch); } }
private bool AskToOverwrite(FileMatch fileMatch, string newPath) { DialogResult result = DialogProvider !.GetResult(new OperationProgress(fileMatch, newPath, OperationKind)); switch (result) { case DialogResult.Yes: { return(true); } case DialogResult.YesToAll: { DialogProvider = null; return(true); } case DialogResult.No: case DialogResult.None: { return(false); } case DialogResult.NoToAll: { ConflictResolution = ConflictResolution.Skip; return(false); } case DialogResult.Cancel: { throw new OperationCanceledException(); } default: { throw new InvalidOperationException($"Unknown enum value '{result}'."); } } }
static void Main(string[] args) { var readDirectory = ConfigurationManager.AppSettings["Directory"]; var writeDirectory = ConfigurationManager.AppSettings["WriteDirectory"]; var personSourceFile = FileMatch.GetFullFileName(readDirectory, ConfigurationManager.AppSettings["GESOURCEFILEPERSON"]); var personWorksheetName = ConfigurationManager.AppSettings["PersonWorksheetName"]; var entitySourceFile = FileMatch.GetFullFileName(readDirectory, ConfigurationManager.AppSettings["GESOURCEFILEENTITY"]); var entityWorksheetName = ConfigurationManager.AppSettings["EntityWorksheetName"]; var headings = ConfigurationManager.AppSettings["Headings"]; DependencyResolution.ConstructContainer(); var reader = DependencyResolution.GetGEFileReader(); var personResult = reader.GetData(readDirectory + personSourceFile, personWorksheetName, 4); var entityResult = reader.GetData(readDirectory + entitySourceFile, entityWorksheetName, 2); var serializer = DependencyResolution.GetFICOSerializer(); var serializedResult = serializer.Serialize(personResult, entityResult); var LibFin_Customer = ConfigurationManager.AppSettings["LibFin_Customer"]; var LibFin_Ext = ConfigurationManager.AppSettings["LibFin_Ext"]; var LibFinRelationship = ConfigurationManager.AppSettings["LibFinRelationship"]; var UnUsed = ConfigurationManager.AppSettings["UnUsed"]; var writer = DependencyResolution.GetFICOFileWriter(writeDirectory + LibFin_Customer, writeDirectory + LibFin_Ext, headings); writer.Write(serializedResult.OutputAndExtension, ""); var relationWriter = DependencyResolution.GetGERelationshipWriter(writeDirectory + LibFinRelationship, UnUsed, "INSTITUTE|CUSTNO|REL_CUSTNO|REL_TYPE|REL_SHARE|REL_FLAG1|REL_FLAG2|REL_FLAG3|REL_COMMENT|PROCESSFLAG"); relationWriter.Write(serializedResult.RelationshipList, "|"); }
private void ExecuteOperation( FileMatch fileMatch, SearchContext context, string? baseDirectoryPath, string indent) { string sourcePath = fileMatch.Path; string destinationPath; if (fileMatch.IsDirectory || (baseDirectoryPath != null && !Options.Flat)) { Debug.Assert(sourcePath.StartsWith(baseDirectoryPath!, FileSystemHelpers.Comparison)); string relativePath = sourcePath.Substring(baseDirectoryPath!.Length + 1); destinationPath = Path.Combine(Target, relativePath); } else { string fileName = Path.GetFileName(sourcePath); destinationPath = Path.Combine(Target, fileName); } if (IgnoredPaths?.Contains(sourcePath) == true) return; try { ExecuteOperation(context, sourcePath, destinationPath, fileMatch.IsDirectory, indent); } catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) { WriteError(ex, sourcePath, indent: indent); } }
private ReplaceResult ReplaceFileIfMatchingFiles(FileMatch replacement, DirectoryInfo contentDirectory) { var replacedFiles = new List <string>(); ImmutableArray <FileInfo> matchingFiles = _fileMatcher.Matches(replacement, contentDirectory); if (matchingFiles.Length > 1) { _logger.Error("Could not find a single matching file to transform, found multiple: {V}", string.Join(", ", matchingFiles.Select(file => $"'{file.FullName}'"))); return(new ReplaceResult(false)); } if (matchingFiles.Any()) { FileInfo targetFileInfo = matchingFiles.Single(); ExitCode replaceExitCode = ReplaceFile( targetFileInfo, replacement.ActionFile, contentDirectory, replacement.ActionFileRootDirectory); if (!replaceExitCode.IsSuccess) { return(new ReplaceResult(false)); } replacedFiles.Add(targetFileInfo.Name); } else { _logger.Debug("Could not find any matching file for file replacement, looked for '{TargetName}'", replacement.TargetName); } return(new ReplaceResult(true, replacedFiles)); }
protected override void ExecuteMatchCore( FileMatch fileMatch, SearchContext context, string?baseDirectoryPath, ColumnWidths?columnWidths) { string indent = GetPathIndent(baseDirectoryPath); List <ReplaceItem> replaceItems = ReplaceHelpers.GetReplaceItems(fileMatch.NameMatch !, Options.ReplaceOptions, NameFilter !.Predicate, context.CancellationToken); string path = fileMatch.Path; string newPath = ReplaceHelpers.GetNewPath(fileMatch, replaceItems); bool changed = !string.Equals(path, newPath, StringComparison.Ordinal); if (!Options.OmitPath && changed) { LogHelpers.WritePath( fileMatch, replaceItems, baseDirectoryPath, relativePath: Options.DisplayRelativePath, colors: Colors.Matched_Path, matchColors: (Options.HighlightMatch) ? Colors.Match : default,
protected override void ExecuteMatch( FileMatch fileMatch, string directoryPath) { bool deleted = false; try { if (!DryRun) { FileSystemHelpers.Delete( fileMatch, contentOnly: DeleteOptions.ContentOnly, includingBom: DeleteOptions.IncludingBom, filesOnly: DeleteOptions.FilesOnly, directoriesOnly: DeleteOptions.DirectoriesOnly); deleted = true; } Report(fileMatch); Telemetry.IncrementProcessedCount(fileMatch.IsDirectory); } catch (Exception ex) when(ex is IOException || ex is UnauthorizedAccessException) { Report(fileMatch, ex); } if (fileMatch.IsDirectory && deleted) { OnDirectoryChanged(new DirectoryChangedEventArgs(fileMatch.Path, null)); } }
protected virtual void ExecuteOperation(FileMatch fileMatch, string destinationPath, bool isDirectory) { string sourcePath = fileMatch.Path; bool fileExists = File.Exists(destinationPath); bool directoryExists = !fileExists && Directory.Exists(destinationPath); bool ask = false; if (isDirectory) { if (fileExists) { ask = true; } else if (directoryExists) { if (File.GetAttributes(sourcePath) == File.GetAttributes(destinationPath)) { return; } ask = true; } } else if (fileExists) { if (CopyOptions.CompareOptions != FileCompareOptions.None && FileSystemHelpers.FileEquals(sourcePath, destinationPath, CopyOptions.CompareOptions)) { return; } ask = true; } else if (directoryExists) { ask = true; } if (ask && ConflictResolution == ConflictResolution.Skip) { return; } if (!isDirectory && fileExists && ConflictResolution == ConflictResolution.Suffix) { destinationPath = FileSystemHelpers.CreateNewFilePath(destinationPath); } if (ask && ConflictResolution == ConflictResolution.Ask) { DialogResult dialogResult = DialogProvider !.GetResult(new OperationProgress(fileMatch, destinationPath, OperationKind)); switch (dialogResult) { case DialogResult.Yes: { break; } case DialogResult.YesToAll: { ConflictResolution = ConflictResolution.Overwrite; break; } case DialogResult.No: case DialogResult.None: { return; } case DialogResult.NoToAll: { ConflictResolution = ConflictResolution.Skip; return; } case DialogResult.Cancel: { throw new OperationCanceledException(); } default: { throw new InvalidOperationException($"Unknown enum value '{dialogResult}'."); } } } Report(fileMatch, destinationPath); if (isDirectory) { if (directoryExists) { if (!DryRun) { FileSystemHelpers.UpdateAttributes(sourcePath, destinationPath); } } else { if (fileExists && !DryRun) { File.Delete(destinationPath); } if (!DryRun) { Directory.CreateDirectory(destinationPath); } } Telemetry.ProcessedDirectoryCount++; } else { if (fileExists) { if (!DryRun) { File.Delete(destinationPath); } } else if (directoryExists) { if (!DryRun) { Directory.Delete(destinationPath, recursive: true); } } else if (!DryRun) { Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)); } if (!DryRun) { ExecuteOperation(sourcePath, destinationPath); } Telemetry.ProcessedFileCount++; } }
protected void Report(FileMatch fileMatch, string?newPath, Exception?exception = null) { Progress?.Report(fileMatch, newPath, OperationKind, exception); }
protected void Report(FileMatch fileMatch, Exception?exception = null) { Report(fileMatch, newPath: null, exception); }
protected abstract void ExecuteMatch(FileMatch fileMatch, string directoryPath);
protected virtual void WritePath(SearchContext context, FileMatch fileMatch, string?baseDirectoryPath, string indent, ColumnWidths?columnWidths) { WritePath(context, fileMatch, baseDirectoryPath, indent, columnWidths, Colors.Match); WriteLine(Verbosity.Minimal); }
protected override void ExecuteMatchCore(FileMatch fileMatch, SearchContext context, string?baseDirectoryPath = null, ColumnWidths?columnWidths = null) { throw new NotSupportedException(); }
private void ExecuteMatchWithContentCore( IEnumerator <ICapture> groups, int count, MaxReason maxReason, FileMatch fileMatch, SearchContext context, ContentWriterOptions writerOptions, string?baseDirectoryPath = null, ColumnWidths?columnWidths = null) { string indent = GetPathIndent(baseDirectoryPath); if (!Options.OmitPath) { WritePath(context, fileMatch, baseDirectoryPath, indent, columnWidths, includeNewline: false); WriteFilePathEnd(count, maxReason, Options.IncludeCount); } SearchTelemetry telemetry = context.Telemetry; ContentWriter?contentWriter = null; TextWriter? textWriter = null; try { int fileMatchCount = 0; int fileReplacementCount = 0; if (!Options.DryRun) { if (Options.AskMode == AskMode.File) { textWriter = new StringWriter(); } else if (Options.AskMode != AskMode.Value && !Options.Interactive) { textWriter = (CanUseStreamWriter) ? new StreamWriter(fileMatch.Path, false, fileMatch.Encoding) : new StringWriter(); } } if (Options.AskMode == AskMode.Value || Options.Interactive || (!Options.OmitContent && ShouldLog(Verbosity.Normal))) { MatchOutputInfo?outputInfo = Options.CreateOutputInfo( fileMatch.ContentText, fileMatch.ContentMatch !, ContentFilter !); if (Options.AskMode == AskMode.Value || Options.Interactive) { Lazy <TextWriter>?lazyWriter = null; if (!Options.DryRun) { lazyWriter = new Lazy <TextWriter>(() => { textWriter = new StringWriter(); return(textWriter); }); } contentWriter = AskReplacementWriter.Create( Options.ContentDisplayStyle, fileMatch.ContentText, Options.Replacer, lazyWriter, writerOptions, outputInfo, isInteractive: Options.Interactive, SpellcheckState); } else { contentWriter = CreateReplacementWriter( Options.ContentDisplayStyle, fileMatch.ContentText, Options.Replacer, writerOptions, textWriter, outputInfo); } } else if (Options.DryRun && CanUseEmptyWriter) { contentWriter = new EmptyContentWriter(FileWriterOptions); } else { contentWriter = new TextWriterContentWriter( fileMatch.ContentText, Options.Replacer, writerOptions, textWriter, SpellcheckState); } WriteMatches(contentWriter, groups, context); fileMatchCount = contentWriter.MatchCount; fileReplacementCount = (contentWriter is IReportReplacement reportReplacement) ? reportReplacement.ReplacementCount : fileMatchCount; telemetry.MatchCount += fileMatchCount; if (contentWriter.MatchingLineCount >= 0) { if (telemetry.MatchingLineCount == -1) { telemetry.MatchingLineCount = 0; } telemetry.MatchingLineCount += contentWriter.MatchingLineCount; } if (Options.AskMode == AskMode.Value || Options.Interactive) { if (textWriter != null) { File.WriteAllText(fileMatch.Path, textWriter.ToString(), fileMatch.Encoding); if (Options.AskMode == AskMode.Value && ((AskReplacementWriter)contentWriter).ContinueWithoutAsking) { Options.AskMode = AskMode.None; } } } else if (Options.AskMode == AskMode.File) { if (context.TerminationReason == TerminationReason.Canceled) { fileReplacementCount = 0; } else { try { if (Options.DryRun) { if (ConsoleHelpers.AskToContinue(indent) == DialogResult.YesToAll) { Options.AskMode = AskMode.None; } } else if (fileReplacementCount > 0 && ConsoleHelpers.AskToExecute("Replace content?", indent)) { File.WriteAllText(fileMatch.Path, textWriter !.ToString(), fileMatch.Encoding); } else { fileReplacementCount = 0; } } catch (OperationCanceledException) { context.TerminationReason = TerminationReason.Canceled; fileReplacementCount = 0; } } } else if (fileReplacementCount > 0 && textWriter is StringWriter) { File.WriteAllText(fileMatch.Path, textWriter.ToString(), fileMatch.Encoding); } telemetry.ProcessedMatchCount += fileReplacementCount; if (fileReplacementCount > 0) { telemetry.ProcessedFileCount++; } } catch (Exception ex) when(ex is IOException || ex is UnauthorizedAccessException) { WriteFileError(ex, indent: indent); } finally { contentWriter?.Dispose(); } }
protected override void ExecuteMatchWithContentCore( FileMatch fileMatch, SearchContext context, ContentWriterOptions writerOptions, string?baseDirectoryPath = null, ColumnWidths?columnWidths = null) { string indent = GetPathIndent(baseDirectoryPath); if (!Options.OmitPath) { WritePath(context, fileMatch, baseDirectoryPath, indent, columnWidths); } SearchTelemetry telemetry = context.Telemetry; ContentWriter? contentWriter = null; TextWriter? textWriter = null; List <Capture>?groups = null; try { groups = ListCache <Capture> .GetInstance(); GetCaptures(fileMatch.ContentMatch !, writerOptions.GroupNumber, context, isPathWritten: !Options.OmitPath, predicate: Options.ContentFilter !.Predicate, captures: groups); int fileMatchCount = 0; int fileReplacementCount = 0; if (!Options.DryRun) { if (Options.AskMode == AskMode.File) { textWriter = new StringWriter(); } else if (Options.AskMode == AskMode.None) { textWriter = new StreamWriter(fileMatch.Path, false, fileMatch.Encoding); } } if (Options.AskMode == AskMode.Value || ShouldLog(Verbosity.Normal)) { MatchOutputInfo?outputInfo = Options.CreateOutputInfo(fileMatch.ContentText, fileMatch.ContentMatch !, ContentFilter !); if (Options.AskMode == AskMode.Value) { Lazy <TextWriter>?lazyWriter = (Options.DryRun) ? null : new Lazy <TextWriter>(() => new StreamWriter(fileMatch.Path, false, fileMatch.Encoding)); contentWriter = AskReplacementWriter.Create(Options.ContentDisplayStyle, fileMatch.ContentText, Options.ReplaceOptions, lazyWriter, writerOptions, outputInfo); } else { contentWriter = ContentWriter.CreateReplace(Options.ContentDisplayStyle, fileMatch.ContentText, Options.ReplaceOptions, writerOptions, textWriter, outputInfo); } } else if (Options.DryRun) { contentWriter = new EmptyContentWriter(FileWriterOptions); } else { contentWriter = new TextWriterContentWriter(fileMatch.ContentText, Options.ReplaceOptions, textWriter !, writerOptions); } WriteMatches(contentWriter, groups, context); fileMatchCount = contentWriter.MatchCount; fileReplacementCount = (contentWriter is AskReplacementWriter askReplacementWriter) ? askReplacementWriter.ReplacementCount : fileMatchCount; telemetry.MatchCount += fileMatchCount; if (contentWriter.MatchingLineCount >= 0) { if (telemetry.MatchingLineCount == -1) { telemetry.MatchingLineCount = 0; } telemetry.MatchingLineCount += contentWriter.MatchingLineCount; } if (Options.AskMode == AskMode.File) { if (context.TerminationReason == TerminationReason.Canceled) { fileReplacementCount = 0; } else { try { if (Options.DryRun) { if (ConsoleHelpers.AskToContinue(indent)) { Options.AskMode = AskMode.None; } } else if (ConsoleHelpers.AskToExecute("Replace content?", indent)) { File.WriteAllText(fileMatch.Path, textWriter !.ToString(), fileMatch.Encoding); } else { fileReplacementCount = 0; } } catch (OperationCanceledException) { context.TerminationReason = TerminationReason.Canceled; fileReplacementCount = 0; } } } else if (Options.AskMode == AskMode.Value) { if (((AskReplacementWriter)contentWriter).ContinueWithoutAsking) { Options.AskMode = AskMode.None; } } telemetry.ProcessedMatchCount += fileReplacementCount; if (fileReplacementCount > 0) { telemetry.ProcessedFileCount++; } } catch (Exception ex) when(ex is IOException || ex is UnauthorizedAccessException) { WriteFileError(ex, indent: indent); } finally { contentWriter?.Dispose(); if (groups != null) { ListCache <Capture> .Free(groups); } } }
public FileMatchResult(FileMatch match, FileComparisonResult comparisonResult) { this.Match = match; this.ComparisonResult = comparisonResult; }
public StorageSection(FileMatch fileMatch, string?baseDirectoryPath, int count) { FileMatch = fileMatch; BaseDirectoryPath = baseDirectoryPath; Count = count; }
public static void Report(this IProgress <OperationProgress> progress, FileMatch fileMatch, string?newPath, OperationKind kind, Exception?exception = null) { progress.Report(new OperationProgress(fileMatch, newPath, kind, exception)); }
protected abstract void ExecuteMatchCore( FileMatch fileMatch, SearchContext context, string?baseDirectoryPath, ColumnWidths?columnWidths);
protected override void ExecuteMatch( FileMatch fileMatch, string directoryPath) { List <ReplaceItem> replaceItems = ReplaceHelpers.GetReplaceItems( fileMatch.NameMatch !, RenameOptions, NameFilter?.Predicate, CancellationToken); string path = fileMatch.Path; string newPath = ReplaceHelpers.GetNewPath(fileMatch, replaceItems); ListCache <ReplaceItem> .Free(replaceItems); if (string.Equals(path, newPath, StringComparison.Ordinal)) { return; } if (FileSystemHelpers.ContainsInvalidFileNameChars(newPath, FileSystemHelpers.GetFileNameIndex(path))) { Report(fileMatch, newPath, new IOException("New file name contains invalid characters.")); return; } if (File.Exists(newPath)) { if (ConflictResolution == ConflictResolution.Skip) { return; } else if (ConflictResolution == ConflictResolution.Suffix) { newPath = FileSystemHelpers.CreateNewFilePath(newPath); } else if (ConflictResolution == ConflictResolution.Ask) { if (!AskToOverwrite(fileMatch, newPath)) { return; } } } var renamed = false; try { if (!DryRun) { if (fileMatch.IsDirectory) { Directory.Move(path, newPath); } else { File.Move(path, newPath); } renamed = true; } Report(fileMatch, newPath); Telemetry.IncrementProcessedCount(fileMatch.IsDirectory); } catch (Exception ex) when(ex is IOException || ex is UnauthorizedAccessException) { Report(fileMatch, newPath, ex); } if (fileMatch.IsDirectory && renamed) { OnDirectoryChanged(new DirectoryChangedEventArgs(path, newPath)); } }
public static IEnumerable <string> FilterFiles(string directory, bool recursive, FileMatch isMatch) { SearchOption option = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; foreach (string filename in Directory.EnumerateFiles(directory, "*", option)) { if (isMatch(filename)) { yield return(filename); } } }
protected sealed override void WritePath(SearchContext context, FileMatch fileMatch, string?baseDirectoryPath, string indent, ColumnWidths?columnWidths) { }