Path: redb-route/redb.Route.GenericFile/GenericFileUtils.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.GenericFile/GenericFileUtils.cs ---- using redb.Route.Expressions; using System.Text.RegularExpressions; namespace redb.Route.GenericFile; /// /// Shared utilities for file-based transports: glob matching, done-file resolution. /// public static class GenericFileUtils { /// /// Ant-style path matching, as Apache Camel's antInclude/antExclude use it: /// ? is one character, * matches within a single path segment and stops at a /// separator, and ** spans any number of segments. Several patterns are separated by /// commas, and the path is matched with / as the separator whatever the transport wrote. /// /// This is deliberately not with a longer input: there * becomes /// .* and crosses separators, so */x.csv and **/x.csv would mean the same /// thing and a pattern could never name one level. /// /// /// Path relative to the polled directory (e.g. "TYPE_A/outbox/a.csv"). /// One or more comma-separated Ant patterns. /// Whether matching respects case (Camel's antFilterCaseSensitive, default true). /// True when any pattern matches the path. public static bool AntMatch(string relativePath, string pattern, bool caseSensitive = true) { ArgumentNullException.ThrowIfNull(relativePath); ArgumentNullException.ThrowIfNull(pattern); var path = relativePath.Replace('\\', '/').TrimStart('/'); foreach (var single in pattern.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) { var regex = AntPatternCache.GetOrAdd((single, caseSensitive), static key => BuildAntRegex(key.Pattern, key.CaseSensitive)); if (regex.IsMatch(path)) return true; } return false; } // One compiled Regex per (pattern, case) pair: a poll runs the same handful of patterns over // every file it listed, and a directory filter runs them again per directory. private static readonly System.Collections.Concurrent.ConcurrentDictionary<(string Pattern, bool CaseSensitive), Regex> AntPatternCache = new(); private static Regex BuildAntRegex(string pattern, bool caseSensitive) { var normalized = pattern.Replace('\\', '/').TrimStart('/'); var sb = new System.Text.StringBuilder("^"); for (var i = 0; i < normalized.Length; i++) { var c = normalized[i]; if (c == '*') { var isDouble = i + 1 < normalized.Length && normalized[i + 1] == '*'; if (isDouble) { i++; // "**/" also matches zero segments, so "**/x.csv" matches "x.csv" at the root. if (i + 1 < normalized.Length && normalized[i + 1] == '/') { i++; sb.Append("(?:.*/)?"); } else { sb.Append(".*"); } } else { sb.Append("[^/]*"); } } else if (c == '?') { sb.Append("[^/]"); } else { sb.Append(Regex.Escape(c.ToString())); } } sb.Append('$'); var options = RegexOptions.Compiled | (caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); return new Regex(sb.ToString(), options); } /// /// Simple glob matching supporting * and ? wildcards. /// Supports comma-separated patterns: "*.csv,*.json". /// /// File name to test. /// Glob pattern (e.g. "*.csv" or "*.csv,*.json"). /// True if the input matches the pattern. public static bool GlobMatch(string input, string pattern) { ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(pattern); // Support comma-separated patterns: "*.csv,*.json" if (pattern.Contains(',')) { return pattern.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) .Any(p => GlobMatch(input, p)); } var regexPattern = "^" + Regex.Escape(pattern) .Replace("\\*", ".*") .Replace("\\?", ".") + "$"; return Regex.IsMatch(input, regexPattern, RegexOptions.IgnoreCase); } /// /// Tests whether a already-normalized path is the base directory itself or lives underneath it. /// Used by producers to keep a caller-supplied file name from escaping the endpoint directory. /// /// Base directory. A trailing separator is ignored. /// Candidate path. Must already be normalized (no "..", no "." segments). /// Path separator of the transport ('/' for remote, OS separator for local). /// Comparison to use. Remote paths are case-sensitive; local ones follow the OS. /// True when the candidate stays inside the base directory. /// /// The separator is part of the comparison on purpose: a plain prefix test would accept /// "/data/out2/x" as living inside "/data/out". /// public static bool IsWithinDirectory( string basePath, string candidatePath, char separator, StringComparison comparison) { ArgumentNullException.ThrowIfNull(basePath); ArgumentNullException.ThrowIfNull(candidatePath); var root = basePath.TrimEnd(separator); if (root.Length == 0) return true; // the whole file system is the base return candidatePath.Equals(root, comparison) || candidatePath.StartsWith(root + separator, comparison); } /// /// Substitutes the file keys of Apache Camel's file language (${file:name}, ${file:name.noext}, /// ${file:ext}, ${file:parent} and the rest of ) in a pattern of a /// consumer option. Keys match ignoring case, as these options always have (${FILE:NAME}). /// /// The file the option is resolved for (). /// Pattern to substitute into. Returned unchanged when it holds no keys. /// The pattern with the file keys replaced. /// /// Only file keys are substituted. Exchange-level expressions (${header.*}, ${body}) cannot be used /// here: these patterns are resolved before the exchange exists, or while it is being disposed. /// /// A key is not a file key; reports it earlier. public static string SubstituteFileTokens(IFileFacts facts, string pattern) { ArgumentNullException.ThrowIfNull(facts); ArgumentNullException.ThrowIfNull(pattern); return FileLanguage.Substitute(pattern, facts, StringComparison.OrdinalIgnoreCase); } /// /// The compatibility form of for a caller that has only the /// file name: the keys that need the path, the size or the time write nothing. /// /// File name with extension (e.g. "order.csv"). /// Pattern to substitute into. Returned unchanged when it holds no keys. /// File operations for path helpers. /// The pattern with the file keys replaced. public static string SubstituteFileTokens(string fileName, string pattern, IFileOperations ops) { ArgumentNullException.ThrowIfNull(fileName); ArgumentNullException.ThrowIfNull(pattern); ArgumentNullException.ThrowIfNull(ops); return SubstituteFileTokens(new GenericFileFacts(fileName, "", null, ops), pattern); } /// /// Checks the file keys in a consumer option when the endpoint is created: a key that is not a file key would /// otherwise surface only when the first file arrives (before 4.7.0 it was left in the path as written). /// /// The option name, for the message (moveTo). /// The option value; empty or null passes. /// A key is not a file key; the message lists the keys. public static void ValidateFileKeys(string option, string? pattern) { if (string.IsNullOrEmpty(pattern)) return; if (FileLanguage.FindUnknownKey(pattern, StringComparison.OrdinalIgnoreCase) is { } key) throw new InvalidOperationException($"{option}='{pattern}': {FileLanguage.UnknownKeyMessage(key)}"); } /// /// Resolves a done-file name pattern by substituting the file keys (${file:name}, ${file:name.noext} /// and the rest of ). /// /// The file to resolve the done-file name for. /// The pattern (e.g. "${file:name}.done"). /// File operations for path helpers. /// Resolved done-file path. public static string ResolveDoneFileName(GenericFileInfo file, string doneFilePattern, IFileOperations ops) { ArgumentNullException.ThrowIfNull(file); ArgumentNullException.ThrowIfNull(doneFilePattern); ArgumentNullException.ThrowIfNull(ops); var pattern = SubstituteFileTokens(new GenericFileFacts(file, file.FullPath, ops), doneFilePattern); if (ops.IsAbsolutePath(pattern)) return pattern; var parentDir = ops.GetParentPath(file.FullPath); return ops.CombinePath(parentDir, pattern); } }