Exemplo n.º 1
0
        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);
                }
            }
        }
Exemplo n.º 2
0
 protected override void ExecuteMatchCore(FileMatch fileMatch, SearchContext context, string?baseDirectoryPath = null, ColumnWidths?columnWidths = null)
 {
     throw new NotSupportedException();
 }
Exemplo n.º 3
0
        private void WriteMatches(
            string input,
            Match match,
            ContentWriterOptions writerOptions,
            SearchContext context)
        {
            SearchTelemetry telemetry = context.Telemetry;

            ContentWriter  contentWriter = null;
            List <Capture> captures      = null;

            try
            {
                captures = ListCache <Capture> .GetInstance();

                GetCaptures(match, writerOptions.GroupNumber, context, isPathWritten: !Options.OmitPath, predicate: ContentFilter.Predicate, captures: captures);

                bool hasAnyFunction = Options.ModifyOptions.HasAnyFunction;

                if (hasAnyFunction ||
                    Options.AskMode == AskMode.Value ||
                    ShouldLog(Verbosity.Normal))
                {
                    if (hasAnyFunction)
                    {
                        if (_fileValues == null)
                        {
                            _fileValues = new List <string>();
                        }
                        else
                        {
                            _fileValues.Clear();
                        }

                        if (_fileStorage == null)
                        {
                            _fileStorage = new ListResultStorage(_fileValues);
                        }
                    }

                    contentWriter = ContentWriter.CreateFind(
                        contentDisplayStyle: Options.ContentDisplayStyle,
                        input: input,
                        options: writerOptions,
                        storage: (hasAnyFunction) ? _fileStorage : _storage,
                        outputInfo: Options.CreateOutputInfo(input, match),
                        writer: (hasAnyFunction) ? null : ContentTextWriter.Default,
                        ask: _askMode == AskMode.Value);
                }
                else
                {
                    contentWriter = new EmptyContentWriter(null, writerOptions);
                }

                WriteMatches(contentWriter, captures, context);

                if (hasAnyFunction)
                {
                    ConsoleColors colors         = (Options.HighlightMatch) ? Colors.Match : default;
                    ConsoleColors boundaryColors = (Options.HighlightBoundary) ? Colors.MatchBoundary : default;

                    var valueWriter = new ValueWriter(ContentTextWriter.Default, writerOptions.Indent, includeEndingIndent: false);

                    foreach (string value in _fileValues.Modify(Options.ModifyOptions))
                    {
                        Write(writerOptions.Indent, Verbosity.Normal);
                        valueWriter.Write(value, Symbols, colors, boundaryColors);
                        WriteLine(Verbosity.Normal);

                        _storage?.Add(value);
                        telemetry.MatchCount++;
                    }

                    _storageIndexes?.Add(_storage !.Count);
                }
                else
                {
                    telemetry.MatchCount += contentWriter.MatchCount;

                    if (contentWriter.MatchingLineCount >= 0)
                    {
                        if (telemetry.MatchingLineCount == -1)
                        {
                            telemetry.MatchingLineCount = 0;
                        }

                        telemetry.MatchingLineCount += contentWriter.MatchingLineCount;
                    }
                }

                if (_askMode == AskMode.Value)
                {
                    if (contentWriter is AskValueContentWriter askValueContentWriter)
                    {
                        if (!askValueContentWriter.Ask)
                        {
                            _askMode = AskMode.None;
                        }
                    }
                    else if (contentWriter is AskLineContentWriter askLineContentWriter)
                    {
                        if (!askLineContentWriter.Ask)
                        {
                            _askMode = AskMode.None;
                        }
                    }
                }
            }
            finally
            {
                contentWriter?.Dispose();

                if (captures != null)
                {
                    ListCache <Capture> .Free(captures);
                }
            }
        }
Exemplo n.º 4
0
        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);
                }
            }
        }
Exemplo n.º 5
0
 protected abstract void ExecuteDirectory(string directoryPath, SearchContext context);
Exemplo n.º 6
0
 protected abstract void ExecuteMatchCore(
     FileMatch fileMatch,
     SearchContext context,
     string?baseDirectoryPath,
     ColumnWidths?columnWidths);
Exemplo n.º 7
0
        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++;
            }
        }
Exemplo n.º 8
0
 protected sealed override void ExecuteResult(SearchResult result, SearchContext context, ColumnWidths?columnWidths)
 {
     ExecuteMatchCore(result.FileMatch, context, result.BaseDirectoryPath, columnWidths);
 }
Exemplo n.º 9
0
 protected abstract void ExecuteResult(FileSystemFinderResult result, SearchContext context, string baseDirectoryPath, ColumnWidths columnWidths);
Exemplo n.º 10
0
        protected virtual void WritePath(SearchContext context, FileSystemFinderResult result, string baseDirectoryPath, string indent, ColumnWidths columnWidths)
        {
            WritePath(context, result, baseDirectoryPath, indent, columnWidths, Colors.Match);

            WriteLine(Verbosity.Minimal);
        }
Exemplo n.º 11
0
        protected virtual DialogResult? ExecuteOperation(
            SearchContext context,
            string sourcePath,
            string destinationPath,
            bool isDirectory,
            string indent)
        {
            bool fileExists = File.Exists(destinationPath);
            bool directoryExists = !fileExists && Directory.Exists(destinationPath);
            var ask = false;

            if (isDirectory)
            {
                if (fileExists)
                {
                    ask = true;
                }
                else if (directoryExists)
                {
                    if (Options.StructureOnly
                        && File.GetAttributes(sourcePath) == File.GetAttributes(destinationPath))
                    {
                        return null;
                    }

                    ask = true;
                }
            }
            else if (fileExists)
            {
                if (Options.CompareOptions != FileCompareOptions.None
                    && FileSystemHelpers.FileEquals(sourcePath, destinationPath, Options.CompareOptions))
                {
                    return null;
                }

                ask = true;
            }
            else if (directoryExists)
            {
                ask = true;
            }

            if (ask
                && ConflictResolution == ConflictResolution.Skip)
            {
                return null;
            }

            if (ConflictResolution == ConflictResolution.Suffix
                && ((isDirectory && directoryExists)
                    || (!isDirectory && fileExists)))
            {
                destinationPath = FileSystemHelpers.CreateNewFilePath(destinationPath);
            }

            if (!Options.OmitPath)
            {
                LogHelpers.WritePath(
                    destinationPath,
                    basePath: Target,
                    relativePath: Options.DisplayRelativePath,
                    colors: default,
Exemplo n.º 12
0
        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();
            }
        }
Exemplo n.º 13
0
        protected override DialogResult?ExecuteOperation(
            SearchContext context,
            string sourcePath,
            string destinationPath,
            bool isDirectory,
            string indent)
        {
            if (_ignoredPaths?.Contains(sourcePath) == true)
            {
                return(null);
            }

            string?renamePath = null;

            ExecuteOperation();

            _destinationPaths?.Add(renamePath ?? destinationPath);

            return(null);

            void ExecuteOperation()
            {
                bool fileExists                 = File.Exists(destinationPath);
                bool directoryExists            = !fileExists && Directory.Exists(destinationPath);
                bool?preferLeft                 = null;
                FileCompareOptions?diffProperty = null;

                if (isDirectory)
                {
                    if (directoryExists)
                    {
                        Debug.Assert(!_isSecondToFirst);

                        if (_isSecondToFirst)
                        {
                            return;
                        }

                        if (FileSystemHelpers.AttributeEquals(sourcePath, destinationPath, Options.NoCompareAttributes))
                        {
                            return;
                        }
                    }
                }
                else if (fileExists)
                {
                    if (_isSecondToFirst)
                    {
                        return;
                    }

                    if ((Options.CompareOptions & FileCompareOptions.ModifiedTime) != 0)
                    {
                        int diff = FileSystemHelpers.CompareLastWriteTimeUtc(
                            sourcePath,
                            destinationPath,
                            Options.AllowedTimeDiff);

                        if (diff > 0)
                        {
                            preferLeft = true;
                        }
                        else if (diff < 0)
                        {
                            preferLeft = false;
                        }
                    }
                }

                if (preferLeft == null)
                {
                    if (!_isSecondToFirst &&
                        !isDirectory)
                    {
                        if (fileExists)
                        {
                            if (Options.CompareOptions != FileCompareOptions.None)
                            {
                                diffProperty = FileSystemHelpers.CompareFiles(
                                    sourcePath,
                                    destinationPath,
                                    Options.CompareOptions,
                                    Options.NoCompareAttributes,
                                    Options.AllowedTimeDiff);

                                if (diffProperty == FileCompareOptions.None)
                                {
                                    return;
                                }
                            }
                        }
                        else if (Options.DetectRename &&
                                 (Options.CompareOptions & FileCompareOptions.Content) != 0)
                        {
                            if (_directoryData == null)
                            {
                                _directoryData = new DirectoryData();
                                _directoryData.Load(Path.GetDirectoryName(destinationPath) !);
                            }
                            else if (!FileSystemHelpers.IsParentDirectory(_directoryData.Path !, destinationPath))
                            {
                                _directoryData.Load(Path.GetDirectoryName(destinationPath) !);
                            }

                            if (_directoryData.Files.Count > 0)
                            {
                                renamePath = _directoryData.FindRenamedFile(sourcePath);
                            }
                        }
                    }

                    if (ConflictResolution == SyncConflictResolution.Ask)
                    {
                        if (base.CanEndProgress)
                        {
                            EndProgress(context);
                        }

                        if (renamePath != null)
                        {
                            WritePathPrefix(sourcePath, "FIL", default, indent);
Exemplo n.º 14
0
        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);
                }
            }
        }
Exemplo n.º 15
0
 protected sealed override void WritePath(SearchContext context, FileMatch fileMatch, string?baseDirectoryPath, string indent, ColumnWidths?columnWidths)
 {
 }
Exemplo n.º 16
0
        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);
        }
Exemplo n.º 17
0
        private void ExecuteInput(SearchContext context, string input)
        {
            int    count         = 0;
            var    maxReason     = MaxReason.None;
            Filter contentFilter = ContentFilter !;
            Match? match         = contentFilter.Match(input);

            if (match != null)
            {
                ContentWriter? contentWriter = null;
                List <Capture>?groups        = null;

                try
                {
                    groups = ListCache <Capture> .GetInstance();

                    maxReason = GetCaptures(
                        match,
                        FileWriterOptions.GroupNumber,
                        context,
                        isPathDisplayed: false,
                        predicate: contentFilter.Predicate,
                        captures: groups);

                    if (ShouldLog(Verbosity.Normal))
                    {
                        MatchOutputInfo?outputInfo = Options.CreateOutputInfo(input, match, contentFilter);

                        contentWriter = ContentWriter.CreateReplace(
                            Options.ContentDisplayStyle,
                            input,
                            Options.ReplaceOptions,
                            FileWriterOptions,
                            outputInfo: outputInfo);
                    }
                    else
                    {
                        contentWriter = new EmptyContentWriter(FileWriterOptions);
                    }

                    WriteMatches(contentWriter, groups, context);
                    count = contentWriter.MatchCount;
                }
                finally
                {
                    contentWriter?.Dispose();

                    if (groups != null)
                    {
                        ListCache <Capture> .Free(groups);
                    }
                }
            }

            if (ShouldLog(Verbosity.Detailed) ||
                Options.IncludeSummary)
            {
                Verbosity verbosity = (Options.IncludeSummary) ? Verbosity.Minimal : Verbosity.Detailed;

                WriteLine(verbosity);
                WriteCount("Replacements", count, Colors.Message_OK, verbosity);
                WriteIf(maxReason == MaxReason.CountExceedsMax, "+", Colors.Message_OK, verbosity);
                WriteLine(verbosity);
            }
        }
Exemplo n.º 18
0
        private void ExecuteResults(SearchContext context)
        {
            IEnumerable <SearchResult> results = context.Results !;
            SortOptions?sortOptions            = Options.SortOptions;

            if (sortOptions?.Descriptors.Any() == true)
            {
                PathDisplayStyle pathDisplayStyle = Options.PathDisplayStyle;

                if (pathDisplayStyle == PathDisplayStyle.Match &&
                    NameFilter == null)
                {
                    pathDisplayStyle = PathDisplayStyle.Full;
                }

                results = SortHelpers.SortResults(context.Results !, sortOptions, pathDisplayStyle);

                if (sortOptions.MaxCount > 0)
                {
                    results = results.Take(sortOptions.MaxCount);
                }
            }

            ImmutableArray <FileProperty> fileProperties = Options.Format.FileProperties;
            ColumnWidths?columnWidths = null;

            if (fileProperties.Any() &&
                Options.Format.AlignColumns)
            {
                List <SearchResult> resultList = results.ToList();

                int maxNameWidth = resultList.Max(f => f.Path.Length);
                int maxSizeWidth = 0;

                if (fileProperties.Contains(FileProperty.Size))
                {
                    long maxSize = 0;

                    foreach (SearchResult result in resultList)
                    {
                        long size = result.GetSize();

                        if (result.IsDirectory)
                        {
                            if (context.DirectorySizeMap == null)
                            {
                                context.DirectorySizeMap = new Dictionary <string, long>();
                            }

                            context.DirectorySizeMap[result.Path] = size;
                        }

                        if (size > maxSize)
                        {
                            maxSize = size;
                        }
                    }

                    maxSizeWidth = maxSize.ToString("n0").Length;
                }

                columnWidths = new ColumnWidths(maxNameWidth, maxSizeWidth);

                results = resultList;
            }

            int i = 0;

            try
            {
                foreach (SearchResult result in results)
                {
                    ExecuteResult(result, context, columnWidths);
                    i++;

                    if (context.TerminationReason == TerminationReason.Canceled)
                    {
                        break;
                    }

                    context.CancellationToken.ThrowIfCancellationRequested();
                }
            }
            catch (OperationCanceledException)
            {
                context.TerminationReason = TerminationReason.Canceled;
            }

            if (context.TerminationReason == TerminationReason.Canceled ||
                context.CancellationToken.IsCancellationRequested)
            {
                OperationCanceled();
            }

            if (Options.Format.FileProperties.Contains(FileProperty.Size) &&
                context.Telemetry.FilesTotalSize == 0)
            {
                foreach (SearchResult result in results.Take(i))
                {
                    context.Telemetry.FilesTotalSize += result.GetSize();
                }
            }
        }
Exemplo n.º 19
0
 protected abstract void ProcessResult(FileSystemFinderResult result, SearchContext context, string baseDirectoryPath = null);
Exemplo n.º 20
0
 protected abstract void ExecuteFile(string filePath, SearchContext context);
Exemplo n.º 21
0
 protected override void ExecuteResult(SearchResult result, SearchContext context, ColumnWidths columnWidths)
 {
     ExecuteResult(result.Result, context, result.BaseDirectoryPath, columnWidths);
 }
Exemplo n.º 22
0
 protected abstract void ExecuteResult(SearchResult result, SearchContext context, ColumnWidths?columnWidths);
Exemplo n.º 23
0
        protected override void ExecuteResult(FileSystemFinderResult result, SearchContext context, string baseDirectoryPath = null, ColumnWidths columnWidths = null)
        {
            base.ExecuteResult(result, context, baseDirectoryPath, columnWidths);

            ExecuteOperation(result, context, baseDirectoryPath, GetPathIndent(baseDirectoryPath));
        }