コード例 #1
0
ファイル: ParseHelpers.cs プロジェクト: fjsnogueira/Orang
        public static bool TryParseRegex(
            string pattern,
            RegexOptions regexOptions,
            TimeSpan matchTimeout,
            string patternOptionName,
            out Regex regex)
        {
            regex = null;

            if (pattern == null)
            {
                return(false);
            }

            try
            {
                regex = new Regex(pattern, regexOptions, matchTimeout);
                return(true);
            }
            catch (ArgumentException ex)
            {
                WriteError(ex, $"Could not parse '{OptionNames.GetHelpText(patternOptionName)}' value: {ex.Message}");
                return(false);
            }
        }
コード例 #2
0
        internal static bool TryParseProperties(string ask, IEnumerable <string> name, CommonFindCommandOptions options)
        {
            if (!TryParseAsEnum(ask, OptionNames.Ask, out AskMode askMode, defaultValue: AskMode.None, OptionValueProviders.AskModeProvider))
            {
                return(false);
            }

            if (askMode == AskMode.Value &&
                ConsoleOut.Verbosity < Verbosity.Normal)
            {
                WriteError($"Option '{OptionNames.GetHelpText(OptionNames.Ask)}' cannot have value '{OptionValueProviders.AskModeProvider.GetValue(nameof(AskMode.Value)).HelpValue}' when '{OptionNames.GetHelpText(OptionNames.Verbosity)}' is set to '{OptionValueProviders.VerbosityProvider.GetValue(ConsoleOut.Verbosity.ToString()).HelpValue}'.");
                return(false);
            }

            if (!FilterParser.TryParse(name, OptionNames.Name, OptionValueProviders.PatternOptionsProvider, out Filter? nameFilter, out FileNamePart namePart, allowNull: true))
            {
                return(false);
            }

            options.AskMode    = askMode;
            options.NameFilter = nameFilter;
            options.NamePart   = namePart;

            return(true);
        }
コード例 #3
0
        private static bool TryParseCount(string value, string optionName, out int count, string?value2 = null)
        {
            if (int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out count))
            {
                return(true);
            }

            WriteError($"Option '{OptionNames.GetHelpText(optionName)}' has invalid value '{value2 ?? value}'.");
            return(false);
        }
コード例 #4
0
        protected override bool TryParsePaths(out ImmutableArray <PathInfo> paths)
        {
            if (Path.Any() &&
                Input != null)
            {
                WriteError($"Option '{OptionNames.GetHelpText(OptionNames.Input)}' and argument '{ArgumentMetaNames.Path}' cannot be set both at the same time.");
                return(false);
            }

            return(base.TryParsePaths(out paths));
        }
コード例 #5
0
ファイル: ParseHelpers.cs プロジェクト: fjsnogueira/Orang
        public static bool TryParseFileProperties(
            IEnumerable <string> values,
            string optionName,
            out FilePropertyFilter filter)
        {
            filter = null;
            Func <long, bool>     sizePredicate         = null;
            Func <DateTime, bool> creationTimePredicate = null;
            Func <DateTime, bool> modifiedTimePredicate = null;

            foreach (string value in values)
            {
                try
                {
                    Expression expression = Expression.Parse(value);

                    if (OptionValues.FileProperty_Size.IsKeyOrShortKey(expression.Identifier))
                    {
                        if (expression.Kind == ExpressionKind.DecrementExpression)
                        {
                            WriteError($"Option '{OptionNames.GetHelpText(optionName)}' has invalid expression '{value}'.");
                            return(false);
                        }

                        sizePredicate = PredicateHelpers.GetLongPredicate(expression);
                    }
                    else if (OptionValues.FileProperty_CreationTime.IsKeyOrShortKey(expression.Identifier))
                    {
                        creationTimePredicate = PredicateHelpers.GetDateTimePredicate(expression);
                    }
                    else if (OptionValues.FileProperty_ModifiedTime.IsKeyOrShortKey(expression.Identifier))
                    {
                        modifiedTimePredicate = PredicateHelpers.GetDateTimePredicate(expression);
                    }
                    else
                    {
                        WriteParseError(value, optionName, OptionValueProviders.FilePropertiesProvider);
                        return(false);
                    }
                }
                catch (ArgumentException)
                {
                    WriteError($"Option '{OptionNames.GetHelpText(optionName)}' has invalid expression '{value}'.");
                    return(false);
                }
            }

            filter = new FilePropertyFilter(
                sizePredicate: sizePredicate,
                creationTimePredicate: creationTimePredicate,
                modifiedTimePredicate: modifiedTimePredicate);

            return(true);
        }
コード例 #6
0
        public bool TryParse(ReplaceCommandOptions options)
        {
            var baseOptions = (CommonReplaceCommandOptions)options;

            if (!TryParse(baseOptions))
            {
                return(false);
            }

            options = (ReplaceCommandOptions)baseOptions;

            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);
            }

            options.Replacer = replaceOptions;
#if DEBUG // --find
            if (Find)
            {
                options.Replacer         = ReplaceOptions.Empty;
                options.HighlightOptions = HighlightOptions.Match;
                options.DryRun           = true;
            }
#endif
            return(true);
        }
コード例 #7
0
        public bool TryParse(CommonCopyCommandOptions options)
        {
            var baseOptions = (CommonFindCommandOptions)options;

            if (!TryParse(baseOptions))
            {
                return(false);
            }

            options = (CommonCopyCommandOptions)baseOptions;

            if (!FilterParser.TryParse(
                    Name,
                    OptionNames.Name,
                    OptionValueProviders.PatternOptionsProvider,
                    out Filter? nameFilter,
                    out FileNamePart namePart,
                    allowNull: true))
            {
                return(false);
            }
#if DEBUG
            if (!TryParseAsEnumFlags(
                    IgnoredAttributes,
                    OptionNames.IgnoredAttributes,
                    out FileSystemAttributes noCompareAttributes,
                    provider: OptionValueProviders.FileSystemAttributesToSkipProvider))
            {
                return(false);
            }

            TimeSpan allowedTimeDiff = TimeSpan.Zero;

            if (AllowedTimeDiff != null &&
                !TimeSpan.TryParse(AllowedTimeDiff, CultureInfo.InvariantCulture, out allowedTimeDiff))
            {
                Logger.WriteError($"Option '{OptionNames.GetHelpText(OptionNames.AllowedTimeDiff)}' "
                                  + $"has invalid value '{AllowedTimeDiff}'.");

                return(false);
            }

            options.AllowedTimeDiff     = allowedTimeDiff;
            options.NoCompareAttributes = GetFileAttributes(noCompareAttributes);
#endif
            options.NameFilter = nameFilter;
            options.NamePart   = namePart;

            return(true);
        }
コード例 #8
0
        public static bool TryParseTargetDirectory(
            string value,
            [NotNullWhen(true)] out string?result,
            CommonCopyCommandOptions options,
            string directoryName,
            string optionName)
        {
            result = null;

            if (value != null)
            {
                if (!TryEnsureFullPath(value, out result))
                {
                    return(false);
                }
            }
            else
            {
                int length = options.Paths.Length;

                if (length < 2)
                {
                    WriteError($"{directoryName} directory is required. It can be specified either as a last unnamed parameter "
                               + $"or using option '{OptionNames.GetHelpText(optionName)}'.");

                    return(false);
                }
                else
                {
                    result        = options.Paths[length - 1].Path;
                    options.Paths = options.Paths.RemoveAt(length - 1);
                }
            }

            return(true);
        }
コード例 #9
0
 private static void WriteOptionError(string value, string optionName, string?allowedValues)
 {
     WriteParseError(value, OptionNames.GetHelpText(optionName), allowedValues);
 }
コード例 #10
0
ファイル: ParseHelpers.cs プロジェクト: fjsnogueira/Orang
        public static bool TryParseModifyOptions(
            IEnumerable <string> values,
            string optionName,
            out ModifyOptions modifyOptions,
            out bool aggregateOnly)
        {
            modifyOptions = null;
            aggregateOnly = false;

            var           sortProperty = ValueSortProperty.None;
            List <string> options      = null;

            foreach (string value in values)
            {
                int index = value.IndexOf('=');

                if (index >= 0)
                {
                    string key    = value.Substring(0, index);
                    string value2 = value.Substring(index + 1);

                    if (OptionValues.SortBy.IsKeyOrShortKey(key))
                    {
                        if (!TryParseAsEnum(value2, optionName, out sortProperty, provider: OptionValueProviders.ValueSortPropertyProvider))
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        string helpText = OptionValueProviders.ModifyFlagsProvider.GetHelpText();
                        WriteError($"Option '{OptionNames.GetHelpText(optionName)}' has invalid value '{value}'. Allowed values: {helpText}.");
                        return(false);
                    }
                }
                else
                {
                    (options ?? (options = new List <string>())).Add(value);
                }
            }

            var modifyFlags = ModifyFlags.None;

            if (options != null &&
                !TryParseAsEnumFlags(options, optionName, out modifyFlags, provider: OptionValueProviders.ModifyFlagsProvider))
            {
                return(false);
            }

            if ((modifyFlags & ModifyFlags.ExceptIntersect) == ModifyFlags.ExceptIntersect)
            {
                WriteError($"Values '{OptionValues.ModifyFlags_Except.HelpValue}' and '{OptionValues.ModifyFlags_Intersect.HelpValue}' cannot be use both at the same time.");
                return(false);
            }

            var functions = ModifyFunctions.None;

            if ((modifyFlags & ModifyFlags.Distinct) != 0)
            {
                functions |= ModifyFunctions.Distinct;
            }

            if ((modifyFlags & ModifyFlags.Ascending) != 0)
            {
                functions |= ModifyFunctions.Sort;
            }

            if ((modifyFlags & ModifyFlags.Descending) != 0)
            {
                functions |= ModifyFunctions.SortDescending;
            }

            if ((modifyFlags & ModifyFlags.Except) != 0)
            {
                functions |= ModifyFunctions.Except;
            }

            if ((modifyFlags & ModifyFlags.Intersect) != 0)
            {
                functions |= ModifyFunctions.Intersect;
            }

            if ((modifyFlags & ModifyFlags.RemoveEmpty) != 0)
            {
                functions |= ModifyFunctions.RemoveEmpty;
            }

            if ((modifyFlags & ModifyFlags.RemoveWhiteSpace) != 0)
            {
                functions |= ModifyFunctions.RemoveWhiteSpace;
            }

            if ((modifyFlags & ModifyFlags.TrimStart) != 0)
            {
                functions |= ModifyFunctions.TrimStart;
            }

            if ((modifyFlags & ModifyFlags.TrimEnd) != 0)
            {
                functions |= ModifyFunctions.TrimEnd;
            }

            if ((modifyFlags & ModifyFlags.ToLower) != 0)
            {
                functions |= ModifyFunctions.ToLower;
            }

            if ((modifyFlags & ModifyFlags.ToUpper) != 0)
            {
                functions |= ModifyFunctions.ToUpper;
            }

            aggregateOnly = (modifyFlags & ModifyFlags.AggregateOnly) != 0;

            if (modifyFlags != ModifyFlags.None)
            {
                modifyOptions = new ModifyOptions(
                    functions: functions,
                    aggregate: (modifyFlags & ModifyFlags.Aggregate) != 0 || aggregateOnly,
                    ignoreCase: (modifyFlags & ModifyFlags.IgnoreCase) != 0,
                    cultureInvariant: (modifyFlags & ModifyFlags.CultureInvariant) != 0,
                    sortProperty: sortProperty);
            }
            else
            {
                modifyOptions = ModifyOptions.Default;
            }

            return(true);
        }
コード例 #11
0
        public bool TryParse(ReplaceCommandOptions options)
        {
            var baseOptions = (FileSystemCommandOptions)options;

            if (!TryParse(baseOptions))
            {
                return(false);
            }

            options = (ReplaceCommandOptions)baseOptions;

            if (!TryParseProperties(Ask, Name, options))
            {
                return(false);
            }

            if (!TryParseAsEnumFlags(Highlight, OptionNames.Highlight, out HighlightOptions highlightOptions, defaultValue: HighlightOptions.Replacement, provider: OptionValueProviders.ReplaceHighlightOptionsProvider))
            {
                return(false);
            }

            if (!FilterParser.TryParse(Content, OptionNames.Content, OptionValueProviders.PatternOptionsWithoutGroupAndPartAndNegativeProvider, out Filter? contentFilter))
            {
                return(false);
            }

            if (!TryParseReplacement(Replacement, out string?replacement))
            {
                return(false);
            }

            if (!DelegateFactory.TryCreateMatchEvaluator(Evaluator, out MatchEvaluator? matchEvaluator))
            {
                return(false);
            }

            if (replacement != null && matchEvaluator != null)
            {
                WriteError($"Options '{OptionNames.GetHelpText(OptionNames.Replacement)}' and '{OptionNames.GetHelpText(OptionNames.Evaluator)}' cannot be set both at the same time.");
                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);
            }

            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,
                    contentDisplayStyleProvider: OptionValueProviders.ContentDisplayStyleProvider_WithoutUnmatchedLines,
                    pathDisplayStyleProvider: OptionValueProviders.PathDisplayStyleProvider))
            {
                return(false);
            }

            if (contentDisplayStyle2 != null)
            {
                if (options.AskMode == AskMode.Value &&
                    contentDisplayStyle2 == ContentDisplayStyle.AllLines)
                {
                    WriteError($"Option '{OptionNames.GetHelpText(OptionNames.Display)}' cannot have value '{OptionValueProviders.ContentDisplayStyleProvider.GetValue(nameof(ContentDisplayStyle.AllLines)).HelpValue}' when option '{OptionNames.GetHelpText(OptionNames.Ask)}' has value '{OptionValueProviders.AskModeProvider.GetValue(nameof(AskMode.Value)).HelpValue}'.");
                    return(false);
                }

                contentDisplayStyle = contentDisplayStyle2.Value;
            }
            else if (Input != null)
            {
                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;
            }

            options.Format = new OutputDisplayFormat(
                contentDisplayStyle: contentDisplayStyle,
                pathDisplayStyle: pathDisplayStyle,
                lineOptions: lineDisplayOptions,
                lineContext: lineContext,
                displayParts: displayParts,
                fileProperties: fileProperties,
                indent: indent,
                separator: separator);

            options.HighlightOptions = highlightOptions;
            options.ContentFilter    = contentFilter;
            options.ReplaceOptions   = replaceOptions;
            options.Input            = Input;
            options.DryRun           = DryRun;
            options.MaxMatchesInFile = maxMatchesInFile;
            options.MaxMatchingFiles = maxMatchingFiles;
            options.MaxTotalMatches  = 0;

            return(true);
        }
コード例 #12
0
        public bool TryParse(FileSystemCommandOptions options)
        {
            var baseOptions = (CommonRegexCommandOptions)options;

            if (!TryParse(baseOptions))
            {
                return(false);
            }

            options = (FileSystemCommandOptions)baseOptions;

            if (!TryParsePaths(out ImmutableArray <PathInfo> paths))
            {
                return(false);
            }

            if (!TryParseAsEnumFlags(Attributes, OptionNames.Attributes, out FileSystemAttributes attributes, provider: OptionValueProviders.FileSystemAttributesProvider))
            {
                return(false);
            }

            if (!TryParseAsEnumFlags(AttributesToSkip, OptionNames.AttributesToSkip, out FileSystemAttributes attributesToSkip, provider: OptionValueProviders.FileSystemAttributesToSkipProvider))
            {
                return(false);
            }

            if (!TryParseEncoding(Encoding, out Encoding defaultEncoding, EncodingHelpers.UTF8NoBom))
            {
                return(false);
            }

            if (!TryParseSortOptions(Sort, OptionNames.Sort, out SortOptions sortOptions))
            {
                return(false);
            }

            if (!FilterParser.TryParse(IncludeDirectory, OptionNames.IncludeDirectory, OptionValueProviders.PatternOptionsProvider, out Filter directoryFilter, allowNull: true))
            {
                return(false);
            }

            if (!FilterParser.TryParse(
                    Extension,
                    OptionNames.Extension,
                    OptionValueProviders.ExtensionOptionsProvider,
                    out Filter extensionFilter,
                    allowNull: true,
                    defaultNamePart: NamePartKind.Extension,
                    includedPatternOptions: PatternOptions.List | PatternOptions.Equals | PatternOptions.IgnoreCase))
            {
                return(false);
            }

            if (!TryParseFileProperties(
                    FileProperties,
                    OptionNames.Properties,
                    out FilePropertyFilter filePropertyFilter))
            {
                return(false);
            }

            if ((attributes & FileSystemAttributes.Empty) != 0)
            {
                if ((attributesToSkip & FileSystemAttributes.Empty) != 0)
                {
                    Logger.WriteError($"Value '{OptionValueProviders.FileSystemAttributesProvider.GetValue(nameof(FileSystemAttributes.Empty)).HelpValue}' cannot be specified both for '{OptionNames.GetHelpText(OptionNames.Attributes)}' and '{OptionNames.GetHelpText(OptionNames.AttributesToSkip)}'.");
                    return(false);
                }

                options.Empty = true;
            }
            else if ((attributesToSkip & FileSystemAttributes.Empty) != 0)
            {
                options.Empty = false;
            }

            options.Paths                 = paths;
            options.DirectoryFilter       = directoryFilter;
            options.ExtensionFilter       = extensionFilter;
            options.Attributes            = GetFileAttributes(attributes);
            options.AttributesToSkip      = GetFileAttributes(attributesToSkip);
            options.RecurseSubdirectories = !NoRecurse;
            options.Progress              = Progress;
            options.DefaultEncoding       = defaultEncoding;
            options.SortOptions           = sortOptions;
            options.FilePropertyFilter    = filePropertyFilter;

            FileSystemAttributes = attributes;

            return(true);
        }
コード例 #13
0
        public bool TryParse(RenameCommandOptions options)
        {
            var baseOptions = (DeleteOrRenameCommandOptions)options;

            if (!TryParse(baseOptions))
            {
                return(false);
            }

            options = (RenameCommandOptions)baseOptions;

            if (!TryParseAsEnumFlags(Highlight, OptionNames.Highlight, out HighlightOptions highlightOptions, defaultValue: HighlightOptions.Replacement, provider: OptionValueProviders.RenameHighlightOptionsProvider))
            {
                return(false);
            }

            if (!FilterParser.TryParse(Name, OptionNames.Name, OptionValueProviders.PatternOptionsWithoutGroupAndNegativeProvider, out Filter? nameFilter, out FileNamePart namePart, namePartProvider: OptionValueProviders.NamePartKindProvider_WithoutFullName))
            {
                return(false);
            }

            if (!FilterParser.TryParse(Content, OptionNames.Content, OptionValueProviders.PatternOptionsWithoutPartProvider, out Filter? contentFilter, allowNull: true))
            {
                return(false);
            }

            if (!TryParseReplacement(Replacement, out string?replacement))
            {
                return(false);
            }

            if (!DelegateFactory.TryCreateMatchEvaluator(Evaluator, out MatchEvaluator? matchEvaluator))
            {
                return(false);
            }

            if (replacement != null && matchEvaluator != null)
            {
                WriteError($"Options '{OptionNames.GetHelpText(OptionNames.Replacement)}' and '{OptionNames.GetHelpText(OptionNames.Evaluator)}' cannot be set both at the same time.");
                return(false);
            }

            if (!TryParseReplaceOptions(Modify, OptionNames.Modify, replacement, matchEvaluator, out ReplaceOptions? replaceOptions))
            {
                return(false);
            }

            if (!TryParseAsEnum(Conflict, OptionNames.Conflict, out ConflictResolution conflictResolution, defaultValue: ConflictResolution.Ask, provider: OptionValueProviders.ConflictResolutionProvider_WithoutSuffix))
            {
                return(false);
            }

            if (!TryParseDisplay(
                    values: Display,
                    optionName: OptionNames.Display,
                    contentDisplayStyle: out ContentDisplayStyle? _,
                    pathDisplayStyle: out PathDisplayStyle? pathDisplayStyle,
                    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,
                    contentDisplayStyleProvider: OptionValueProviders.ContentDisplayStyleProvider,
                    pathDisplayStyleProvider: OptionValueProviders.PathDisplayStyleProvider_Rename))
            {
                return(false);
            }

            if (pathDisplayStyle == PathDisplayStyle.Relative &&
                options.Paths.Length > 1 &&
                options.SortOptions != null)
            {
                pathDisplayStyle = PathDisplayStyle.Full;
            }

            options.Format = new OutputDisplayFormat(
                contentDisplayStyle: ContentDisplayStyle.None,
                pathDisplayStyle: pathDisplayStyle ?? PathDisplayStyle.Full,
                lineOptions: lineDisplayOptions,
                lineContext: lineContext,
                displayParts: displayParts,
                fileProperties: fileProperties,
                indent: indent,
                separator: separator);

            options.HighlightOptions = highlightOptions;
            options.SearchTarget     = GetSearchTarget();
            options.ReplaceOptions   = replaceOptions;
            options.Ask                = Ask;
            options.DryRun             = DryRun;
            options.NameFilter         = nameFilter;
            options.NamePart           = namePart;
            options.ContentFilter      = contentFilter;
            options.MaxMatchingFiles   = MaxCount;
            options.ConflictResolution = conflictResolution;

            return(true);
        }
コード例 #14
0
        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);
        }
コード例 #15
0
ファイル: ParseHelpers.cs プロジェクト: fjsnogueira/Orang
 private static void WriteParseError(string value, string optionName, string helpText)
 {
     WriteError($"Option '{OptionNames.GetHelpText(optionName)}' has invalid value '{value}'. Allowed values: {helpText}.");
 }
コード例 #16
0
        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);
        }
コード例 #17
0
ファイル: ParseHelpers.cs プロジェクト: fjsnogueira/Orang
        public static bool TryParseDisplay(
            IEnumerable <string> values,
            string optionName,
            out ContentDisplayStyle?contentDisplayStyle,
            out PathDisplayStyle?pathDisplayStyle,
            out LineDisplayOptions lineDisplayOptions,
            out DisplayParts displayParts,
            out ImmutableArray <FileProperty> fileProperties,
            out string indent,
            out string separator,
            OptionValueProvider contentDisplayStyleProvider = null,
            OptionValueProvider pathDisplayStyleProvider    = null)
        {
            contentDisplayStyle = null;
            pathDisplayStyle    = null;
            lineDisplayOptions  = LineDisplayOptions.None;
            displayParts        = DisplayParts.None;
            fileProperties      = ImmutableArray <FileProperty> .Empty;
            indent    = null;
            separator = null;

            ImmutableArray <FileProperty> .Builder builder = null;

            foreach (string value in values)
            {
                int index = value.IndexOf('=');

                if (index >= 0)
                {
                    string key    = value.Substring(0, index);
                    string value2 = value.Substring(index + 1);

                    if (OptionValues.Display_Content.IsKeyOrShortKey(key))
                    {
                        if (!TryParseAsEnum(value2, optionName, out ContentDisplayStyle contentDisplayStyle2, provider: contentDisplayStyleProvider))
                        {
                            return(false);
                        }

                        contentDisplayStyle = contentDisplayStyle2;
                    }
                    else if (OptionValues.Display_Path.IsKeyOrShortKey(key))
                    {
                        if (!TryParseAsEnum(value2, optionName, out PathDisplayStyle pathDisplayStyle2, provider: pathDisplayStyleProvider))
                        {
                            return(false);
                        }

                        pathDisplayStyle = pathDisplayStyle2;
                    }
                    else if (OptionValues.Display_Indent.IsKeyOrShortKey(key))
                    {
                        indent = value2;
                    }
                    else if (OptionValues.Display_Separator.IsKeyOrShortKey(key))
                    {
                        separator = value2;
                    }
                    else
                    {
                        ThrowException(value);
                    }
                }
                else if (OptionValues.Display_Summary.IsValueOrShortValue(value))
                {
                    displayParts |= DisplayParts.Summary;
                }
                else if (OptionValues.Display_Count.IsValueOrShortValue(value))
                {
                    displayParts |= DisplayParts.Count;
                }
                else if (OptionValues.Display_CreationTime.IsValueOrShortValue(value))
                {
                    (builder ?? (builder = ImmutableArray.CreateBuilder <FileProperty>())).Add(FileProperty.CreationTime);
                }
                else if (OptionValues.Display_ModifiedTime.IsValueOrShortValue(value))
                {
                    (builder ?? (builder = ImmutableArray.CreateBuilder <FileProperty>())).Add(FileProperty.ModifiedTime);
                }
                else if (OptionValues.Display_Size.IsValueOrShortValue(value))
                {
                    (builder ?? (builder = ImmutableArray.CreateBuilder <FileProperty>())).Add(FileProperty.Size);
                }
                else if (OptionValues.Display_LineNumber.IsValueOrShortValue(value))
                {
                    lineDisplayOptions |= LineDisplayOptions.IncludeLineNumber;
                }
                else if (OptionValues.Display_TrimLine.IsValueOrShortValue(value))
                {
                    lineDisplayOptions |= LineDisplayOptions.TrimLine;
                }
                else if (OptionValues.Display_TrimLine.IsValueOrShortValue(value))
                {
                    lineDisplayOptions |= LineDisplayOptions.TrimLine;
                }
                else if (OptionValues.Display_TrimLine.IsValueOrShortValue(value))
                {
                    lineDisplayOptions |= LineDisplayOptions.TrimLine;
                }
                else
                {
                    ThrowException(value);
                }
            }

            if (builder != null)
            {
                fileProperties = builder.ToImmutableArray();
            }

            return(true);

            void ThrowException(string value)
            {
                string helpText = OptionValueProviders.DisplayProvider.GetHelpText();

                throw new ArgumentException($"Option '{OptionNames.GetHelpText(optionName)}' has invalid value '{value}'. Allowed values: {helpText}.", nameof(values));
            }
        }
コード例 #18
0
        public bool TryParse(DeleteCommandOptions options)
        {
            var baseOptions = (CommonFindCommandOptions)options;

            if (!TryParse(baseOptions))
            {
                return(false);
            }

            options = (DeleteCommandOptions)baseOptions;

            if (!TryParseAsEnumFlags(Highlight, OptionNames.Highlight, out HighlightOptions highlightOptions, defaultValue: HighlightOptions.Default, provider: OptionValueProviders.DeleteHighlightOptionsProvider))
            {
                return(false);
            }

            if (!FilterParser.TryParse(Name, OptionNames.Name, OptionValueProviders.PatternOptionsProvider, out Filter nameFilter, allowNull: true))
            {
                return(false);
            }

            if (nameFilter == null &&
                options.Paths.Length == 1 &&
                options.Paths[0].Origin == PathOrigin.CurrentDirectory)
            {
                Logger.WriteError($"Option '{OptionNames.GetHelpText(OptionNames.Name)}' is required when no path is specified (i.e. current directory is used).");
                return(false);
            }

            if (!FilterParser.TryParse(Content, OptionNames.Content, OptionValueProviders.PatternOptionsProvider, out Filter contentFilter, allowNull: true))
            {
                return(false);
            }

            if (!TryParseDisplay(
                    values: Display,
                    optionName: OptionNames.Display,
                    contentDisplayStyle: out ContentDisplayStyle? _,
                    pathDisplayStyle: out PathDisplayStyle? 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,
                    pathDisplayStyleProvider: OptionValueProviders.PathDisplayStyleProvider))
            {
                return(false);
            }

            if (pathDisplayStyle == PathDisplayStyle.Relative &&
                options.Paths.Length > 1 &&
                options.SortOptions != null)
            {
                pathDisplayStyle = PathDisplayStyle.Full;
            }

            options.Format = new OutputDisplayFormat(
                contentDisplayStyle: ContentDisplayStyle.None,
                pathDisplayStyle: pathDisplayStyle ?? PathDisplayStyle.Full,
                lineOptions: lineDisplayOptions,
                displayParts: displayParts,
                fileProperties: fileProperties,
                indent: indent,
                separator: separator);

            options.Ask              = Ask;
            options.DryRun           = DryRun;
            options.HighlightOptions = highlightOptions;
            options.SearchTarget     = GetSearchTarget();
            options.NameFilter       = nameFilter;
            options.ContentFilter    = contentFilter;
            options.ContentOnly      = ContentOnly;
            options.IncludingBom     = IncludingBom;
            options.MaxMatchingFiles = MaxCount;

            return(true);
        }
コード例 #19
0
ファイル: FilterParser.cs プロジェクト: fjsnogueira/Orang
        public static bool TryParse(
            IEnumerable <string> values,
            string optionName,
            OptionValueProvider provider,
            out Filter filter,
            bool allowNull = false,
            NamePartKind defaultNamePart          = NamePartKind.Name,
            PatternOptions includedPatternOptions = PatternOptions.None)
        {
            filter = null;

            string pattern = values.FirstOrDefault();

            if (pattern == null)
            {
                if (allowNull)
                {
                    return(true);
                }
                else
                {
                    throw new InvalidOperationException($"Option '{OptionNames.GetHelpText(optionName)}' is required.");
                }
            }

            TimeSpan             matchTimeout = Regex.InfiniteMatchTimeout;
            string               groupName    = null;
            NamePartKind         namePart     = defaultNamePart;
            string               separator    = null;
            Func <Capture, bool> predicate    = null;

            List <string> options = null;

            foreach (string option in values.Skip(1))
            {
                int index = option.IndexOf("=");

                if (index != -1)
                {
                    string key   = option.Substring(0, index);
                    string value = option.Substring(index + 1);

                    if (OptionValues.Group.IsKeyOrShortKey(key))
                    {
                        groupName = value;
                        continue;
                    }
                    else if (OptionValues.ListSeparator.IsKeyOrShortKey(key))
                    {
                        separator = value;
                        continue;
                    }
                    else if (OptionValues.Part.IsKeyOrShortKey(key))
                    {
                        if (!TryParseAsEnum(value, out namePart, provider: OptionValueProviders.NamePartKindProvider))
                        {
                            string helpText = OptionValueProviders.NamePartKindProvider.GetHelpText();
                            WriteError($"Option '{OptionValues.Part.HelpValue}' has invalid value '{value}'. Allowed values: {helpText}.");
                            return(false);
                        }

                        continue;
                    }
                    else if (OptionValues.Timeout.IsKeyOrShortKey(key))
                    {
                        if (!TryParseMatchTimeout(value, out matchTimeout))
                        {
                            WriteError($"Option '{OptionValues.Timeout.HelpValue}' has invalid value '{value}'.");
                            return(false);
                        }

                        continue;
                    }
                }

                if (Expression.TryParse(option, out Expression expression))
                {
                    if (OptionValues.Length.IsKeyOrShortKey(expression.Identifier))
                    {
                        try
                        {
                            predicate = PredicateHelpers.GetLengthPredicate(expression);
                            continue;
                        }
                        catch (ArgumentException)
                        {
                            WriteError($"Option '{OptionNames.GetHelpText(optionName)}' has invalid value '{option}'.");
                            return(false);
                        }
                    }
                    else
                    {
                        WriteError($"Option '{OptionNames.GetHelpText(optionName)}' has invalid value '{option}'. Allowed values: {provider.GetHelpText()}.");
                        return(false);
                    }
                }

                (options ?? (options = new List <string>())).Add(option);
            }

            if (!TryParseRegexOptions(options, optionName, out RegexOptions regexOptions, out PatternOptions patternOptions, includedPatternOptions, provider))
            {
                return(false);
            }

            switch (patternOptions & (PatternOptions.WholeWord | PatternOptions.WholeLine))
            {
            case PatternOptions.None:
            case PatternOptions.WholeWord:
            case PatternOptions.WholeLine:
            {
                break;
            }

            default:
            {
                WriteError($"Values '{OptionValueProviders.PatternOptionsProvider.GetValue(nameof(PatternOptions.WholeWord)).HelpValue}' and '{OptionValueProviders.PatternOptionsProvider.GetValue(nameof(PatternOptions.WholeLine)).HelpValue}' cannot be combined.");
                return(false);
            }
            }

            if ((patternOptions & PatternOptions.FromFile) != 0 &&
                !FileSystemHelpers.TryReadAllText(pattern, out pattern))
            {
                return(false);
            }

            pattern = BuildPattern(pattern, patternOptions, separator);

            Regex regex = null;

            try
            {
                regex = new Regex(pattern, regexOptions, matchTimeout);
            }
            catch (ArgumentException ex)
            {
                WriteError(ex, $"Could not parse regular expression: {ex.Message}");
                return(false);
            }

            int groupIndex = -1;

            if (groupName != null)
            {
                groupIndex = regex.GroupNumberFromName(groupName);
                if (groupIndex == -1)
                {
                    string message = $"Group '{groupName}' does not exist.";

                    string[] groupNames = regex.GetGroupNames();

                    if (groupNames.Length > 1)
                    {
                        message += $" Existing group names: {TextHelpers.Join(", ", " and ", groupNames.Where(f => f != "0"))}.";
                    }

                    WriteError(message);
                    return(false);
                }
            }

            filter = new Filter(
                regex,
                namePart: namePart,
                groupNumber: groupIndex,
                isNegative: (patternOptions & PatternOptions.Negative) != 0,
                predicate);

            return(true);
        }
コード例 #20
0
        public bool TryParse(CommonFindCommandOptions options)
        {
            var baseOptions = (FileSystemCommandOptions)options;

            if (!TryParse(baseOptions))
            {
                return(false);
            }

            options = (CommonFindCommandOptions)baseOptions;

            if (!TryParseProperties(Ask, Name, options))
            {
                return(false);
            }

            if (!TryParseAsEnumFlags(Highlight, OptionNames.Highlight, out HighlightOptions highlightOptions, defaultValue: HighlightOptions.Default, provider: OptionValueProviders.FindHighlightOptionsProvider))
            {
                return(false);
            }

            if (!FilterParser.TryParse(Content, OptionNames.Content, OptionValueProviders.PatternOptionsWithoutPartProvider, out Filter? contentFilter, allowNull: true))
            {
                return(false);
            }

            if (!TryParseDisplay(
                    values: Display,
                    optionName: OptionNames.Display,
                    contentDisplayStyle: out ContentDisplayStyle? contentDisplayStyle,
                    pathDisplayStyle: out PathDisplayStyle? pathDisplayStyle,
                    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,
                    contentDisplayStyleProvider: OptionValueProviders.ContentDisplayStyleProvider,
                    pathDisplayStyleProvider: OptionValueProviders.PathDisplayStyleProvider))
            {
                return(false);
            }

            if (pathDisplayStyle == PathDisplayStyle.Relative &&
                options.Paths.Length > 1 &&
                options.SortOptions != null)
            {
                pathDisplayStyle = PathDisplayStyle.Full;
            }

            if (options.AskMode == AskMode.Value &&
                (contentDisplayStyle == ContentDisplayStyle.AllLines || contentDisplayStyle == ContentDisplayStyle.UnmatchedLines))
            {
                WriteError($"Option '{OptionNames.GetHelpText(OptionNames.Display)}' cannot have value '{OptionValueProviders.ContentDisplayStyleProvider.GetValue(contentDisplayStyle.Value.ToString()).HelpValue}' when option '{OptionNames.GetHelpText(OptionNames.Ask)}' has value '{OptionValueProviders.AskModeProvider.GetValue(nameof(AskMode.Value)).HelpValue}'.");
                return(false);
            }

            if (!TryParseMaxCount(MaxCount, out int maxMatchingFiles, out int maxMatchesInFile))
            {
                return(false);
            }

            options.Format = new OutputDisplayFormat(
                contentDisplayStyle: contentDisplayStyle ?? ContentDisplayStyle.Line,
                pathDisplayStyle: pathDisplayStyle ?? PathDisplayStyle.Full,
                lineOptions: lineDisplayOptions,
                lineContext: lineContext,
                displayParts: displayParts,
                fileProperties: fileProperties,
                indent: indent,
                separator: separator);

            options.HighlightOptions = highlightOptions;
            options.SearchTarget     = GetSearchTarget();
            options.ContentFilter    = contentFilter;
            options.MaxMatchesInFile = maxMatchesInFile;
            options.MaxMatchingFiles = maxMatchingFiles;
            options.MaxTotalMatches  = 0;

            return(true);
        }
コード例 #21
0
        public bool TryParse(FileSystemCommandOptions options)
        {
            var baseOptions = (CommonRegexCommandOptions)options;

            if (!TryParse(baseOptions))
            {
                return(false);
            }

            options = (FileSystemCommandOptions)baseOptions;

            if (!TryParsePaths(out ImmutableArray <PathInfo> paths))
            {
                return(false);
            }

            if (!TryParseAsEnumFlags(Attributes, OptionNames.Attributes, out FileSystemAttributes attributes, provider: OptionValueProviders.FileSystemAttributesProvider))
            {
                return(false);
            }

            if (!TryParseAsEnumFlags(AttributesToSkip, OptionNames.AttributesToSkip, out FileSystemAttributes attributesToSkip, provider: OptionValueProviders.FileSystemAttributesToSkipProvider))
            {
                return(false);
            }

            if (!TryParseEncoding(Encoding, out Encoding defaultEncoding, Text.EncodingHelpers.UTF8NoBom))
            {
                return(false);
            }

            if (!TryParseSortOptions(Sort, OptionNames.Sort, out SortOptions? sortOptions))
            {
                return(false);
            }

            if (!FilterParser.TryParse(IncludeDirectory, OptionNames.IncludeDirectory, OptionValueProviders.PatternOptionsProvider, out Filter? directoryFilter, out FileNamePart directoryNamePart, allowNull: true, namePartProvider: OptionValueProviders.NamePartKindProvider_WithoutExtension))
            {
                return(false);
            }

            if (!FilterParser.TryParse(
                    Extension,
                    OptionNames.Extension,
                    OptionValueProviders.ExtensionOptionsProvider,
                    out Filter? extensionFilter,
                    allowNull: true,
                    defaultNamePart: FileNamePart.Extension,
                    includedPatternOptions: PatternOptions.List | PatternOptions.Equals | PatternOptions.IgnoreCase))
            {
                return(false);
            }

            if (!TryParseFileProperties(
                    FileProperties,
                    OptionNames.Properties,
                    out FilterPredicate <DateTime>?creationTimePredicate,
                    out FilterPredicate <DateTime>?modifiedTimePredicate,
                    out FilterPredicate <long>?sizePredicate))
            {
                return(false);
            }

            if ((attributes & FileSystemAttributes.Empty) != 0)
            {
                if ((attributesToSkip & FileSystemAttributes.Empty) != 0)
                {
                    Logger.WriteError($"Value '{OptionValueProviders.FileSystemAttributesProvider.GetValue(nameof(FileSystemAttributes.Empty)).HelpValue}' cannot be specified both for '{OptionNames.GetHelpText(OptionNames.Attributes)}' and '{OptionNames.GetHelpText(OptionNames.AttributesToSkip)}'.");
                    return(false);
                }

                options.EmptyOption = FileEmptyOption.Empty;
            }
            else if ((attributesToSkip & FileSystemAttributes.Empty) != 0)
            {
                options.EmptyOption = FileEmptyOption.NonEmpty;
            }

            options.Paths                 = paths;
            options.DirectoryFilter       = directoryFilter;
            options.DirectoryNamePart     = directoryNamePart;
            options.ExtensionFilter       = extensionFilter;
            options.Attributes            = GetFileAttributes(attributes);
            options.AttributesToSkip      = GetFileAttributes(attributesToSkip);
            options.RecurseSubdirectories = !NoRecurse;
            options.Progress              = Progress;
            options.DefaultEncoding       = defaultEncoding;
            options.SortOptions           = sortOptions;
            options.CreationTimePredicate = creationTimePredicate;
            options.ModifiedTimePredicate = modifiedTimePredicate;
            options.SizePredicate         = sizePredicate;

            if (creationTimePredicate != null ||
                modifiedTimePredicate != null ||
                sizePredicate != null)
            {
                options.FilePropertyFilter = new FilePropertyFilter(
                    creationTimePredicate: creationTimePredicate?.Predicate,
                    modifiedTimePredicate: modifiedTimePredicate?.Predicate,
                    sizePredicate: sizePredicate?.Predicate);
            }

            FileSystemAttributes = attributes;

            return(true);
        }
コード例 #22
0
        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);
        }
コード例 #23
0
        public static bool TryParse(
            IEnumerable <string> values,
            string optionName,
            OptionValueProvider provider,
            out Filter?filter,
            out FileNamePart namePart,
            bool allowNull = false,
            OptionValueProvider?namePartProvider  = null,
            FileNamePart defaultNamePart          = FileNamePart.Name,
            PatternOptions includedPatternOptions = PatternOptions.None)
        {
            filter   = null;
            namePart = defaultNamePart;

            string?pattern = values.FirstOrDefault();

            if (pattern == null)
            {
                if (allowNull)
                {
                    return(true);
                }
                else
                {
                    throw new InvalidOperationException($"Option '{OptionNames.GetHelpText(optionName)}' is required.");
                }
            }

            TimeSpan            matchTimeout = Regex.InfiniteMatchTimeout;
            string?             groupName    = null;
            string?             separator    = null;
            Func <string, bool>?predicate    = null;

            List <string>?options = null;

            foreach (string option in values.Skip(1))
            {
                int index = option.IndexOfAny(_equalsOrLessThanOrGreaterThanChars);

                if (index != -1)
                {
                    string key = option.Substring(0, index);

                    if (!provider.ContainsKeyOrShortKey(key))
                    {
                        WriteOptionError(option, optionName, provider);
                        return(false);
                    }

                    string value = option.Substring(index + 1);

                    if (OptionValues.Group.IsKeyOrShortKey(key))
                    {
                        groupName = value;
                        continue;
                    }
                    else if (OptionValues.ListSeparator.IsKeyOrShortKey(key))
                    {
                        separator = value;
                        continue;
                    }
                    else if (OptionValues.Part.IsKeyOrShortKey(key))
                    {
                        if (!TryParseAsEnum(
                                value,
                                out namePart,
                                provider: namePartProvider ?? OptionValueProviders.NamePartKindProvider))
                        {
                            WriteOptionValueError(
                                value,
                                OptionValues.Part,
                                namePartProvider ?? OptionValueProviders.NamePartKindProvider);
                            return(false);
                        }

                        continue;
                    }
                    else if (OptionValues.Timeout.IsKeyOrShortKey(key))
                    {
                        if (!TryParseMatchTimeout(value, out matchTimeout))
                        {
                            WriteOptionValueError(value, OptionValues.Timeout);
                            return(false);
                        }

                        continue;
                    }
                }

                if (Expression.TryParse(option, out Expression? expression))
                {
                    if (OptionValues.Length.IsKeyOrShortKey(expression.Identifier) &&
                        provider.ContainsKeyOrShortKey(expression.Identifier))
                    {
                        try
                        {
                            predicate = PredicateHelpers.GetLengthPredicate(expression);
                            continue;
                        }
                        catch (ArgumentException)
                        {
                            WriteOptionValueError(
                                expression.Value,
                                OptionValues.Length,
                                HelpProvider.GetExpressionsText("  ", includeDate: false));
                            return(false);
                        }
                    }
                    else
                    {
                        WriteOptionError(option, optionName, provider);
                        return(false);
                    }
                }

                (options ??= new List <string>()).Add(option);
            }

            if (!TryParseRegexOptions(
                    options,
                    optionName,
                    out RegexOptions regexOptions,
                    out PatternOptions patternOptions,
                    includedPatternOptions,
                    provider))
            {
                return(false);
            }

            switch (patternOptions & (PatternOptions.WholeWord | PatternOptions.WholeLine))
            {
            case PatternOptions.None:
            case PatternOptions.WholeWord:
            case PatternOptions.WholeLine:
            {
                break;
            }

            default:
            {
                string helpValue = OptionValueProviders.PatternOptionsProvider
                                   .GetValue(nameof(PatternOptions.WholeWord)).HelpValue;

                string helpValue2 = OptionValueProviders.PatternOptionsProvider
                                    .GetValue(nameof(PatternOptions.WholeLine)).HelpValue;

                WriteError($"Values '{helpValue}' and '{helpValue2}' cannot be combined.");

                return(false);
            }
            }

            if ((patternOptions & PatternOptions.FromFile) != 0 &&
                !FileSystemHelpers.TryReadAllText(pattern, out pattern, ex => WriteError(ex)))
            {
                return(false);
            }

            pattern = BuildPattern(pattern, patternOptions, separator);

            if (pattern.Length == 0)
            {
                throw new InvalidOperationException(
                          $"Option '{OptionNames.GetHelpText(optionName)}' is invalid: pattern cannot be empty.");
            }

            Regex?regex = null;

            try
            {
                regex = new Regex(pattern, regexOptions, matchTimeout);
            }
            catch (ArgumentException ex)
            {
                WriteError(ex, $"Could not parse regular expression: {ex.Message}");
                return(false);
            }

            int groupIndex = -1;

            if (groupName != null)
            {
                groupIndex = regex.GroupNumberFromName(groupName);
                if (groupIndex == -1)
                {
                    string message = $"Group '{groupName}' does not exist.";

                    string[] groupNames = regex.GetGroupNames();

                    if (groupNames.Length > 1)
                    {
                        message += " Existing group names: "
                                   + $"{TextHelpers.Join(", ", " and ", groupNames.Where(f => f != "0"))}.";
                    }

                    WriteError(message);
                    return(false);
                }
            }

            filter = new Filter(
                regex,
                isNegative: (patternOptions & PatternOptions.Negative) != 0,
                groupNumber: groupIndex,
                predicate: predicate);

            return(true);
        }
コード例 #24
0
        public bool TryParse(RenameCommandOptions options)
        {
            var baseOptions = (DeleteOrRenameCommandOptions)options;

            if (!TryParse(baseOptions))
            {
                return(false);
            }

            options = (RenameCommandOptions)baseOptions;

            if (!TryParseHighlightOptions(
                    Highlight,
                    out HighlightOptions highlightOptions,
                    defaultValue: HighlightOptions.Replacement,
                    provider: OptionValueProviders.RenameHighlightOptionsProvider))
            {
                return(false);
            }

            if (!FilterParser.TryParse(
                    Name,
                    OptionNames.Name,
                    OptionValueProviders.PatternOptionsWithoutGroupAndNegativeProvider,
                    out Filter? nameFilter,
                    out FileNamePart namePart,
                    namePartProvider: OptionValueProviders.NamePartKindProvider_WithoutFullName))
            {
                return(false);
            }

            if (!FilterParser.TryParse(
                    Content,
                    OptionNames.Content,
                    OptionValueProviders.PatternOptionsWithoutPartProvider,
                    out Filter? contentFilter,
                    allowNull: true))
            {
                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 (!TryParseAsEnum(
                    Conflict,
                    OptionNames.Conflict,
                    out ConflictResolution conflictResolution,
                    defaultValue: ConflictResolution.Ask,
                    provider: OptionValueProviders.ConflictResolutionProvider_WithoutSuffix))
            {
                return(false);
            }

            if (!TryParseDisplay(
                    values: Display,
                    optionName: OptionNames.Display,
                    contentDisplayStyle: out ContentDisplayStyle? contentDisplayStyle,
                    pathDisplayStyle: out PathDisplayStyle? pathDisplayStyle,
                    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,
                    pathDisplayStyleProvider: OptionValueProviders.PathDisplayStyleProvider_Rename))
            {
                return(false);
            }

            if (pathDisplayStyle == PathDisplayStyle.Relative &&
                options.Paths.Length > 1 &&
                options.SortOptions != null)
            {
                pathDisplayStyle = PathDisplayStyle.Full;
            }

            options.Format = new OutputDisplayFormat(
                contentDisplayStyle: contentDisplayStyle ?? ContentDisplayStyle.Omit,
                pathDisplayStyle: pathDisplayStyle ?? PathDisplayStyle.Full,
                lineOptions: lineDisplayOptions,
                lineContext: lineContext,
                displayParts: displayParts,
                fileProperties: fileProperties,
                indent: indent,
                separator: separator,
                alignColumns: !noAlign);

            options.HighlightOptions   = highlightOptions;
            options.SearchTarget       = GetSearchTarget();
            options.ReplaceOptions     = replaceOptions;
            options.AskMode            = (Ask) ? AskMode.File : AskMode.None;
            options.DryRun             = DryRun;
            options.NameFilter         = nameFilter;
            options.NamePart           = namePart;
            options.ContentFilter      = contentFilter;
            options.MaxMatchingFiles   = MaxCount;
            options.ConflictResolution = conflictResolution;
            options.Interactive        = Interactive;

            return(true);
        }
コード例 #25
0
        public bool TryParse(FindCommandOptions options)
        {
            var baseOptions = (CommonFindCommandOptions)options;

            if (!TryParse(baseOptions))
            {
                return(false);
            }

            options = (FindCommandOptions)baseOptions;

            if (!TryParseProperties(Ask, Name, options))
            {
                return(false);
            }

            if (!TryParseAsEnumFlags(Highlight, OptionNames.Highlight, out HighlightOptions highlightOptions, defaultValue: HighlightOptions.Default, provider: OptionValueProviders.FindHighlightOptionsProvider))
            {
                return(false);
            }

            if (!FilterParser.TryParse(Content, OptionNames.Content, OptionValueProviders.PatternOptionsWithoutPartProvider, out Filter contentFilter, allowNull: true))
            {
                return(false);
            }

            if (!TryParseDisplay(
                    values: Display,
                    optionName: OptionNames.Display,
                    contentDisplayStyle: out ContentDisplayStyle? contentDisplayStyle,
                    pathDisplayStyle: out PathDisplayStyle? 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,
                    pathDisplayStyleProvider: OptionValueProviders.PathDisplayStyleProvider))
            {
                return(false);
            }

            if (pathDisplayStyle == PathDisplayStyle.Relative &&
                options.Paths.Length > 1 &&
                options.SortOptions != null)
            {
                pathDisplayStyle = PathDisplayStyle.Full;
            }

            if (options.AskMode == AskMode.Value &&
                (contentDisplayStyle == ContentDisplayStyle.AllLines || contentDisplayStyle == ContentDisplayStyle.UnmatchedLines))
            {
                WriteError($"Option '{OptionNames.GetHelpText(OptionNames.Display)}' cannot have value '{OptionValueProviders.ContentDisplayStyleProvider.GetValue(contentDisplayStyle.ToString()).HelpValue}' when option '{OptionNames.GetHelpText(OptionNames.Ask)}' has value '{OptionValueProviders.AskModeProvider.GetValue(nameof(AskMode.Value)).HelpValue}'.");
                return(false);
            }

            if (!TryParseMaxCount(MaxCount, out int maxCount, out int maxMatches, out int maxMatchingFiles))
            {
                return(false);
            }

            int maxMatchesInFile;

            if (contentFilter != null)
            {
                maxMatchesInFile = maxCount;
            }
            else
            {
                maxMatchesInFile = 0;
                maxMatches       = 0;
                maxMatchingFiles = (maxCount > 0) ? maxCount : maxMatchingFiles;
            }

            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;
                pathDisplayStyle     = PathDisplayStyle.Omit;
            }

            options.Format = new OutputDisplayFormat(
                contentDisplayStyle: contentDisplayStyle ?? ContentDisplayStyle.Line,
                pathDisplayStyle: pathDisplayStyle ?? PathDisplayStyle.Full,
                lineOptions: lineDisplayOptions,
                displayParts: displayParts,
                fileProperties: fileProperties,
                indent: indent,
                separator: separator);

            options.ModifyOptions    = modifyOptions;
            options.HighlightOptions = highlightOptions;
            options.SearchTarget     = GetSearchTarget();
            options.ContentFilter    = contentFilter;
            options.MaxMatchesInFile = maxMatchesInFile;
            options.MaxMatches       = maxMatches;
            options.MaxMatchingFiles = maxMatchingFiles;

            return(true);
        }