tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Add .tazelignore and the tazel ignore commands
- Commit
8a6769fd90a9eeafada4b665d36fad2ace6918ba- Author
- Leitwolf11 ·
- Parents
802e9549ff91
Changes
CHANGELOG.md | 4 + docs/commands.md | 34 ++ src/Progmasoft.Tazel/Archive/ModuleArchive.cs | 6 + src/Progmasoft.Tazel/Cli/CommandLine.cs | 15 +- src/Progmasoft.Tazel/Cli/Commands.cs | 3 +- src/Progmasoft.Tazel/Cli/Help.cs | 18 + src/Progmasoft.Tazel/Cli/IgnoreCommands.cs | 226 ++++++++++++ src/Progmasoft.Tazel/Cli/MoreCommands.cs | 2 +- src/Progmasoft.Tazel/Cli/Query.cs | 3 +- src/Progmasoft.Tazel/Cli/Selector.cs | 5 +- .../Dsl/Configuration/ConfigurationResolver.cs | 49 +-- src/Progmasoft.Tazel/Output/ErrorCodes.cs | 8 + src/Progmasoft.Tazel/Program.cs | 11 + src/Progmasoft.Tazel/Project/FileSets.cs | 13 +- src/Progmasoft.Tazel/Project/Ignore/IgnoreFile.cs | 385 +++++++++++++++++++++ src/Progmasoft.Tazel/Project/Ignore/IgnoreRules.cs | 117 +++++++ src/Progmasoft.Tazel/Project/ModuleFiles.cs | 43 ++- src/Progmasoft.Tazel/Project/Workspace.cs | 91 ++++- tests/Progmasoft.Tazel.Tests/IgnoreTests.cs | 295 ++++++++++++++++ 19 files changed, 1287 insertions(+), 41 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b3691e..3c825d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ ## Unreleased +- `.tazelignore`: gitignore rules, `regex:` and `!regex:`, `pragma:once`, `import:` and `include:`, nested per + directory, for package discovery, patterns, source globs and module archives; explicit paths and labels are never + ignored. `tazel ignore create-from|validate|add|delete|del`. Error `E0013`. + - `--recompile` and `--no-cache` for `build`, `run`, `test` and `coverage`: every compilation runs, or every action and test runs with no cache read or written. zig compiles again with an empty cache of its own. diff --git a/docs/commands.md b/docs/commands.md index 0a1f6a4..5ff5987 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -221,6 +221,40 @@ tazel dotnet what-is CLI .NET, CLI (the Common Language Infrastructure), CIL, CLR, C++/CLI, C#, WorkstationGC, BackgroundGC, daemon, CTS, VES and ECMA-335, offline. Tazel has no daemon: `tazel dotnet start-daemon` and the like say so. +## .tazelignore + +```gitignore +pragma:once +import:<common.ignore.txt> +include:"config/build.ignore.txt" +*.tmp +**/generated/ +!important.log +regex:^src/.*\.generated\.cpp$ +!regex:^src/required\.generated\.cpp$ +``` + +A `.tazelignore` holds gitignore rules: comments, `*`, `**`, `?`, `[...]`, anchoring with `/`, a trailing `/` for +directories, `\` escapes, `!` negation, trailing spaces dropped unless escaped, the last matching rule deciding, and +nothing inside an ignored directory brought back. A file applies to its directory and below, after the files above +it. `regex:` and `!regex:` take a .NET regular expression over the path relative to the file's directory, with `/` +between its parts; it must compile and finish within a second on a path. `pragma:once`, `import:` and `include:` read +other files as the directives of the text files do, `<file>` below `$TAZEL_HOME/Include/Ignore/`; there are no +conditions. A gitignore rule that starts with one of these words takes a backslash: `\regex:name`. A `.gitignore` is +not read. + +The rules apply to package discovery, `//...` and the other patterns, source globs and module archives. A path or a +label named explicitly is never ignored: a package that `Depends` or the command line names is loaded from its own +directory, without searching ignored ones, and patterns still leave it out. Hidden directories, `.tazel` among them, +are left out before any rule. + +```text +tazel ignore create-from .gitignore # ./.tazelignore from a gitignore file, never over one +tazel ignore validate # every .tazelignore of the module, ignored directories too +tazel ignore add '*.log' # appended to ./.tazelignore unless it is there already +tazel ignore del '*.log' # every line that is the pattern as written; delete is the same +``` + ## External tools ```text diff --git a/src/Progmasoft.Tazel/Archive/ModuleArchive.cs b/src/Progmasoft.Tazel/Archive/ModuleArchive.cs index a68c21d..3ae1459 100644 --- a/src/Progmasoft.Tazel/Archive/ModuleArchive.cs +++ b/src/Progmasoft.Tazel/Archive/ModuleArchive.cs @@ -40,6 +40,7 @@ internal static class ModuleArchive { ArgumentNullException.ThrowIfNull(excluded); var found = new List<string>(); + var ignore = Project.Ignore.IgnoreRules.For(root); Visit(new DirectoryInfo(root), ""); found.Sort(StringComparer.Ordinal); return found; @@ -54,6 +55,11 @@ internal static class ModuleArchive } var relative = prefix + entry.Name; + if (ignore.Ignored(relative, entry is DirectoryInfo)) + { + continue; + } + if (entry.LinkTarget is not null) { throw new ProjectException($"{relative} is a symbolic link; an archive holds only files"); diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs index 32ca366..d97366d 100644 --- a/src/Progmasoft.Tazel/Cli/CommandLine.cs +++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs @@ -145,7 +145,7 @@ internal static class CommandLine /// <summary>The commands, as <c>tazel help</c> lists them.</summary> public static IReadOnlyList<string> Commands { get; } = ["build", "run", "test", "coverage", "query", "cquery", "aquery", "fetch", "vendor", "clean", "package", "custom", - "portal-modules", "cache", "explain", "version", "help", "dotnet", "limited-time", "options", "custom-cmds", "envs", "tool"]; + "portal-modules", "cache", "explain", "version", "help", "dotnet", "limited-time", "options", "custom-cmds", "envs", "tool", "ignore"]; private enum Kind { @@ -339,6 +339,7 @@ internal static class CommandLine ["dotnet"] = MakeDaemon, ["options"] = MakeOptions, ["tool"] = MakeTool, + ["ignore"] = MakeIgnore, ["custom-cmds"] = (scanned, output) => MakeValidate(scanned, output, ConfigurationKind.Custom), ["envs"] = (scanned, output) => MakeValidate(scanned, output, ConfigurationKind.Envs), ["cache"] = MakeCache, @@ -401,6 +402,18 @@ internal static class CommandLine }; } + private static Command MakeIgnore(Scanned scanned, OutputOptions output) => scanned.Positional switch + { + ["validate"] => new IgnoreCommand(output, "validate", null), + ["create-from" or "add", var argument] => new IgnoreCommand(output, scanned.Positional[0], argument), + ["delete" or "del", var argument] => new IgnoreCommand(output, "delete", argument), + [var action, ..] when action is "create-from" or "add" or "delete" or "del" => + throw new CommandLineException($"tazel ignore {action} takes one {(action == "create-from" ? "path" : "pattern")}; quote a pattern with spaces"), + _ => throw new CommandLineException("tazel ignore takes create-from <path>, validate, add <pattern>, delete <pattern> or del <pattern>" + + (scanned.Positional.Count > 0 && Suggestions.Nearest(scanned.Positional[0], ["create-from", "validate", "add", "delete"]) is { } near + ? $"; did you mean {near}?" : "")), + }; + private static Command MakeTool(Scanned scanned, OutputOptions output) { var positional = scanned.Positional; diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index 7b049cd..a238ede 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -44,6 +44,7 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector PackageCommand => PackageAsync(), CustomCommandLine custom => CustomAsync(custom, cancel), ToolLaunchCommand tool => Task.FromResult(LaunchTool(tool)), + IgnoreCommand ignore => Task.FromResult(new IgnoreCommands(reporter, workingDirectory).Run(ignore)), ToolWrapperCommand wrapper => Task.FromResult(CreateWrapper(wrapper)), OptionsCommand options => Task.FromResult(new ConfigurationCommands(reporter, workingDirectory).Options(options)), ValidateCommand validate => Task.FromResult(new ConfigurationCommands(reporter, workingDirectory).Validate(validate.Kind, validate.Scope)), @@ -340,7 +341,7 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector var mode = flags.Mode ?? BuildMode.Debug; reporter.Status($"loading the module for {platform.Name()}, {mode.ToString().ToLowerInvariant()}"); var workspace = await Workspace.LoadAsync(workingDirectory, new BuildContext(mode, platform), TazelVersion, - reporter.Status).ConfigureAwait(false); + reporter.Status, labels).ConfigureAwait(false); WarnAboutWhatThisTazelDoesNotDo(workspace.Main.Globals); var buildOptions = OptionsOf(flags, workspace.Main.Globals.execution?.Settings, kind, platform, mode); var selected = Select(new Selector(workspace, platform), labels, kind, platform); diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index a2b01f3..efdb523 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -214,6 +214,24 @@ internal static class Help --algorithm ed25519|rsa-4096|ml-dsa the algorithm; default: ed25519. ml-dsa is ML-DSA-65 (FIPS 204). """), + ["ignore"] = new("tazel ignore create-from|validate|add|delete: the .tazelignore of this directory.", """ + tazel ignore create-from <path> + tazel ignore validate + tazel ignore add <pattern> + tazel ignore delete|del <pattern> + + A .tazelignore holds gitignore rules, and regex:EXPRESSION or !regex:EXPRESSION for a .NET regular + expression over the path relative to its directory; pragma:once, import:<file>, import:"file", + include:<file> and include:"file" read other files in place. It applies to its directory and below, to + package discovery, //..., source globs and the archives of modules; a path or label named explicitly is + never ignored. A .gitignore is not read. + + create-from writes ./.tazelignore from a gitignore file, never over one, and leaves the source as it was; a + line that starts with a word above takes a backslash, so it means what it meant for git. validate reads every + .tazelignore of the module, those of ignored directories too, and runs nothing. add appends a rule to + ./.tazelignore, which must exist, unless it is there already; delete and del remove every line that is the + pattern as written. + """), ["tool"] = new("tazel tool launch|create-wrapper: runs tazel-<name> tools, or writes a wrapper for a program.", """ tazel tool launch <name> [arguments] tazel tool create-wrapper <name> [-o <dir> | --output-dir <dir>] diff --git a/src/Progmasoft.Tazel/Cli/IgnoreCommands.cs b/src/Progmasoft.Tazel/Cli/IgnoreCommands.cs new file mode 100644 index 0000000..4bbef0a --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/IgnoreCommands.cs @@ -0,0 +1,226 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using Progmasoft.Tazel.Dsl.Configuration; +using Progmasoft.Tazel.Output; +using Progmasoft.Tazel.Project; +using Progmasoft.Tazel.Project.Ignore; + +namespace Progmasoft.Tazel.Cli; + +/// <summary><c>tazel ignore create-from|validate|add|delete|del</c>.</summary> +internal sealed record IgnoreCommand(OutputOptions Output, string Action, string? Argument) : Command(Output); + +/// <summary> +/// The commands of <c>.tazelignore</c>. <c>validate</c> reads; <c>create-from</c> makes the file of the current +/// directory, never over one; <c>add</c> and <c>delete</c> edit only that file, which must exist, keeping its other +/// lines, under a lock, writing beside it and moving the new text into place. +/// </summary> +internal sealed class IgnoreCommands(Reporter reporter, string workingDirectory) +{ + private string Here => Path.Combine(workingDirectory, IgnoreFile.FileName); + + public int Run(IgnoreCommand command) => command.Action switch + { + "create-from" => CreateFrom(command.Argument!), + "validate" => Validate(), + "add" => Add(command.Argument!), + _ => Delete(command.Argument!), + }; + + /// <summary> + /// A <c>.tazelignore</c> here with the rules of a gitignore file, which is read and left as it is. A line that + /// starts with a word Tazel reads as a directive takes a backslash, so it means for Tazel what it meant for git. + /// </summary> + private int CreateFrom(string source) + { + var from = Path.GetFullPath(source, workingDirectory); + string text; + try + { + text = File.ReadAllText(from, new UTF8Encoding(false, throwOnInvalidBytes: true)); + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException or DecoderFallbackException) + { + throw new IgnoreException($"{source} cannot be read as a gitignore file: {error.Message}", error); + } + + if (text.Contains('\0', StringComparison.Ordinal)) + { + throw new IgnoreException($"{source} holds a NUL character; a gitignore file is text"); + } + + var newline = text.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n"; + var lines = text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n') + .Select(line => IgnoreFile.NeedsEscape(line) ? (line.StartsWith('!') ? "!\\" + line[1..] : "\\" + line) : line); + var converted = string.Join(newline, lines); + IgnoreFile.Read(Here, converted); + try + { + using var stream = new FileStream(Here, FileMode.CreateNew, FileAccess.Write, FileShare.None); + stream.Write(new UTF8Encoding(false).GetBytes(converted)); + } + catch (IOException error) when (File.Exists(Here)) + { + throw new IgnoreException($"{IgnoreFile.FileName} is already here; Tazel does not overwrite it", error); + } + + reporter.Success($"wrote {IgnoreFile.FileName} from {source}"); + return 0; + } + + /// <summary> + /// Reads every <c>.tazelignore</c> of the module, those of ignored directories too, with the files they include, + /// and compiles every rule; nothing is matched or run. + /// </summary> + private int Validate() + { + var root = ModuleFiles.RootOf(workingDirectory) ?? workingDirectory; + var files = new List<string>(); + Collect(new DirectoryInfo(root), files, top: true); + if (files.Count == 0) + { + reporter.Plain($"no {IgnoreFile.FileName} in this module; there is nothing to check"); + return 0; + } + + foreach (var file in files) + { + var rules = IgnoreFile.Read(file, File.ReadAllText(file)); + reporter.Plain($"valid: {Path.GetRelativePath(workingDirectory, file).Replace('\\', '/')} ({rules.Count} rule{(rules.Count == 1 ? "" : "s")})"); + } + + return 0; + } + + // Every ignore file of the module below directory: hidden directories, links and other modules are not entered. + private static void Collect(DirectoryInfo directory, List<string> files, bool top) + { + if (!top && File.Exists(Path.Combine(directory.FullName, ModuleFiles.ModuleFile))) + { + return; + } + + var file = Path.Combine(directory.FullName, IgnoreFile.FileName); + if (File.Exists(file)) + { + files.Add(file); + } + + foreach (var child in directory.EnumerateDirectories().OrderBy(d => d.Name, StringComparer.Ordinal)) + { + if (!child.Name.StartsWith('.') && child.LinkTarget is null) + { + Collect(child, files, top: false); + } + } + } + + /// <summary>Adds a rule at the end of the file here; a rule already there as written is left, and said so.</summary> + private int Add(string pattern) + { + CheckRule(pattern); + return Edit(lines => + { + if (lines.Contains(pattern, StringComparer.Ordinal)) + { + reporter.Plain($"'{pattern}' is already in {IgnoreFile.FileName}; nothing changed"); + return null; + } + + lines.Add(pattern); + reporter.Success($"added '{pattern}' to {IgnoreFile.FileName}"); + return lines; + }); + } + + /// <summary>Deletes every line that is <paramref name="pattern"/> as written; no pattern is matched or run.</summary> + private int Delete(string pattern) => Edit(lines => + { + var removed = lines.RemoveAll(line => line == pattern); + if (removed == 0) + { + throw new IgnoreException($"'{pattern}' is not a line of {IgnoreFile.FileName}; delete takes a line exactly as written"); + } + + reporter.Success($"deleted '{pattern}' from {IgnoreFile.FileName}{(removed > 1 ? $" ({removed} lines)" : "")}"); + return lines; + }); + + // A line add takes: one line, a rule and not a directive of includes, valid as the file would read it. + private void CheckRule(string pattern) + { + if (pattern.Length == 0 || pattern.Contains('\n', StringComparison.Ordinal) || pattern.Contains('\r', StringComparison.Ordinal)) + { + throw new IgnoreException("tazel ignore add takes one rule on one line"); + } + + if (pattern.StartsWith('#') || pattern.StartsWith("pragma:", StringComparison.Ordinal) || + pattern.StartsWith("import:", StringComparison.Ordinal) || pattern.StartsWith("include:", StringComparison.Ordinal)) + { + throw new IgnoreException($"'{pattern}' is not a rule; tazel ignore add adds patterns and regex: rules, and edits no directive"); + } + + IgnoreFile.Read(Here, pattern); + } + + // The file here, edited by change under a lock; change returns null for no change. + private int Edit(Func<List<string>, List<string>?> change) + { + if (!File.Exists(Here)) + { + throw new IgnoreException($"there is no {IgnoreFile.FileName} here; make one, or tazel ignore create-from a gitignore file"); + } + + using var held = Lock(Here); + var text = File.ReadAllText(Here); + var newline = text.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n"; + var lines = text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n').ToList(); + var endsWithNewline = lines.Count > 1 && lines[^1].Length == 0; + if (endsWithNewline) + { + lines.RemoveAt(lines.Count - 1); + } + + var changed = change(lines); + if (changed is null) + { + return 0; + } + + var updated = string.Join(newline, changed) + (endsWithNewline || text.Length == 0 ? newline : ""); + IgnoreFile.Read(Here, updated); + var partial = $"{Here}.{Guid.NewGuid():N}.partial"; + File.WriteAllText(partial, updated, new UTF8Encoding(false)); + File.Move(partial, Here, overwrite: true); + return 0; + } + + private static FileStream Lock(string file) + { + var locks = Path.Combine(TazelHome.Directory(), "Locks"); + Directory.CreateDirectory(locks); + var name = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(Path.GetFullPath(file))))[..16]; + var path = Path.Combine(locks, $"ignore-{name}.lock"); + const int Attempts = 100; + for (var attempt = 1; attempt < Attempts; attempt++) + { + try + { + return new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + } + catch (IOException) + { + System.Threading.Thread.Sleep(50); + } + } + + return new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + } +} diff --git a/src/Progmasoft.Tazel/Cli/MoreCommands.cs b/src/Progmasoft.Tazel/Cli/MoreCommands.cs index aa132c4..91e0e37 100644 --- a/src/Progmasoft.Tazel/Cli/MoreCommands.cs +++ b/src/Progmasoft.Tazel/Cli/MoreCommands.cs @@ -31,7 +31,7 @@ internal sealed partial class Commands var platform = query.Flags.Platform ?? options.Platform ?? Host.Platform; var mode = query.Flags.Mode ?? BuildMode.Debug; var workspace = await Workspace.LoadAsync(workingDirectory, new BuildContext(mode, platform), TazelVersion, - reporter.Status).ConfigureAwait(false); + reporter.Status, [query.Expression]).ConfigureAwait(false); var current = CurrentPackage(workspace); var targets = new Query(workspace, current).Evaluate(query.Expression); var configuration = $"{platform.Name()}-{mode.ToString().ToLowerInvariant()}"; diff --git a/src/Progmasoft.Tazel/Cli/Query.cs b/src/Progmasoft.Tazel/Cli/Query.cs index c3af743..a0d7d7b 100644 --- a/src/Progmasoft.Tazel/Cli/Query.cs +++ b/src/Progmasoft.Tazel/Cli/Query.cs @@ -211,7 +211,8 @@ internal sealed class Query(Workspace workspace, PackageId current) TargetLabel label => workspace.Targets.TryGetValue(label, out var target) ? [target] : throw new ProjectException($"{label} is not a target"), - PackagePattern pattern => workspace.Targets.Values.Where(target => pattern.Covers(target.Label.Package)).ToHashSet(), + PackagePattern pattern => workspace.Targets.Values + .Where(target => pattern.Covers(target.Label.Package) && !workspace.IgnoredPackages.Contains(target.Label.Package)).ToHashSet(), _ => [], }; } diff --git a/src/Progmasoft.Tazel/Cli/Selector.cs b/src/Progmasoft.Tazel/Cli/Selector.cs index 7332398..9c4e2a1 100644 --- a/src/Progmasoft.Tazel/Cli/Selector.cs +++ b/src/Progmasoft.Tazel/Cli/Selector.cs @@ -63,12 +63,13 @@ internal sealed class Selector(Workspace workspace, Platform platform) } else if (selection is PackagePattern pattern) { - if (!workspace.Packages.Any(pattern.Covers)) + bool Covers(PackageId package) => pattern.Covers(package) && !workspace.IgnoredPackages.Contains(package); + if (!workspace.Packages.Any(Covers)) { throw new ProjectException($"{pattern} names no package"); } - AddPattern(selected, target => pattern.Covers(target.Label.Package), wanted); + AddPattern(selected, target => Covers(target.Label.Package), wanted); } } diff --git a/src/Progmasoft.Tazel/Dsl/Configuration/ConfigurationResolver.cs b/src/Progmasoft.Tazel/Dsl/Configuration/ConfigurationResolver.cs index 0dedfd3..ab70f1d 100644 --- a/src/Progmasoft.Tazel/Dsl/Configuration/ConfigurationResolver.cs +++ b/src/Progmasoft.Tazel/Dsl/Configuration/ConfigurationResolver.cs @@ -23,6 +23,9 @@ public enum ConfigurationFamily /// <summary><c>tazel_envs.txt</c>.</summary> Envs, + + /// <summary><c>.tazelignore</c>.</summary> + Ignore, } /// <summary> @@ -79,6 +82,29 @@ public static class ConfigurationResolver internal static string IncludeRoot(ConfigurationFamily family) => Path.Combine(TazelHome.Directory(), "Include", family.ToString()); + // Why a path is not taken as written, or null when it is. + internal static string? Refusal(string path, bool global) + { + if (path.IndexOfAny(['*', '?', '[', ']']) >= 0) + { + return "has a wildcard; name one file"; + } + + if (path.Contains("://", StringComparison.Ordinal)) + { + return "is a URL; Tazel includes files of this machine only"; + } + + if (Path.IsPathRooted(path) || (path.Length >= 2 && path[1] == ':')) + { + return global ? "is absolute; a path in <> is below the Include directory" : "is absolute; a path in quotes is relative to this file"; + } + + return global && path.Replace('\\', '/').Split('/').Any(part => part is ".." or ".") + ? "has . or .. parts; a path in <> stays below the Include directory" + : null; + } + private sealed class Walk(ConfigurationFamily family, ConfigurationContext context) { private readonly List<Token> _output = []; @@ -275,29 +301,6 @@ public static class ConfigurationResolver return Global(path, at, shown, text); } - // Why a path is not taken as written, or null when it is. - private static string? Refusal(string path, bool global) - { - if (path.IndexOfAny(['*', '?', '[', ']']) >= 0) - { - return "has a wildcard; name one file"; - } - - if (path.Contains("://", StringComparison.Ordinal)) - { - return "is a URL; Tazel includes files of this machine only"; - } - - if (Path.IsPathRooted(path) || (path.Length >= 2 && path[1] == ':')) - { - return global ? "is absolute; a path in <> is below the Include directory" : "is absolute; a path in quotes is relative to this file"; - } - - return global && path.Replace('\\', '/').Split('/').Any(part => part is ".." or ".") - ? "has . or .. parts; a path in <> stays below the Include directory" - : null; - } - // A file below the family's Include directory of TAZEL_HOME, which no link may leave. private string Global(string path, Token at, string shown, string text) { diff --git a/src/Progmasoft.Tazel/Output/ErrorCodes.cs b/src/Progmasoft.Tazel/Output/ErrorCodes.cs index 29c8b04..5d9a7fd 100644 --- a/src/Progmasoft.Tazel/Output/ErrorCodes.cs +++ b/src/Progmasoft.Tazel/Output/ErrorCodes.cs @@ -36,6 +36,7 @@ internal static partial class ErrorCodes public const string IncludeMissing = "E0010"; public const string IncludeTooDeep = "E0011"; public const string PlatformDependsOnTarget = "E0012"; + public const string IgnoreInvalid = "E0013"; public const string CommandLine = "E0100"; @@ -172,6 +173,13 @@ internal static partial class ErrorCodes "cannot be given an argument with \", % or a line break as written, so such an argument is refused. " + "tazel tool create-wrapper writes tazel-<name> into a directory that exists and never overwrites a file.", "TAZEL_TOOL_EXECUTABLE= tazel tool launch fmt", "TAZEL_TOOL_EXECUTABLE=./bin/fmt tazel tool launch fmt", "tazel"), + new(IgnoreInvalid, "a .tazelignore Tazel cannot read", + "A .tazelignore holds gitignore rules, one per line, and a few lines of Tazel's own: pragma:once first in a " + + "file, import:<file> or import:\"file\" and include:<file> or include:\"file\" (quoted beside this file, " + + "<> below TAZEL_HOME's Include/Ignore), and regex:EXPRESSION or !regex:EXPRESSION, a .NET regular expression " + + "over the path relative to the file's directory, which must compile and finish within a second. A gitignore " + + "rule that starts with one of these words takes a backslash before it: \\regex:name.", + "regex:([a-z", "regex:^[a-z]+\\.tmp$", ".tazelignore"), new(CommandLine, "a command line Tazel cannot take", "The command, an option or a value is not one Tazel knows, or a command got arguments it does not take. Tazel " + "suggests the nearest spelling when there is one. tazel help lists the commands, and tazel help <command> --long " + diff --git a/src/Progmasoft.Tazel/Program.cs b/src/Progmasoft.Tazel/Program.cs index d152e21..35329cb 100644 --- a/src/Progmasoft.Tazel/Program.cs +++ b/src/Progmasoft.Tazel/Program.cs @@ -76,6 +76,12 @@ internal static class Program "A key with no name on it opens nothing, least of all a cache."); return 1; } + catch (Project.Ignore.IgnoreException error) + { + reporter.Error(ErrorCodes.IgnoreInvalid, error.Message, "tazel explain E0013 says what a .tazelignore takes", + "Tazel ignores many things, but not a file it cannot read."); + return 1; + } catch (ToolException error) { reporter.Error(ErrorCodes.Tool, error.Message, "tazel explain E0507 says where Tazel looks for tools", @@ -140,6 +146,11 @@ internal static class Program { return options; } + + if (error is Project.Ignore.IgnoreException { Diagnostic: { } ignore }) + { + return ignore; + } } return null; diff --git a/src/Progmasoft.Tazel/Project/FileSets.cs b/src/Progmasoft.Tazel/Project/FileSets.cs index 5aac65f..41c9f49 100644 --- a/src/Progmasoft.Tazel/Project/FileSets.cs +++ b/src/Progmasoft.Tazel/Project/FileSets.cs @@ -93,14 +93,18 @@ internal static class FileSets { Checked(glob.Pattern, place); var all = new List<string>(); - Walk(packageDirectory, "", all, top: true); + // A package is in a module; outside one, its own directory is where ignore files start. + var root = ModuleFiles.RootOf(packageDirectory) ?? packageDirectory; + var package = Path.GetRelativePath(root, packageDirectory).Replace('\\', '/'); + Walk(packageDirectory, "", all, top: true, Ignore.IgnoreRules.For(root), package == "." ? "" : package + "/"); return all .Where(file => Matches(glob.Pattern, file) && !glob.Exclude.Any(pattern => Matches(pattern, file))) .Order(StringComparer.Ordinal) .ToList(); } - private static void Walk(string directory, string prefix, List<string> found, bool top) + // The files of a package below directory, less hidden ones, other packages and modules, and what is ignored. + private static void Walk(string directory, string prefix, List<string> found, bool top, Ignore.IgnoreRules ignore, string package) { if (!top && ModuleFiles.BuildFileIn(directory) is not null) { @@ -109,7 +113,8 @@ internal static class FileSets foreach (var entry in new DirectoryInfo(directory).EnumerateFileSystemInfos()) { - if (entry.Name.StartsWith('.') || entry.LinkTarget is not null) + if (entry.Name.StartsWith('.') || entry.LinkTarget is not null || + ignore.Ignored(package + prefix + entry.Name, entry is DirectoryInfo)) { continue; } @@ -118,7 +123,7 @@ internal static class FileSets { if (!File.Exists(Path.Combine(entry.FullName, ModuleFiles.ModuleFile))) { - Walk(entry.FullName, prefix + entry.Name + "/", found, top: false); + Walk(entry.FullName, prefix + entry.Name + "/", found, top: false, ignore, package); } } else diff --git a/src/Progmasoft.Tazel/Project/Ignore/IgnoreFile.cs b/src/Progmasoft.Tazel/Project/Ignore/IgnoreFile.cs new file mode 100644 index 0000000..f0afd53 --- /dev/null +++ b/src/Progmasoft.Tazel/Project/Ignore/IgnoreFile.cs @@ -0,0 +1,385 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// 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; + +/// <summary>What is wrong with a <c>.tazelignore</c>, with where it is when it has a place.</summary> +public sealed class IgnoreException : Exception +{ + /// <summary>A problem with no place in a file.</summary> + public IgnoreException(string message) + : base(message) + { + } + + /// <summary>A problem at a line of a file.</summary> + public IgnoreException(Diagnostic diagnostic) + : base(diagnostic?.Plain) + { + Diagnostic = diagnostic; + } + + /// <summary>Nothing to say.</summary> + public IgnoreException() + { + } + + /// <summary>What is wrong, and why.</summary> + public IgnoreException(string message, Exception inner) + : base(message, inner) + { + } + + /// <summary>Where the problem is, when it is in a file.</summary> + public Diagnostic? Diagnostic { get; } +} + +/// <summary>One rule: a gitignore pattern or a <c>regex:</c>, compiled, with whether it ignores or keeps.</summary> +/// <param name="Text">The line as written, for messages.</param> +/// <param name="Pattern">What a path relative to the rule's directory must match, whole.</param> +/// <param name="Negated">Whether it keeps what an earlier rule ignored (<c>!</c>).</param> +/// <param name="DirectoryOnly">Whether it matches directories only (a trailing <c>/</c>).</param> +/// <param name="Place">The file and line it was read from.</param> +internal sealed record IgnoreRule(string Text, Regex Pattern, bool Negated, bool DirectoryOnly, string Place); + +/// <summary> +/// The rules of one <c>.tazelignore</c>, 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: +/// <c>pragma:once</c>, <c>import:<file></c>, <c>import:"file"</c>, <c>include:…</c>, <c>regex:…</c> and +/// <c>!regex:…</c>. A rule that means a name starting with one of these words is written <c>\pragma:…</c>, as gitignore +/// itself reads it. +/// </summary> +internal static class IgnoreFile +{ + /// <summary>The name of the file.</summary> + public static string FileName { get; } = ".tazelignore"; + + /// <summary>How long one <c>regex:</c> may take on one path.</summary> + public static TimeSpan RegexTimeout { get; } = TimeSpan.FromSeconds(1); + + private static readonly string[] Reserved = ["pragma:", "import:", "include:", "regex:", "!regex:"]; + + /// <summary>Whether a gitignore line starts with a word Tazel reads as a directive, so it needs a backslash.</summary> + public static bool NeedsEscape(string line) => Reserved.Any(word => line.StartsWith(word, StringComparison.Ordinal)); + + /// <summary> + /// The rules of <paramref name="file"/>, read from <paramref name="text"/>, with includes followed; a problem is an + /// <see cref="IgnoreException"/> at its line. + /// </summary> + public static IReadOnlyList<IgnoreRule> Read(string file, string text) => new Reader().Root(file, text); + + private sealed class Reader + { + private readonly List<IgnoreRule> _rules = []; + private readonly HashSet<string> _once = new(StringComparer.Ordinal); + private readonly HashSet<string> _loaded = new(StringComparer.Ordinal); + private readonly List<string> _chain = []; + + public IReadOnlyList<IgnoreRule> Root(string file, string text) + { + Read(Path.GetFullPath(file), text); + return _rules; + } + + private void Read(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:<file> 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); + } + + Read(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; +} + +/// <summary>gitignore patterns, compiled to regular expressions that match a path relative to the file's directory.</summary> +internal static class Gitignore +{ + /// <summary> + /// The pattern of <paramref name="line"/>, or null for a line that is no rule (only spaces, or a lone <c>!</c>). + /// Trailing spaces go unless a backslash keeps them; <c>!</c> negates, <c>\!</c> and <c>\#</c> are literal; a + /// trailing <c>/</c> matches directories only; a <c>/</c> elsewhere anchors the pattern to the file's directory, + /// and without one it matches at any depth. <c>*</c>, <c>?</c> and <c>[...]</c> stop at <c>/</c>; <c>**</c> as a + /// whole part matches any number of directories. + /// </summary> + 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(Part(parts[i])); + if (!last) + { + result.Append('/'); + } + } + + return result.ToString(); + } + + private static string Part(string part) + { + var result = new StringBuilder(); + for (var i = 0; i < part.Length; i++) + { + var letter = part[i]; + switch (letter) + { + case '\\' when i + 1 < part.Length: + result.Append(Regex.Escape(part[++i].ToString())); + break; + case '*': + while (i + 1 < part.Length && part[i + 1] == '*') + { + i++; + } + + result.Append("[^/]*"); + break; + case '?': + result.Append("[^/]"); + break; + case '[' when Class(part, i) is { } found: + result.Append(found.Expression); + i = found.End; + break; + default: + result.Append(Regex.Escape(letter.ToString())); + break; + } + } + + 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; + } +} diff --git a/src/Progmasoft.Tazel/Project/Ignore/IgnoreRules.cs b/src/Progmasoft.Tazel/Project/Ignore/IgnoreRules.cs new file mode 100644 index 0000000..17c0401 --- /dev/null +++ b/src/Progmasoft.Tazel/Project/Ignore/IgnoreRules.cs @@ -0,0 +1,117 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.RegularExpressions; + +namespace Progmasoft.Tazel.Project.Ignore; + +/// <summary> +/// What the <c>.tazelignore</c> files of a module ignore. A file applies to its directory and below; for a path, the +/// rules of every file from the module root down to the path's directory are read in that order, and the last rule +/// that matches decides, <c>!</c> keeping what an earlier one ignored. A path inside an ignored directory is ignored +/// whatever a rule says of it, as in gitignore. Directories whose names start with a dot, <c>.tazel</c> among them, are +/// left out by Tazel before any rule, and no rule brings them back. +/// </summary> +internal sealed class IgnoreRules +{ + private readonly string _root; + private readonly Dictionary<string, IReadOnlyList<(string Scope, IgnoreRule Rule)>> _rulesOf = new(StringComparer.Ordinal); + private readonly Dictionary<string, bool> _directories = new(StringComparer.Ordinal); + + private IgnoreRules(string root) => _root = Path.GetFullPath(root); + + /// <summary>The rules of the module rooted at <paramref name="root"/>; files are read as paths need them.</summary> + public static IgnoreRules For(string root) => new(root); + + /// <summary>Whether <paramref name="relative"/>, a path below the module root with <c>/</c> between its parts, is ignored.</summary> + public bool Ignored(string relative, bool directory) + { + ArgumentNullException.ThrowIfNull(relative); + var path = relative.Replace('\\', '/').Trim('/'); + if (path.Length == 0) + { + return false; + } + + var slash = path.LastIndexOf('/'); + var parent = slash < 0 ? "" : path[..slash]; + if (parent.Length > 0 && IgnoredDirectory(parent)) + { + return true; + } + + return directory ? IgnoredDirectory(path) : Decide(path, parent, directory: false); + } + + private bool IgnoredDirectory(string path) + { + if (_directories.TryGetValue(path, out var known)) + { + return known; + } + + var slash = path.LastIndexOf('/'); + var parent = slash < 0 ? "" : path[..slash]; + var ignored = (parent.Length > 0 && IgnoredDirectory(parent)) || Decide(path, parent, directory: true); + _directories[path] = ignored; + return ignored; + } + + // The last matching rule of the files from the root down to parent decides. + private bool Decide(string path, string parent, bool directory) + { + var ignored = false; + foreach (var (scope, rule) in RulesDownTo(parent)) + { + if (rule.DirectoryOnly && !directory) + { + continue; + } + + var local = scope.Length == 0 ? path : path[(scope.Length + 1)..]; + bool matches; + try + { + matches = rule.Pattern.IsMatch(local); + } + catch (RegexMatchTimeoutException error) + { + throw new IgnoreException($"{rule.Place}: '{rule.Text}' took more than {IgnoreFile.RegexTimeout.TotalSeconds:0} s on {path}", error); + } + + if (matches) + { + ignored = !rule.Negated; + } + } + + return ignored; + } + + // The rules of the files of the root and of each directory down to directory, shallowest first. + private IReadOnlyList<(string Scope, IgnoreRule Rule)> RulesDownTo(string directory) + { + if (_rulesOf.TryGetValue(directory, out var known)) + { + return known; + } + + var slash = directory.LastIndexOf('/'); + var above = directory.Length == 0 ? [] : RulesDownTo(slash < 0 ? "" : directory[..slash]); + var rules = new List<(string, IgnoreRule)>(above); + var file = Path.Combine(_root, directory.Replace('/', Path.DirectorySeparatorChar), IgnoreFile.FileName); + if (File.Exists(file)) + { + foreach (var rule in IgnoreFile.Read(file, File.ReadAllText(file))) + { + rules.Add((directory, rule)); + } + } + + _rulesOf[directory] = rules; + return rules; + } +} diff --git a/src/Progmasoft.Tazel/Project/ModuleFiles.cs b/src/Progmasoft.Tazel/Project/ModuleFiles.cs index e544316..47943d9 100644 --- a/src/Progmasoft.Tazel/Project/ModuleFiles.cs +++ b/src/Progmasoft.Tazel/Project/ModuleFiles.cs @@ -21,7 +21,11 @@ internal static class ModuleFiles public const string BuildFile = "BUILD.csx"; /// <summary>The root of the module <paramref name="directory"/> is in: the nearest directory with a MODULE.csx.</summary> - public static string FindRoot(string directory) + public static string FindRoot(string directory) => RootOf(directory) + ?? throw new ProjectException($"there is no {ModuleFile} in {Path.GetFullPath(directory)} or above it"); + + /// <summary>The root of the module <paramref name="directory"/> is in, or null when it is in none.</summary> + public static string? RootOf(string directory) { for (var current = new DirectoryInfo(Path.GetFullPath(directory)); current is not null; current = current.Parent) { @@ -31,7 +35,7 @@ internal static class ModuleFiles } } - throw new ProjectException($"there is no {ModuleFile} in {Path.GetFullPath(directory)} or above it"); + return null; } /// <summary>The project file of the package at <paramref name="directory"/>, or null when it has none.</summary> @@ -58,11 +62,13 @@ internal static class ModuleFiles /// <summary> /// Every package of the module at <paramref name="root"/>, by its path: directories with a project file, less - /// hidden ones and the directories of other modules. + /// hidden ones, the directories of other modules and what its <c>.tazelignore</c> files ignore. An ignored + /// directory is not entered. /// </summary> public static IReadOnlyList<(string Path, string File)> Packages(string root) { var found = new List<(string, string)>(); + var ignore = Ignore.IgnoreRules.For(root); Visit(root, ""); return found.OrderBy(entry => entry.Item1, StringComparer.Ordinal).ToList(); @@ -75,14 +81,41 @@ internal static class ModuleFiles foreach (var child in new DirectoryInfo(directory).EnumerateDirectories()) { + var childPath = path.Length == 0 ? child.Name : $"{path}/{child.Name}"; if (child.Name.StartsWith('.') || child.LinkTarget is not null || - File.Exists(Path.Combine(child.FullName, ModuleFile))) + File.Exists(Path.Combine(child.FullName, ModuleFile)) || ignore.Ignored(childPath, directory: true)) { continue; } - Visit(child.FullName, path.Length == 0 ? child.Name : $"{path}/{child.Name}"); + Visit(child.FullName, childPath); } } } + + /// <summary> + /// The package at <paramref name="path"/> of the module at <paramref name="root"/>, whatever its .tazelignore files + /// say, as an explicit label names it; null when there is none there: no project file, a hidden or linked + /// directory on the way, or another module's. + /// </summary> + public static (string Path, string File)? PackageAt(string root, string path) + { + var directory = root; + foreach (var part in path.Length == 0 ? [] : path.Split('/')) + { + if (part.Length == 0 || part.StartsWith('.')) + { + return null; + } + + directory = Path.Combine(directory, part); + if (!Directory.Exists(directory) || new DirectoryInfo(directory).LinkTarget is not null || + File.Exists(Path.Combine(directory, ModuleFile))) + { + return null; + } + } + + return BuildFileIn(directory) is { } file ? (path, file) : null; + } } diff --git a/src/Progmasoft.Tazel/Project/Workspace.cs b/src/Progmasoft.Tazel/Project/Workspace.cs index 928c6e4..a558ca1 100644 --- a/src/Progmasoft.Tazel/Project/Workspace.cs +++ b/src/Progmasoft.Tazel/Project/Workspace.cs @@ -96,12 +96,26 @@ internal sealed class Workspace /// <summary>The packages of every module.</summary> public List<PackageId> Packages { get; } = []; + /// <summary> + /// The packages a .tazelignore leaves out of discovery that a label named, so they were loaded: patterns such as + /// <c>//...</c> do not cover them. + /// </summary> + public HashSet<PackageId> IgnoredPackages { get; } = []; + /// <summary>The toolchains the main module registers, in its order.</summary> public List<ProjectToolchain> Registered { get; } = []; /// <summary>Loads the module that <paramref name="directory"/> is in, with the modules it depends on.</summary> + public static Task<Workspace> LoadAsync( + string directory, BuildContext build, Version tazelVersion, Action<string>? status = null) => + LoadAsync(directory, build, tazelVersion, status, []); + + /// <summary> + /// <see cref="LoadAsync(string, BuildContext, Version, Action{string})"/>, with the labels of the command line, so a + /// package they name loads even where a .tazelignore leaves it out of discovery. + /// </summary> public static async Task<Workspace> LoadAsync( - string directory, BuildContext build, Version tazelVersion, Action<string>? status = null) + string directory, BuildContext build, Version tazelVersion, Action<string>? status, IReadOnlyList<string> labels) { var root = ModuleFiles.FindRoot(directory); var main = await LoadModuleAsync(root, null, tazelVersion, root, build.Platform).ConfigureAwait(false); @@ -114,6 +128,8 @@ internal sealed class Workspace await workspace.LoadPackagesAsync(module, build, status ?? (_ => { })).ConfigureAwait(false); } + var here = Path.GetRelativePath(root, Path.GetFullPath(directory)).Replace('\\', '/'); + await workspace.LoadNamedPackagesAsync(build, labels, new PackageId(null, here == "." ? "" : here)).ConfigureAwait(false); workspace.Resolve(); return workspace; } @@ -278,8 +294,77 @@ internal sealed class Workspace { var plugins = Plugins.LoadAll(Main.Root, module, build, status); PluginsOf[module.Repository ?? ""] = plugins; - var environment = Plugins.EnvironmentFor(plugins); - var packages = ModuleFiles.Packages(module.Root); + await LoadPackageListAsync(module, ModuleFiles.Packages(module.Root), build).ConfigureAwait(false); + } + + /// <summary> + /// Loads the packages that labels name directly and discovery left out because a .tazelignore ignores them: those + /// of Depends, of ModuleImports, of the registered toolchains and of the command line, until none is missing. No + /// ignored directory is searched; only the named package's own directory is looked at. + /// </summary> + private async Task LoadNamedPackagesAsync(BuildContext build, IReadOnlyList<string> labels, PackageId here) + { + while (true) + { + var wanted = new HashSet<PackageId>(); + foreach (var target in Targets.Values) + { + var texts = target.Settings.Depends.Items.Select(reference => reference.Label) + .Concat(target.Settings is ZigModuleSettings zig ? zig.ModuleImports.Values : []); + foreach (var text in texts) + { + AddPackage(wanted, text, target.Label.Package, target.Module.Repository); + } + } + + foreach (var text in (Main.Globals.toolchains?.Labels ?? []).Concat(labels)) + { + AddPackage(wanted, text, here, null); + } + + var missing = wanted.Where(id => !Packages.Contains(id)) + .Select(id => (Id: id, Module: id.Repository is null ? Main : External.GetValueOrDefault(id.Repository))) + .Where(entry => entry.Module is not null) + .Select(entry => (entry.Module!, Package: ModuleFiles.PackageAt(entry.Module!.Root, entry.Id.Path))) + .Where(entry => entry.Package is not null) + .GroupBy(entry => entry.Item1) + .ToList(); + if (missing.Count == 0) + { + return; + } + + foreach (var group in missing) + { + foreach (var entry in group) + { + IgnoredPackages.Add(new PackageId(group.Key.Repository, entry.Package!.Value.Path)); + } + + await LoadPackageListAsync(group.Key, group.Select(entry => entry.Package!.Value).ToList(), build).ConfigureAwait(false); + } + } + } + + // The package of a label, when it is a label of one target; patterns and malformed text are left to the selector. + private static void AddPackage(HashSet<PackageId> wanted, string text, PackageId from, string? repository) + { + try + { + var label = Labels.Target(text, from); + wanted.Add(label.Package.Repository is null && repository is not null + ? label.Package with { Repository = repository } + : label.Package); + } + catch (LabelException) + { + // Not one target's label: //..., :all and the like select from what discovery found. + } + } + + private async Task LoadPackageListAsync(LoadedModule module, IReadOnlyList<(string Path, string File)> packages, BuildContext build) + { + var environment = Plugins.EnvironmentFor(PluginsOf[module.Repository ?? ""]); var scopes = await Task.WhenAll(packages.Select(package => Task.Run(async () => { var shown = module.Shown(FileSets.ToRoot(package.File, module.Root)); diff --git a/tests/Progmasoft.Tazel.Tests/IgnoreTests.cs b/tests/Progmasoft.Tazel.Tests/IgnoreTests.cs new file mode 100644 index 0000000..b36bb10 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/IgnoreTests.cs @@ -0,0 +1,295 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Progmasoft.Tazel.Archive; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Dsl.Configuration; +using Progmasoft.Tazel.Project; +using Progmasoft.Tazel.Project.Ignore; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class GitignoreTests +{ + private static bool? Matches(string rule, string path, bool directory = false) + { + var parsed = Gitignore.Parse(rule); + if (parsed is null) + { + return null; + } + + var (pattern, _, directoryOnly) = parsed.Value; + return (!directoryOnly || directory) && pattern.IsMatch(path); + } + + [Theory] + [InlineData("*.log", "a.log", true)] + [InlineData("*.log", "deep/down/a.log", true)] + [InlineData("*.log", "a.log.txt", false)] + [InlineData("/a.log", "a.log", true)] + [InlineData("/a.log", "sub/a.log", false)] + [InlineData("doc/*.txt", "doc/a.txt", true)] + [InlineData("doc/*.txt", "doc/x/a.txt", false)] + [InlineData("doc/*.txt", "x/doc/a.txt", false)] + [InlineData("**/foo", "foo", true)] + [InlineData("**/foo", "a/b/foo", true)] + [InlineData("**/foo/bar", "a/foo/bar", true)] + [InlineData("abc/**", "abc/x", true)] + [InlineData("abc/**", "abc/x/y", true)] + [InlineData("abc/**", "abc", false)] + [InlineData("a/**/b", "a/b", true)] + [InlineData("a/**/b", "a/x/y/b", true)] + [InlineData("a/**/b", "a/xb", false)] + [InlineData("?.c", "a.c", true)] + [InlineData("?.c", "ab.c", false)] + [InlineData("[ab].c", "b.c", true)] + [InlineData("[ab].c", "c.c", false)] + [InlineData("[a-c].c", "b.c", true)] + [InlineData("[!a].c", "a.c", false)] + [InlineData("[!a].c", "b.c", true)] + [InlineData("[^a].c", "b.c", true)] + [InlineData("a*b", "a/b", false)] + [InlineData("\\#name", "#name", true)] + [InlineData("\\!name", "!name", true)] + [InlineData("a\\*", "a*", true)] + [InlineData("a\\*", "ab", false)] + [InlineData("name ", "name", true)] + [InlineData("name\\ ", "name ", true)] + [InlineData("[ab", "[ab", true)] + [InlineData("a.b", "aXb", false)] + public void MatchesAsGitDoes(string rule, string path, bool expected) => Assert.Equal(expected, Matches(rule, path)); + + [Fact] + public void ATrailingSlashMeansDirectoriesOnly() + { + Assert.Equal(true, Matches("build/", "build", directory: true)); + Assert.Equal(false, Matches("build/", "build", directory: false)); + Assert.Equal(true, Matches("build/", "x/build", directory: true)); + } + + [Fact] + public void NegationAndEmptyRules() + { + Assert.True(Gitignore.Parse("!keep.log")!.Value.Negated); + Assert.Null(Gitignore.Parse(" ")); + Assert.Null(Gitignore.Parse("!")); + } +} + +[Collection(nameof(TazelHomeCollection))] +public sealed class IgnoreTests +{ + private sealed class Home : IDisposable + { + private readonly string? _was = Environment.GetEnvironmentVariable(TazelHome.Variable); + + public Home(string value) => Environment.SetEnvironmentVariable(TazelHome.Variable, value); + + public void Dispose() => Environment.SetEnvironmentVariable(TazelHome.Variable, _was); + } + + private static IgnoreException Problem(Action read) => Assert.Throws<IgnoreException>(read); + + [Fact] + public void TheLastMatchingRuleDecidesAndNestedFilesComeAfter() + { + using var module = new TemporaryModule() + .Write(".tazelignore", "*.log\n!keep.log\nsub/drop.txt\n") + .Write("sub/.tazelignore", "!*.log\n*.tmp\n"); + var rules = IgnoreRules.For(module.Root); + Assert.True(rules.Ignored("a.log", false)); + Assert.False(rules.Ignored("keep.log", false)); + Assert.False(rules.Ignored("sub/a.log", false)); + Assert.True(rules.Ignored("sub/x.tmp", false)); + Assert.False(rules.Ignored("x.tmp", false)); + Assert.True(rules.Ignored("sub/drop.txt", false)); + } + + [Fact] + public void NothingInsideAnIgnoredDirectoryComesBack() + { + using var module = new TemporaryModule().Write(".tazelignore", "gen/\n!gen/keep.c\n"); + var rules = IgnoreRules.For(module.Root); + Assert.True(rules.Ignored("gen", true)); + Assert.True(rules.Ignored("gen/keep.c", false)); + Assert.True(rules.Ignored("gen/deep/x.c", false)); + Assert.False(rules.Ignored("gen", false)); + } + + [Fact] + public void RegexRulesMatchThePathFromTheirDirectory() + { + using var module = new TemporaryModule() + .Write(".tazelignore", "regex:^src/.*\\.generated\\.cpp$\n!regex:^src/required\\.generated\\.cpp$\n") + .Write("lib/.tazelignore", "regex:^x\\.c$\n"); + var rules = IgnoreRules.For(module.Root); + Assert.True(rules.Ignored("src/a.generated.cpp", false)); + Assert.True(rules.Ignored("src/deep/a.generated.cpp", false)); + Assert.False(rules.Ignored("src/required.generated.cpp", false)); + Assert.True(rules.Ignored("lib/x.c", false)); + Assert.False(rules.Ignored("x.c", false)); + } + + [Fact] + public void ARegexThatRunsTooLongIsAnError() + { + using var module = new TemporaryModule().Write(".tazelignore", "regex:^(a+)+$\n"); + var error = Problem(() => IgnoreRules.For(module.Root).Ignored(new string('a', 40) + "!", false)); + Assert.Contains("took more than 1 s", error.Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData("regex:([a-z", "is not a regular expression")] + [InlineData("pragma:twice", "is not a pragma")] + [InlineData("*.log\npragma:once", "must come first")] + [InlineData("include:nothing", "needs one path")] + [InlineData("include:\"*.txt\"", "has a wildcard")] + [InlineData("include:\"missing.txt\"", "is not a file beside this one")] + [InlineData("import:</etc/x>", "is absolute")] + public void SaysWhatIsWrongWithALine(string text, string message) + { + using var module = new TemporaryModule().Write(".tazelignore", text); + var error = Problem(() => IgnoreFile.Read(Path.Combine(module.Root, ".tazelignore"), text)); + Assert.Contains(message, error.Diagnostic!.Message, StringComparison.Ordinal); + Assert.Equal(Output.ErrorCodes.IgnoreInvalid, error.Diagnostic.Code); + } + + [Fact] + public void IncludesImportsAndOnce() + { + using var module = new TemporaryModule() + .Write("config/a.ignore.txt", "include:\"b.ignore.txt\"\n*.a\n") + .Write("config/b.ignore.txt", "pragma:once\n*.b\n") + .Write("config/loop.ignore.txt", "include:\"loop.ignore.txt\"\n"); + var root = Path.Combine(module.Root, ".tazelignore"); + var rules = IgnoreFile.Read(root, "include:\"config/a.ignore.txt\"\nimport:\"config/a.ignore.txt\"\ninclude:\"config/b.ignore.txt\"\n*.c\n"); + Assert.Equal(["*.b", "*.a", "*.c"], rules.Select(rule => rule.Text)); + var cycle = Problem(() => IgnoreFile.Read(root, "include:\"config/loop.ignore.txt\"\n")); + Assert.Contains("includes itself", cycle.Diagnostic!.Message, StringComparison.Ordinal); + } + + [Fact] + public void GlobalIncludesComeFromTazelHome() + { + using var module = new TemporaryModule().Write("home/Include/Ignore/common.ignore.txt", "*.o\n"); + using var home = new Home(Path.Combine(module.Root, "home")); + var rules = IgnoreFile.Read(Path.Combine(module.Root, ".tazelignore"), "import:<common.ignore.txt>\n"); + Assert.Equal("*.o", Assert.Single(rules).Text); + } + + [Fact] + public void ABackslashMakesADirectiveWordAName() + { + using var module = new TemporaryModule().Write(".tazelignore", "\\regex:name\n\\pragma:x\n!\\regex:keep\n"); + var rules = IgnoreRules.For(module.Root); + Assert.True(rules.Ignored("regex:name", false)); + Assert.True(rules.Ignored("pragma:x", false)); + Assert.True(IgnoreFile.NeedsEscape("regex:x")); + Assert.True(IgnoreFile.NeedsEscape("!regex:x")); + Assert.False(IgnoreFile.NeedsEscape("!import:x")); + } + + private static TemporaryModule Module() => new TemporaryModule() + .Write("MODULE.csx", TemporaryModule.ModuleFile) + .Write("BUILD.csx", "using Progmasoft.Tazel.Dsl.Build.Prelude;\nCC.Executable(\"app\", new() { Sources = new Glob(\"**/*.c\"), Depends = [\"//skipped:lib\"] });\n") + .Write("main.c", "int f(void);\nint main(void) { return f(); }\n") + .Write("gen/bad.c", "#error ignored\n") + .Write("skipped/BUILD.csx", "using Progmasoft.Tazel.Dsl.Build.Prelude;\nCC.StaticLibrary(\"lib\", new() { Sources = [\"f.c\"], Visibility = Visibility.Public });\n") + .Write("skipped/f.c", "int f(void) { return 0; }\n") + .Write("other/BUILD.csx", "using Progmasoft.Tazel.Dsl.Build.Prelude;\nCC.StaticLibrary(\"o\", new() { Sources = [\"o.c\"] });\n") + .Write("other/o.c", "int o(void) { return 0; }\n") + .Write(".tazelignore", "gen/\nskipped/\nother/\n"); + + [Fact] + public void DiscoveryAndGlobsLeaveIgnoredPathsOut() + { + using var module = Module(); + Assert.Equal([""], ModuleFiles.Packages(module.Root).Select(package => package.Path)); + var files = FileSets.Resolve(new Glob("**/*.c"), module.Root, module.Root, "BUILD.csx:2"); + Assert.Equal(["main.c"], files); + // An explicit path is not ignored. + Assert.Equal(["gen/bad.c"], FileSets.Resolve(["gen/bad.c"], module.Root, module.Root, "BUILD.csx:2")); + } + + [Fact] + public async Task ALabelNamesAnIgnoredPackageAndPatternsDoNot() + { + Assert.SkipWhen(Driver.Host.Which("cc") is null && Driver.Host.Which("gcc") is null && Driver.Host.Which("clang") is null, "no C compiler"); + using var module = Module(); + var (status, output) = await module.TazelAsync(".", "--color", "never", "build", "//:app"); + Assert.True(status == 0, output); + (status, output) = await module.TazelAsync(".", "--color", "never", "query", "//..."); + Assert.Equal(0, status); + Assert.Contains("//:app", output, StringComparison.Ordinal); + Assert.DoesNotContain("//skipped:lib", output, StringComparison.Ordinal); + Assert.DoesNotContain("//other:o", output, StringComparison.Ordinal); + (status, output) = await module.TazelAsync(".", "--color", "never", "build", "//other:o"); + Assert.True(status == 0, output); + } + + [Fact] + public void ModuleArchivesLeaveIgnoredFilesOut() + { + using var module = Module(); + var files = ModuleArchive.Files(module.Root, _ => false); + Assert.Contains("main.c", files); + Assert.DoesNotContain(files, file => file.StartsWith("gen/", StringComparison.Ordinal) || file.StartsWith("skipped/", StringComparison.Ordinal)); + } + + [Fact] + public async Task CreateFromEscapesDirectiveWordsAndNeverOverwrites() + { + using var module = new TemporaryModule().Write("home/keep", "").Write(".gitignore", "# kept\nregex:literal\n!regex:too\n*.log\n"); + using var home = new Home(Path.Combine(module.Root, "home")); + var (status, output) = await module.TazelAsync(".", "--color", "never", "ignore", "create-from", ".gitignore"); + Assert.True(status == 0, output); + Assert.Equal("# kept\n\\regex:literal\n!\\regex:too\n*.log\n", File.ReadAllText(Path.Combine(module.Root, ".tazelignore"))); + Assert.Equal("# kept\nregex:literal\n!regex:too\n*.log\n", File.ReadAllText(Path.Combine(module.Root, ".gitignore"))); + (status, output) = await module.TazelAsync(".", "--color", "never", "ignore", "create-from", ".gitignore"); + Assert.Equal(1, status); + Assert.Contains("already here", output, StringComparison.Ordinal); + (status, _) = await module.TazelAsync(".", "--color", "never", "ignore", "create-from", "missing"); + Assert.Equal(1, status); + } + + [Fact] + public async Task AddAndDeleteEditOnlyThisDirectorysFile() + { + using var module = new TemporaryModule().Write("home/keep", "").Write(".tazelignore", "# comment\n*.log\n\n*.o\n*.o\n"); + using var home = new Home(Path.Combine(module.Root, "home")); + var file = Path.Combine(module.Root, ".tazelignore"); + Assert.Equal(0, (await module.TazelAsync(".", "ignore", "add", "regex:^x$")).Status); + Assert.Contains("already", (await module.TazelAsync(".", "--color", "never", "ignore", "add", "*.log")).Output, StringComparison.Ordinal); + Assert.Equal(1, (await module.TazelAsync(".", "ignore", "add", "regex:([")).Status); + Assert.Equal(1, (await module.TazelAsync(".", "ignore", "add", "include:\"x\"")).Status); + Assert.Equal(0, (await module.TazelAsync(".", "ignore", "del", "*.o")).Status); + Assert.Equal("# comment\n*.log\n\nregex:^x$\n", File.ReadAllText(file)); + Assert.Equal(1, (await module.TazelAsync(".", "ignore", "delete", "*.o")).Status); + Assert.Equal(0, (await module.TazelAsync(".", "ignore", "delete", "regex:^x$")).Status); + Assert.Equal("# comment\n*.log\n\n", File.ReadAllText(file)); + File.Delete(file); + Assert.Equal(1, (await module.TazelAsync(".", "ignore", "add", "*.x")).Status); + } + + [Fact] + public async Task ValidateReadsTheFilesOfIgnoredDirectoriesToo() + { + using var module = new TemporaryModule() + .Write("MODULE.csx", TemporaryModule.ModuleFile) + .Write(".tazelignore", "hidden/\n") + .Write("hidden/.tazelignore", "regex:([\n"); + var (status, output) = await module.TazelAsync(".", "--color", "never", "ignore", "validate"); + Assert.Equal(1, status); + Assert.Contains("is not a regular expression", output, StringComparison.Ordinal); + File.WriteAllText(Path.Combine(module.Root, "hidden", ".tazelignore"), "*.x\n"); + (status, output) = await module.TazelAsync(".", "--color", "never", "ignore", "validate"); + Assert.True(status == 0, output); + Assert.Contains("valid: hidden/.tazelignore (1 rule)", output, StringComparison.Ordinal); + } +}