protected override void WriteEndMatch(Capture capture) { WriteLine(); if (Ask && ConsoleHelpers.AskToContinue(Options.Indent)) { Ask = false; } }
protected override void WriteEndMatch(CaptureInfo capture) { WriteLine(); if (Ask && ConsoleHelpers.AskToContinue(Options.Indent) == DialogResult.YesToAll) { Ask = false; } }
internal void WriteDiagnostic() { WriteDiagnosticCore(); #if DEBUG if (Logger.ConsoleOut.Verbosity == Verbosity.Diagnostic) { ConsoleHelpers.WaitForKeyPress(); } #endif }
protected override void WriteEndMatch(Capture capture) { int endIndex = capture.Index + capture.Length; int eolIndex = FindEndOfLine(capture); WriteEndLine(endIndex, eolIndex); if (ConsoleHelpers.QuestionIf(Ask, "Continue without asking?", Options.Indent)) { Ask = false; } }
protected override void WriteEndMatch(Capture capture) { int endIndex = capture.Index + capture.Length; int eolIndex = FindEndOfLine(capture); WriteEndLine(endIndex, eolIndex); if (Ask && ConsoleHelpers.AskToContinue(Options.Indent)) { Ask = false; } }
protected virtual bool TryParsePaths(out ImmutableArray <PathInfo> paths) { paths = ImmutableArray <PathInfo> .Empty; if (Path.Any() && !TryEnsureFullPath(Path, PathOrigin.Argument, out paths)) { return(false); } ImmutableArray <PathInfo> pathsFromFile = ImmutableArray <PathInfo> .Empty; if (PathsFrom != null) { if (!FileSystemHelpers.TryReadAllText(PathsFrom, out string?content, ex => Logger.WriteError(ex))) { return(false); } IEnumerable <string> lines = TextHelpers.ReadLines(content).Where(f => !string.IsNullOrWhiteSpace(f)); if (!TryEnsureFullPath(lines, PathOrigin.File, out pathsFromFile)) { return(false); } paths = paths.AddRange(pathsFromFile); } if (Console.IsInputRedirected) { ImmutableArray <PathInfo> pathsFromInput = ConsoleHelpers.ReadRedirectedInputAsLines() .Where(f => !string.IsNullOrEmpty(f)) .Select(f => new PathInfo(f, PathOrigin.RedirectedInput)) .ToImmutableArray(); paths = paths.AddRange(pathsFromInput); } if (paths.IsEmpty) { paths = ImmutableArray.Create(new PathInfo(Environment.CurrentDirectory, PathOrigin.CurrentDirectory)); } return(true); }
protected override void WriteEndReplacement(ICapture capture, string?result) { bool isUserInput = IsInteractive && (capture is RegexCapture || result == null) && (result == null || result.IndexOfAny(_newLineChars) == -1); string replacement = result ?? capture.Value; if (isUserInput) { replacement = ConsoleHelpers.ReadUserInput(replacement, Options.Indent + "Replacement: "); } if (!string.Equals(capture.Value, replacement, StringComparison.Ordinal)) { if (_lazyWriter != null) { if (IsInteractive || ConsoleHelpers.AskToExecute("Replace?", Options.Indent)) { _lazyWriter.Value.Write(Input.AsSpan(_writerIndex, capture.Index - _writerIndex)); _lazyWriter.Value.Write(replacement); _writerIndex = capture.Index + capture.Length; ReplacementCount++; } } else if (!ContinueWithoutAsking && !IsInteractive && ConsoleHelpers.AskToContinue(Options.Indent) == DialogResult.YesToAll) { ContinueWithoutAsking = true; } } SpellcheckState?.ProcessReplacement( Input, capture, replacement, lineNumber: (ValueWriter as LineNumberValueWriter)?.LineNumber, isUserInput: true); }
protected override void WriteEndMatch(CaptureInfo capture) { int endIndex = capture.Index + capture.Length; int eolIndex = FindEndOfLine(capture); WriteEndLine(endIndex, eolIndex); if (Options.ContextAfter > 0) { WriteContextAfter(eolIndex, Input.Length, _lineNumber); } if (Ask && ConsoleHelpers.AskToContinue(Options.Indent) == DialogResult.YesToAll) { Ask = false; } }
protected override void WriteEndReplacement(Match match, string result) { if (_lazyWriter != null) { if (ConsoleHelpers.Question("Replace?", Options.Indent)) { _lazyWriter.Value.Write(Input.AsSpan(_writerIndex, match.Index - _writerIndex)); _lazyWriter.Value.Write(result); _writerIndex = match.Index + match.Length; ReplacementCount++; } } else if (!ContinueWithoutAsking && ConsoleHelpers.Question("Continue without asking?", Options.Indent)) { ContinueWithoutAsking = true; } }
public bool TryParse(EscapeCommandOptions options) { string input = Input; if (input == null) { input = ConsoleHelpers.ReadRedirectedInput(); if (input == null) { Logger.WriteError("Input is missing."); return(false); } } options.Input = input; options.InCharGroup = CharGroup; options.Replacement = Replacement; return(true); }
protected bool AskToExecute(SearchContext context, string question, string indent) { DialogResult result = ConsoleHelpers.Ask((Options.DryRun) ? "Continue?" : question, indent); switch (result) { case DialogResult.Yes: { return(true); } case DialogResult.YesToAll: { Options.Ask = false; return(true); } case DialogResult.No: case DialogResult.None: { return(false); } case DialogResult.NoToAll: case DialogResult.Cancel: { context.TerminationReason = TerminationReason.Canceled; return(false); } default: { throw new InvalidOperationException($"Unknown enum value '{result}'."); } } }
public bool TryParse(RegexCommandOptions options) { var baseOptions = (CommonRegexCommandOptions)options; if (!TryParse(baseOptions)) { return(false); } options = (RegexCommandOptions)baseOptions; string input = Input; if (!string.IsNullOrEmpty(Path)) { if (input != null) { WriteError($"Option '{OptionNames.GetHelpText(OptionNames.Input)}' and argument '{ArgumentMetaNames.Path}' cannot be set both at the same time."); return(false); } try { input = File.ReadAllText(Path); } catch (Exception ex) when(ex is ArgumentException || ex is IOException || ex is UnauthorizedAccessException) { WriteError(ex); return(false); } } else if (string.IsNullOrEmpty(input)) { input = ConsoleHelpers.ReadRedirectedInput(); if (input == null) { WriteError("Input is missing."); return(false); } } if (!TryParseDisplay( values: Display, optionName: OptionNames.Display, contentDisplayStyle: out ContentDisplayStyle? contentDisplayStyle, pathDisplayStyle: out PathDisplayStyle? _, lineDisplayOptions: out LineDisplayOptions lineDisplayOptions, displayParts: out DisplayParts displayParts, fileProperties: out ImmutableArray <FileProperty> fileProperties, indent: out string indent, separator: out string separator, contentDisplayStyleProvider: OptionValueProviders.ContentDisplayStyleProvider_WithoutLineAndUnmatchedLinesAndOmit, pathDisplayStyleProvider: OptionValueProviders.PathDisplayStyleProvider)) { return(false); } if (!TryParseModifyOptions(Modify, OptionNames.Modify, out ModifyOptions modifyOptions, out bool aggregateOnly)) { return(false); } if (modifyOptions.HasAnyFunction && contentDisplayStyle == ContentDisplayStyle.ValueDetail) { contentDisplayStyle = ContentDisplayStyle.Value; } if (aggregateOnly) { ConsoleOut.Verbosity = Orang.Verbosity.Minimal; } options.Format = new OutputDisplayFormat( contentDisplayStyle: contentDisplayStyle ?? ContentDisplayStyle.Value, pathDisplayStyle: PathDisplayStyle.Full, lineOptions: lineDisplayOptions, displayParts: displayParts, fileProperties: fileProperties, indent: indent, separator: separator ?? Environment.NewLine); options.ModifyOptions = modifyOptions; options.Input = input; return(true); }
public static void WriteObsoleteWarning(string message) { WriteWarning(message); ConsoleHelpers.WaitForKeyPress(); }
private void ReplaceMatches( string filePath, Encoding encoding, string input, Match match, string indent, ContentWriterOptions writerOptions, SearchContext context) { SearchTelemetry telemetry = context.Telemetry; ContentWriter contentWriter = null; TextWriter textWriter = null; List <Capture> groups = null; try { groups = ListCache <Capture> .GetInstance(); GetCaptures(match, 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(filePath, false, encoding); } } if (Options.AskMode == AskMode.Value || ShouldLog(Verbosity.Normal)) { MatchOutputInfo outputInfo = Options.CreateOutputInfo(input, match); if (Options.AskMode == AskMode.Value) { Lazy <TextWriter> lazyWriter = (Options.DryRun) ? null : new Lazy <TextWriter>(() => new StreamWriter(filePath, false, encoding)); contentWriter = AskReplacementWriter.Create(Options.ContentDisplayStyle, input, Options.ReplaceOptions, lazyWriter, writerOptions, outputInfo); } else { contentWriter = ContentWriter.CreateReplace(Options.ContentDisplayStyle, input, Options.ReplaceOptions, writerOptions, textWriter, outputInfo); } } else if (Options.DryRun) { contentWriter = new EmptyContentWriter(null, FileWriterOptions); } else { contentWriter = new TextWriterContentWriter(input, 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.Question("Continue without asking?", indent)) { Options.AskMode = AskMode.None; } } else if (ConsoleHelpers.Question("Replace content?", indent)) { File.WriteAllText(filePath, textWriter !.ToString(), 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 bool TryParse(ReplaceCommandOptions options) { if (!TryParseAsEnum( Pipe, OptionNames.Pipe, out PipeMode pipeMode, PipeMode.None, OptionValueProviders.PipeMode)) { return(false); } if (pipeMode == PipeMode.None) { if (Console.IsInputRedirected) { PipeMode = PipeMode.Text; } } else { if (!Console.IsInputRedirected) { WriteError("Redirected/piped input is required " + $"when option '{OptionNames.GetHelpText(OptionNames.Pipe)}' is specified."); return(false); } PipeMode = pipeMode; } if (!TryParseProperties(Ask, Name, options)) { return(false); } var baseOptions = (FileSystemCommandOptions)options; if (!TryParse(baseOptions)) { return(false); } options = (ReplaceCommandOptions)baseOptions; if (!FilterParser.TryParse( Content, OptionNames.Content, OptionValueProviders.PatternOptionsWithoutGroupAndPartAndNegativeProvider, out Filter? contentFilter)) { return(false); } if (!TryParseReplacement(Replacement, out string?replacement, out MatchEvaluator? matchEvaluator)) { return(false); } if (matchEvaluator == null && Evaluator != null) { LogHelpers.WriteObsoleteWarning( $"Option '{OptionNames.GetHelpText(OptionNames.Evaluator)}' is obsolete. " + $"Use option '{OptionNames.GetHelpText(OptionNames.Replacement)}' instead."); if (!DelegateFactory.TryCreateFromAssembly(Evaluator, typeof(string), typeof(Match), out matchEvaluator)) { return(false); } } if (!TryParseReplaceOptions( Modify, OptionNames.Modify, replacement, matchEvaluator, out ReplaceOptions? replaceOptions)) { return(false); } if (!TryParseMaxCount(MaxCount, out int maxMatchingFiles, out int maxMatchesInFile)) { return(false); } string?input = null; if (Input.Any() && !TryParseInput(Input, out input)) { return(false); } if (pipeMode != PipeMode.Paths && Console.IsInputRedirected) { if (input != null) { WriteError("Cannot use both redirected/piped input and " + $"option '{OptionNames.GetHelpText(OptionNames.Input)}'."); return(false); } if (contentFilter == null) { WriteError($"Option '{OptionNames.GetHelpText(OptionNames.Content)}' is required " + "when redirected/piped input is used as a text to be searched."); return(false); } input = ConsoleHelpers.ReadRedirectedInput(); } ContentDisplayStyle contentDisplayStyle; PathDisplayStyle pathDisplayStyle; if (!TryParseDisplay( values: Display, optionName: OptionNames.Display, contentDisplayStyle: out ContentDisplayStyle? contentDisplayStyle2, pathDisplayStyle: out PathDisplayStyle? pathDisplayStyle2, lineDisplayOptions: out LineDisplayOptions lineDisplayOptions, lineContext: out LineContext lineContext, displayParts: out DisplayParts displayParts, fileProperties: out ImmutableArray <FileProperty> fileProperties, indent: out string?indent, separator: out string?separator, noAlign: out bool noAlign, contentDisplayStyleProvider: OptionValueProviders.ContentDisplayStyleProvider_WithoutUnmatchedLines, pathDisplayStyleProvider: OptionValueProviders.PathDisplayStyleProvider)) { return(false); } if (contentDisplayStyle2 != null) { if (options.AskMode == AskMode.Value && contentDisplayStyle2 == ContentDisplayStyle.AllLines) { string helpValue = OptionValueProviders.ContentDisplayStyleProvider .GetValue(nameof(ContentDisplayStyle.AllLines)) .HelpValue; string helpValue2 = OptionValueProviders.AskModeProvider.GetValue(nameof(AskMode.Value)).HelpValue; WriteError($"Option '{OptionNames.GetHelpText(OptionNames.Display)}' cannot have value " + $"'{helpValue}' when option '{OptionNames.GetHelpText(OptionNames.Ask)}' has value '{helpValue2}'."); return(false); } contentDisplayStyle = contentDisplayStyle2.Value; } else if (Input.Any()) { contentDisplayStyle = ContentDisplayStyle.AllLines; } else { contentDisplayStyle = ContentDisplayStyle.Line; } pathDisplayStyle = pathDisplayStyle2 ?? PathDisplayStyle.Full; if (pathDisplayStyle == PathDisplayStyle.Relative && options.Paths.Length > 1 && options.SortOptions != null) { pathDisplayStyle = PathDisplayStyle.Full; } if (!TryParseHighlightOptions( Highlight, out HighlightOptions highlightOptions, defaultValue: HighlightOptions.Replacement, contentDisplayStyle: contentDisplayStyle, provider: OptionValueProviders.ReplaceHighlightOptionsProvider)) { return(false); } options.Format = new OutputDisplayFormat( contentDisplayStyle: contentDisplayStyle, pathDisplayStyle: pathDisplayStyle, lineOptions: lineDisplayOptions, lineContext: lineContext, displayParts: displayParts, fileProperties: fileProperties, indent: indent, separator: separator, alignColumns: !noAlign); options.HighlightOptions = highlightOptions; options.ContentFilter = contentFilter; options.ReplaceOptions = replaceOptions; options.Input = input; options.DryRun = DryRun; options.MaxMatchesInFile = maxMatchesInFile; options.MaxMatchingFiles = maxMatchingFiles; options.MaxTotalMatches = 0; options.Interactive = Interactive; #if DEBUG // --find if (Find) { options.ReplaceOptions = ReplaceOptions.Empty; options.HighlightOptions = HighlightOptions.Match; options.DryRun = true; } #endif return(true); }
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); } } }
protected override void ExecuteResult( FileSystemFinderResult result, SearchContext context, string baseDirectoryPath = null, ColumnWidths columnWidths = null) { string indent = GetPathIndent(baseDirectoryPath); if (!Options.OmitPath) { WritePath(context, result, baseDirectoryPath, indent, columnWidths); } bool deleted = false; if (!Options.DryRun && (!Options.Ask || AskToDelete())) { try { FileSystemHelpers.Delete( result, contentOnly: Options.ContentOnly, includingBom: Options.IncludingBom, filesOnly: Options.FilesOnly, directoriesOnly: Options.DirectoriesOnly); deleted = true; } catch (Exception ex) when(ex is IOException || ex is UnauthorizedAccessException) { WriteFileError(ex, indent: indent); } } if (Options.DryRun || deleted) { if (result.IsDirectory) { context.Telemetry.ProcessedDirectoryCount++; } else { context.Telemetry.ProcessedFileCount++; } } if (result.IsDirectory && deleted) { OnDirectoryChanged(new DirectoryChangedEventArgs(result.Path, null)); } bool AskToDelete() { try { return(ConsoleHelpers.Question( (Options.ContentOnly) ? "Delete content?" : "Delete?", indent)); } catch (OperationCanceledException) { context.TerminationReason = TerminationReason.Canceled; return(false); } } }
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(); } }
public bool TryParse(FindCommandOptions options) { if (!TryParseAsEnum( Pipe, OptionNames.Pipe, out PipeMode pipeMode, PipeMode.None, OptionValueProviders.PipeMode)) { return(false); } if (pipeMode == PipeMode.None) { if (Console.IsInputRedirected) { PipeMode = PipeMode.Text; } } else { if (!Console.IsInputRedirected) { WriteError("Redirected/piped input is required " + $"when option '{OptionNames.GetHelpText(OptionNames.Pipe)}' is specified."); return(false); } PipeMode = pipeMode; } var baseOptions = (CommonFindCommandOptions)options; if (!TryParse(baseOptions)) { return(false); } options = (FindCommandOptions)baseOptions; if (!TryParseProperties(Ask, Name, options)) { return(false); } string?input = null; if (pipeMode != PipeMode.Paths && Console.IsInputRedirected) { if (options.ContentFilter == null) { WriteError($"Option '{OptionNames.GetHelpText(OptionNames.Content)}' is required " + "when redirected/piped input is used as a text to be searched."); return(false); } input = ConsoleHelpers.ReadRedirectedInput(); } EnumerableModifier <string>?modifier = null; #if DEBUG // --modifier if (Modifier.Any() && !TryParseModifier(Modifier, OptionNames.Modifier, out modifier)) { return(false); } #endif if (!TryParseModifyOptions( Modify, OptionNames.Modify, modifier, out ModifyOptions? modifyOptions, out bool aggregateOnly)) { return(false); } OutputDisplayFormat format = options.Format; ContentDisplayStyle contentDisplayStyle = format.ContentDisplayStyle; PathDisplayStyle pathDisplayStyle = format.PathDisplayStyle; if (modifyOptions.HasAnyFunction && contentDisplayStyle == ContentDisplayStyle.ValueDetail) { contentDisplayStyle = ContentDisplayStyle.Value; } options.Input = input; options.ModifyOptions = modifyOptions; options.AggregateOnly = aggregateOnly; options.Split = Split; options.Format = new OutputDisplayFormat( contentDisplayStyle: contentDisplayStyle, pathDisplayStyle: pathDisplayStyle, lineOptions: format.LineOptions, lineContext: format.LineContext, displayParts: format.DisplayParts, fileProperties: format.FileProperties, indent: format.Indent, separator: format.Separator, alignColumns: format.AlignColumns, includeBaseDirectory: format.IncludeBaseDirectory); return(true); }
protected virtual void ExecuteOperation(SearchContext context, string sourcePath, string destinationPath, bool isDirectory, string indent) { 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 (Options.CompareOptions != FileCompareOptions.None && FileSystemHelpers.FileEquals(sourcePath, destinationPath, Options.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 (!Options.OmitPath) { LogHelpers.WritePath(destinationPath, basePath: Target, relativePath: Options.DisplayRelativePath, colors: Colors.Matched_Path, indent: indent, verbosity: Verbosity.Minimal); WriteLine(Verbosity.Minimal); } if (ask && ConflictResolution == ConflictResolution.Ask) { string question; if (directoryExists) { question = (isDirectory) ? "Update directory attributes?" : "Overwrite directory?"; } else { question = "Overwrite file?"; } DialogResult dialogResult = ConsoleHelpers.Ask(question, indent); 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: { context.TerminationReason = TerminationReason.Canceled; return; } default: { throw new InvalidOperationException($"Unknown enum value '{dialogResult}'."); } } } if (isDirectory) { if (directoryExists) { if (!Options.DryRun) { FileSystemHelpers.UpdateAttributes(sourcePath, destinationPath); } } else { if (fileExists && !Options.DryRun) { File.Delete(destinationPath); } if (!Options.DryRun) { Directory.CreateDirectory(destinationPath); } } context.Telemetry.ProcessedDirectoryCount++; } else { if (fileExists) { if (!Options.DryRun) { File.Delete(destinationPath); } } else if (directoryExists) { if (!Options.DryRun) { Directory.Delete(destinationPath, recursive: true); } } else if (!Options.DryRun) { Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)); } if (!Options.DryRun) { ExecuteOperation(sourcePath, destinationPath); } context.Telemetry.ProcessedFileCount++; } }