// SPDX-FileCopyrightText: 2026 Progmasoft // SPDX-License-Identifier: MIT using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Progmasoft.Tazel.Dsl.Configuration; using Progmasoft.Tazel.Dsl.Custom; using Progmasoft.Tazel.Output; namespace Progmasoft.Tazel.Project.Ignore; /// What is wrong with a .tazelignore, with where it is when it has a place. public sealed class IgnoreException : Exception { /// A problem with no place in a file. public IgnoreException(string message) : base(message) { } /// A problem at a line of a file. public IgnoreException(Diagnostic diagnostic) : base(diagnostic?.Plain) { Diagnostic = diagnostic; } /// Nothing to say. public IgnoreException() { } /// What is wrong, and why. public IgnoreException(string message, Exception inner) : base(message, inner) { } /// Where the problem is, when it is in a file. public Diagnostic? Diagnostic { get; } } /// One rule: a gitignore pattern or a regex:, compiled, with whether it ignores or keeps. /// The line as written, for messages. /// What a path relative to the rule's directory must match, whole. /// Whether it keeps what an earlier rule ignored (!). /// Whether it matches directories only (a trailing /). /// The file and line it was read from. internal sealed record IgnoreRule(string Text, Regex Pattern, bool Negated, bool DirectoryOnly, string Place); /// /// The rules of one .tazelignore, with the files it includes and imports in their places. Lines are gitignore /// rules, except these, which no gitignore line can be without a backslash before it: /// pragma:once, import:<file>, import:"file", include:…, regex:… and /// !regex:…. A rule that means a name starting with one of these words is written \pragma:…, as gitignore /// itself reads it. /// internal static class IgnoreFile { /// The name of the file. public static string FileName { get; } = ".tazelignore"; /// How long one regex: may take on one path. public static TimeSpan RegexTimeout { get; } = TimeSpan.FromSeconds(1); private static readonly string[] Reserved = ["pragma:", "import:", "include:", "regex:", "!regex:"]; /// Whether a gitignore line starts with a word Tazel reads as a directive, so it needs a backslash. public static bool NeedsEscape(string line) => Reserved.Any(word => line.StartsWith(word, StringComparison.Ordinal)); /// /// The rules of , read from , with includes followed; a problem is an /// at its line. /// public static IReadOnlyList Read(string file, string text) => new Reader().Root(file, text); private sealed class Reader { private readonly List _rules = []; private readonly HashSet _once = new(StringComparer.Ordinal); private readonly HashSet _loaded = new(StringComparer.Ordinal); private readonly List _chain = []; public IReadOnlyList Root(string file, string text) { Load(Path.GetFullPath(file), text); return _rules; } private void Load(string file, string text) { var canonical = ConfigurationResolver.Canonical(file); _chain.Add(canonical); _loaded.Add(canonical); var lines = text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n'); var first = true; for (var number = 1; number <= lines.Length; number++) { var line = lines[number - 1]; if (line.Length == 0 || line.StartsWith('#')) { continue; } if (line == "pragma:once") { if (!first) { throw Fail(file, text, number, "pragma:once must come first in its file", "move it above every rule"); } _once.Add(canonical); } else if (line.StartsWith("pragma:", StringComparison.Ordinal)) { throw Fail(file, text, number, $"'{line}' is not a pragma; pragma:once is the only one", $"for a name that starts with pragma:, write \\{line}"); } else if (line.StartsWith("import:", StringComparison.Ordinal) || line.StartsWith("include:", StringComparison.Ordinal)) { Include(file, text, number, line); } else { _rules.Add(Rule(file, text, number, line)); } first = false; } _chain.RemoveAt(_chain.Count - 1); } private void Include(string file, string text, int number, string line) { var import = line.StartsWith("import:", StringComparison.Ordinal); var argument = line[(line.IndexOf(':', StringComparison.Ordinal) + 1)..]; var (path, global) = argument switch { ['<', .. var inner, '>'] when inner.Length > 0 => (new string(inner), true), ['"', .. var inner, '"'] when inner.Length > 0 => (new string(inner), false), _ => throw Fail(file, text, number, $"'{line}' needs one path, in quotes or in angle brackets", "write include:\"file\" for a file beside this one, or include: for one of TAZEL_HOME's Include/Ignore"), }; if (ConfigurationResolver.Refusal(path, global) is { } refusal) { throw Fail(file, text, number, $"'{path}' {refusal}", null); } var target = global ? Global(file, text, number, path) : Path.GetFullPath(Path.Combine(Path.GetDirectoryName(file)!, path)); if (!File.Exists(target)) { throw Fail(file, text, number, $"{path} is not a file{(global ? " of TAZEL_HOME's Include/Ignore" : " beside this one")}", null); } var canonical = ConfigurationResolver.Canonical(target); if (_once.Contains(canonical) || (import && _loaded.Contains(canonical))) { return; } if (_chain.Contains(canonical)) { throw Fail(file, text, number, $"{path} includes itself: {string.Join(" -> ", _chain.Select(Path.GetFileName))} -> {path}", "read it once with import:, or begin it with pragma:once"); } if (_chain.Count >= ConfigurationParser.MaxDepth || _loaded.Count >= ConfigurationResolver.MaxFiles) { throw Fail(file, text, number, $"includes nest more than {ConfigurationParser.MaxDepth} deep, or read more than {ConfigurationResolver.MaxFiles} files", null); } if (import) { _once.Add(canonical); } Load(target, File.ReadAllText(target)); } // A file below TAZEL_HOME/Include/Ignore, which no link may leave. private static string Global(string file, string text, int number, string path) { string root; try { root = ConfigurationResolver.Canonical(ConfigurationResolver.IncludeRoot(ConfigurationFamily.Ignore)); } catch (ConfigurationHomeException error) { throw Fail(file, text, number, error.Message, null); } var full = Path.GetFullPath(Path.Combine(root, path)); if (File.Exists(full) && !ConfigurationResolver.Canonical(full).StartsWith(root + Path.DirectorySeparatorChar, StringComparison.Ordinal)) { throw Fail(file, text, number, $"'{path}' leaves {root} through a link", null); } return full; } } // One rule line: regex:, !regex:, or a gitignore pattern. private static IgnoreRule Rule(string file, string text, int number, string line) { var place = $"{file}:{number}"; foreach (var (prefix, negated) in new[] { ("regex:", false), ("!regex:", true) }) { if (line.StartsWith(prefix, StringComparison.Ordinal)) { var expression = line[prefix.Length..]; try { return new IgnoreRule(line, new Regex(expression, RegexOptions.CultureInvariant, RegexTimeout), negated, false, place); } catch (ArgumentException error) { throw Fail(file, text, number, $"'{expression}' is not a regular expression: {error.Message}", "fix the expression; it is .NET's Regex"); } } } var glob = Gitignore.Parse(line); return glob is null ? new IgnoreRule(line, new Regex("(?!)", RegexOptions.None, RegexTimeout), false, false, place) : new IgnoreRule(line, glob.Value.Pattern, glob.Value.Negated, glob.Value.DirectoryOnly, place); } private static IgnoreException Fail(string file, string text, int number, string message, string? help) => new(Diagnostic.At(ErrorCodes.IgnoreInvalid, text, file, new Place(number, 1, Math.Max(1, LineLength(text, number))), message, "this line", help, "Tazel ignores many things, but not a line it cannot read.")); private static int LineLength(string text, int number) => text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n').ElementAtOrDefault(number - 1)?.Length ?? 1; } /// gitignore patterns, compiled to regular expressions that match a path relative to the file's directory. internal static class Gitignore { /// /// The pattern of , or null for a line that is no rule (only spaces, or a lone !). /// Trailing spaces go unless a backslash keeps them; ! negates, \! and \# are literal; a /// trailing / matches directories only; a / elsewhere anchors the pattern to the file's directory, /// and without one it matches at any depth. *, ? and [...] stop at /; ** as a /// whole part matches any number of directories. /// public static (Regex Pattern, bool Negated, bool DirectoryOnly)? Parse(string line) { var pattern = TrimTrailingSpaces(line); var negated = pattern.StartsWith('!'); if (negated) { pattern = pattern[1..]; } var directoryOnly = pattern.EndsWith('/') && !pattern.EndsWith("\\/", StringComparison.Ordinal); if (directoryOnly) { pattern = pattern.TrimEnd('/'); } if (pattern.Length == 0) { return null; } var anchored = pattern.Contains('/', StringComparison.Ordinal); pattern = pattern.TrimStart('/'); var body = Body(pattern); var expression = anchored ? $"^{body}$" : $"^(?:.*/)?{body}$"; return (new Regex(expression, RegexOptions.CultureInvariant, IgnoreFile.RegexTimeout), negated, directoryOnly); } private static string TrimTrailingSpaces(string line) { var end = line.Length; while (end > 0 && line[end - 1] == ' ' && !(end >= 2 && line[end - 2] == '\\')) { end--; } return line[..end]; } // The pattern as a regular expression, part by part. private static string Body(string pattern) { var parts = pattern.Split('/'); var result = new StringBuilder(); for (var i = 0; i < parts.Length; i++) { var last = i == parts.Length - 1; if (parts[i] == "**") { // Leading or middle: any directories, none too; trailing: everything below. result.Append(last ? ".*" : "(?:[^/]+/)*"); continue; } result.Append(PartExpression(parts[i])); if (!last) { result.Append('/'); } } return result.ToString(); } // One part of a path, between slashes, as a regular expression; each step says how far it read. private static string PartExpression(string part) { var result = new StringBuilder(); var i = 0; while (i < part.Length) { var letter = part[i]; if (letter == '\\' && i + 1 < part.Length) { result.Append(Regex.Escape(part[i + 1].ToString())); i += 2; } else if (letter == '*') { // Stars in a row match what one star matches. while (i < part.Length && part[i] == '*') { i++; } result.Append("[^/]*"); } else if (letter == '?') { result.Append("[^/]"); i++; } else if (letter == '[' && Class(part, i) is { } found) { result.Append(found.Expression); i = found.End + 1; } else { result.Append(Regex.Escape(letter.ToString())); i++; } } return result.ToString(); } // [abc], [a-z], [!x] or [^x] from start; null when it has no closing ], so the [ is literal. private static (string Expression, int End)? Class(string part, int start) { var i = start + 1; var negated = i < part.Length && part[i] is '!' or '^'; if (negated) { i++; } var members = new StringBuilder(); var firstMember = true; for (; i < part.Length; i++) { var letter = part[i]; if (letter == ']' && !firstMember) { return ($"(?![/])[{(negated ? "^" : "")}{members}]", i); } if (letter == '\\' && i + 1 < part.Length) { letter = part[++i]; members.Append('\\').Append(letter); } else { members.Append(letter is '-' ? "-" : letter is '[' or '^' or ']' ? "\\" + letter : letter); } firstMember = false; } return null; } }