tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
feat(cli): record why actions ran and explain it with tazel log why
- Commit
499fffdae7a26847e415f461972200537e22ed20- Author
- Leitwolf11 ·
- Parents
8d0e76780758
Changes
CHANGELOG.md | 3 + docs/commands.md | 1 + src/Progmasoft.Tazel/Cli/CommandMakers.cs | 12 +- src/Progmasoft.Tazel/Cli/CommandTypes.cs | 2 +- src/Progmasoft.Tazel/Cli/Commands.cs | 29 +++- src/Progmasoft.Tazel/Cli/Help.cs | 5 +- src/Progmasoft.Tazel/Cli/LogCommands.cs | 69 +++++++- .../Cli/ShellCompletion.FishPowerShell.cs | 2 +- src/Progmasoft.Tazel/Cli/ShellCompletion.cs | 2 +- src/Progmasoft.Tazel/Driver/Actions.cs | 50 +++++- src/Progmasoft.Tazel/Driver/CCPlanner.cs | 3 + src/Progmasoft.Tazel/Driver/Executor.cs | 6 +- src/Progmasoft.Tazel/Driver/RebuildReasons.cs | 133 +++++++++++++++ src/Progmasoft.Tazel/Driver/StepPlanner.cs | 1 + src/Progmasoft.Tazel/Driver/ZigPlanner.cs | 1 + .../Progmasoft.Tazel.Tests/RebuildReasonsTests.cs | 180 +++++++++++++++++++++ 16 files changed, 480 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 805a1e0..ea1b25e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,9 @@ a lock: entries older than `trash-max-age` days (default 30), then the oldest above `trash-max-size` MiB (default 10240). Both options are read only from `$TAZEL_HOME/User/tazel_options.txt`. - Added SQLite graph metadata persistence (`CadreCelesteStore` + `GraphEngine.RestoreMetadata`) and conservative C/C++/Objective-C ABI-aware early-cutoff fingerprinting (`AbiFingerprint.HashHeaderTokens`, `AbiFingerprint.HashExportedSymbols`) in `Progmasoft.Tazel.CadreCeleste`. +- `tazel log why <label>`: every build records why each action ran (its first cause: changed, removed or new input with + old and new digests, changed command, changed output, no record, or forced) in `.tazel/logs/why.json`, and the + command prints the chain from the first changed source through each rebuild to the target's actions. ## 0.5.0 - 2026-12-03 diff --git a/docs/commands.md b/docs/commands.md index 9a8dc31..24d1e7b 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -16,6 +16,7 @@ | `tazel init [--force]` | interactively initializes a module in the current directory | | `tazel git add` | stages the module's files with system `git`, respecting `.gitignore` | | `tazel log cache\|workspace\|what-ran\|what-failed\|what-up\|snoop\|daemon\|registries` | read-only inspection of cache, module root, recent runs, daemon status, and effective registries | +| `tazel log why <label>` | why the target's actions ran in the last build: for each, the first cause (a changed, removed or newly read input with its old and new SHA-256 prefix, a changed command, an output changed behind the build's back, no earlier record, or `--no-cache`/`--recompile`) and the chain of rebuilds from that cause to the action; it reads `.tazel/logs/why.json`, which every build rewrites, and loads no `BUILD.csx` | | `tazel doctor` | checks local compilers, runtime, git, Linux KVM/MicroVM, and daemon status without requiring a workspace | | `tazel dump [--cadre-celeste=...] [-o text\|json]` | inspects the running .NET daemon and Cadre Celeste state without starting a daemon | | `tazel ide compdb [labels] [-o <file>]` | writes a deterministic `compile_commands.json` for C/C++/ObjC targets (default `//...`) | diff --git a/src/Progmasoft.Tazel/Cli/CommandMakers.cs b/src/Progmasoft.Tazel/Cli/CommandMakers.cs index 240ac86..d546396 100644 --- a/src/Progmasoft.Tazel/Cli/CommandMakers.cs +++ b/src/Progmasoft.Tazel/Cli/CommandMakers.cs @@ -132,7 +132,17 @@ internal static class CommandMakers private static Command MakeLog(ScannedCommand scanned, OutputOptions output) { - var actions = new[] { "cache", "workspace", "what-ran", "what-failed", "what-up", "snoop", "daemon", "registries" }; + var actions = new[] { "cache", "workspace", "what-ran", "what-failed", "what-up", "snoop", "daemon", "registries", "why" }; + if (scanned.Positional is ["why", var label]) + { + return new LogCommand(output, "why", label); + } + + if (scanned.Positional is ["why", ..]) + { + throw new CommandLineException("tazel log why takes one target label: tazel log why //app:greeter"); + } + if (scanned.Positional.Count == 1 && actions.Contains(scanned.Positional[0], StringComparer.Ordinal)) { return new LogCommand(output, scanned.Positional[0]); diff --git a/src/Progmasoft.Tazel/Cli/CommandTypes.cs b/src/Progmasoft.Tazel/Cli/CommandTypes.cs index 77da924..95a0e04 100644 --- a/src/Progmasoft.Tazel/Cli/CommandTypes.cs +++ b/src/Progmasoft.Tazel/Cli/CommandTypes.cs @@ -210,7 +210,7 @@ internal sealed record TrashCommand(OutputOptions Output, string Action, string? : Command(Output); /// <summary><c>tazel log <action></c>: read-only inspection of workspace, cache, runs, daemon, and registries.</summary> -internal sealed record LogCommand(OutputOptions Output, string Action) : Command(Output); +internal sealed record LogCommand(OutputOptions Output, string Action, string? Argument = null) : Command(Output); /// <summary><c>tazel doctor</c>: read-only environment diagnostics with actionable hints.</summary> internal sealed record DoctorCommand(OutputOptions Output) : Command(Output); diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index 65e2e55..d402a92 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -48,7 +48,7 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector GitAddCommand => new GitCommands(reporter, workingDirectory).AddAsync(TazelVersion), NewCommand create => Task.FromResult(new NewInitCommands(reporter, workingDirectory).New(create.Name, create.Force)), InitCommand init => Task.FromResult(new NewInitCommands(reporter, workingDirectory).Init(init.Force)), - LogCommand log => Task.FromResult(new LogCommands(reporter, workingDirectory, TazelVersion).Run(log.Action)), + LogCommand log => Task.FromResult(new LogCommands(reporter, workingDirectory, TazelVersion).Run(log.Action, log.Argument)), TrashCommand trash => Task.FromResult(new TrashCommands(reporter).Run(trash)), DoctorCommand => new DoctorCommands(reporter, TazelVersion).RunAsync(cancel), DumpCommand dump => new DumpCommands(reporter).RunAsync(dump, cancel), @@ -577,13 +577,36 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector ? new Cache.RemoteCache(remote.Url, remote.Settings.Token) : null; var remoteActions = remoteCache is null ? null : RemoteActionsOf(remoteCache, cacheSettings!.Remote!.Settings, digests); + var reasons = new RebuildReasonLog(); var executor = new Executor(buildOptions.Jobs, buildOptions.KeepGoing || kind is BuildKind.Test or BuildKind.Coverage, new ActionCache(digests, enabled: cacheSettings?.Local ?? true), reporter, remoteActions, buildOptions.CachePolicy, - planner.Layout.Full($"{ModuleFiles.StateDirectory}/forced")); - var succeeded = await executor.RunAsync(goals, cancel).ConfigureAwait(false); + planner.Layout.Full($"{ModuleFiles.StateDirectory}/forced"), reasons); + bool succeeded; + try + { + succeeded = await executor.RunAsync(goals, cancel).ConfigureAwait(false); + } + finally + { + // What ran is worth explaining whether the build passed, failed or was stopped. + WriteReasons(planner.Layout.Full(ModuleFiles.StateDirectory), reasons); + } + return new Built(buildOptions, planner, chooser, executor, succeeded, planned); } + private void WriteReasons(string state, RebuildReasonLog reasons) + { + try + { + RebuildReasons.Write(state, reasons.All); + } + catch (Exception problem) when (problem is IOException or UnauthorizedAccessException) + { + reporter.Warning($"tazel log why will not know this build: {problem.Message}"); + } + } + /// <summary>The remote cache as MODULE.csx sets it up, with its keys read.</summary> private Cache.RemoteActions RemoteActionsOf(Cache.RemoteCache cache, Dsl.Module.Prelude.RemoteSettings settings, Digests digests) { diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index de55f7d..290f8df 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -382,13 +382,14 @@ internal static class Help empty removes entries, all of them or those older than --older-than days; --dry-run only lists them A fingerprint is given by at least 8 of its digits. """), - ["log"] = new("tazel log cache|workspace|what-ran|what-failed|what-up|snoop|daemon|registries: inspects workspace and cache state.", """ - tazel log cache|workspace|what-ran|what-failed|what-up|snoop|daemon|registries + ["log"] = new("tazel log cache|workspace|what-ran|what-failed|what-up|snoop|daemon|registries|why <label>: inspects workspace and cache state.", """ + tazel log cache|workspace|what-ran|what-failed|what-up|snoop|daemon|registries|why <label> Read-only inspection commands: cache state and size of local .tazel caches workspace root directory of the current module what-ran recent recorded runs, newest first + why <label> why the target's actions ran in the last build: the first changed input, then each rebuild it caused what-failed recent failed runs, newest first what-up operations currently in progress on the daemon snoop watch operations in progress on the daemon diff --git a/src/Progmasoft.Tazel/Cli/LogCommands.cs b/src/Progmasoft.Tazel/Cli/LogCommands.cs index 548bd99..b49ec6d 100644 --- a/src/Progmasoft.Tazel/Cli/LogCommands.cs +++ b/src/Progmasoft.Tazel/Cli/LogCommands.cs @@ -17,8 +17,9 @@ internal sealed class LogCommands(Reporter reporter, string workingDirectory, Ve ["out", "testlogs", "coverage", "zig-cache", "package", "downloads", Project.ScriptCache.Directory]; /// <summary>Dispatches one <c>tazel log <action></c> subcommand.</summary> - public int Run(string action) => action switch + public int Run(string action, string? argument = null) => action switch { + "why" => Why(argument ?? throw new CommandLineException("tazel log why takes one target label")), "workspace" => Workspace(), "cache" => Cache(), "daemon" => Daemon(), @@ -30,6 +31,72 @@ internal sealed class LogCommands(Reporter reporter, string workingDirectory, Ve _ => throw new CommandLineException($"tazel log has no '{action}'"), }; + /// <summary> + /// tazel log why: for each action of the target that ran in the last build, the chain from the first cause, a changed + /// source or command, through the actions that rebuilt what it reads. Reads one file; loads no BUILD.csx. + /// </summary> + private int Why(string text) + { + var root = ModuleFiles.FindRoot(workingDirectory); + var label = Label.Labels.Target(text, CurrentPackage(root)).ToString(); + var reasons = Driver.RebuildReasons.Read(Path.Combine(root, ModuleFiles.StateDirectory)); + if (reasons is null) + { + reporter.Status("no build has been recorded here yet; build first, then ask why"); + return 0; + } + + var own = reasons.Where(reason => reason.Target == label).ToList(); + if (own.Count == 0) + { + reporter.Status($"{label} was not rebuilt in the last build: all it needed was current"); + return 0; + } + + foreach (var reason in own) + { + var chain = Driver.RebuildReasons.Chain(reason, reasons); + reporter.Plain($"{reason.Description}:"); + reporter.Plain($" {Cause(chain[0], root)}"); + foreach (var step in chain) + { + reporter.Plain($" -> {step.Description}"); + } + } + + return 0; + } + + private static string Cause(Driver.RebuildReason reason, string root) + { + var file = reason.File is null ? null : FileSets.ToRoot(reason.File, root); + return reason.Cause switch + { + Driver.RebuildCause.NoRecord => "no earlier run was recorded (first build, or after tazel clean)", + Driver.RebuildCause.CommandChanged => "its command, directory or environment changed", + Driver.RebuildCause.InputChanged when reason.Now is null => $"{file} was removed", + Driver.RebuildCause.InputChanged => $"{file} changed ({Short(reason.Was)} -> {Short(reason.Now)})", + Driver.RebuildCause.InputAdded => $"{file} is read for the first time", + Driver.RebuildCause.OutputChanged => $"{file}, which it writes, was changed or removed since", + _ => "--no-cache, --recompile or a disabled local cache ran it regardless", + }; + } + + private static string Short(string? digest) => digest is null ? "none" : digest[..12]; + + // The package of the working directory: the nearest directory up to the module root with a BUILD.csx. + private Label.PackageId CurrentPackage(string root) + { + var directory = Path.GetFullPath(workingDirectory); + while (directory.Length > root.Length && !File.Exists(Path.Combine(directory, ModuleFiles.BuildFile))) + { + directory = Path.GetDirectoryName(directory)!; + } + + var relative = FileSets.ToRoot(directory, root); + return new Label.PackageId(null, relative == "." ? "" : relative); + } + private int Workspace() { var root = ModuleFiles.FindRoot(workingDirectory); diff --git a/src/Progmasoft.Tazel/Cli/ShellCompletion.FishPowerShell.cs b/src/Progmasoft.Tazel/Cli/ShellCompletion.FishPowerShell.cs index 1f02feb..fee9567 100644 --- a/src/Progmasoft.Tazel/Cli/ShellCompletion.FishPowerShell.cs +++ b/src/Progmasoft.Tazel/Cli/ShellCompletion.FishPowerShell.cs @@ -96,7 +96,7 @@ internal static class FishPowerShellCompletions sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from clean' -l dry-run -d 'Preview removals without deleting'"); sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from new init' -l force -d 'Overwrite existing MODULE.csx'"); sb.AppendLine("complete -c tazel -n '__tazel_needs_subcmd git' -a 'add'"); - sb.AppendLine("complete -c tazel -n '__tazel_needs_subcmd log' -a 'cache workspace what-ran what-failed what-up snoop daemon registries'"); + sb.AppendLine("complete -c tazel -n '__tazel_needs_subcmd log' -a 'cache workspace what-ran what-failed what-up snoop daemon registries why'"); sb.AppendLine("complete -c tazel -n '__tazel_needs_subcmd modules' -a 'graph deps explain tidy resolve diff merge export verify'"); sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from modules update fetch' -l locked -d 'Require LOCK.sqlite3 to match MODULE.csx'"); sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from modules update fetch' -l frozen -d 'Require --locked and --offline'"); diff --git a/src/Progmasoft.Tazel/Cli/ShellCompletion.cs b/src/Progmasoft.Tazel/Cli/ShellCompletion.cs index 0b4c27d..fb62348 100644 --- a/src/Progmasoft.Tazel/Cli/ShellCompletion.cs +++ b/src/Progmasoft.Tazel/Cli/ShellCompletion.cs @@ -255,7 +255,7 @@ internal static class ShellCompletion if [[ -z "$subcmd" ]]; then words="$words add"; fi ;; log) - if [[ -z "$subcmd" ]]; then words="$words cache workspace what-ran what-failed what-up snoop daemon registries"; fi + if [[ -z "$subcmd" ]]; then words="$words cache workspace what-ran what-failed what-up snoop daemon registries why"; fi ;; modules) words="$words --locked --frozen --offline --all-features --duplicates -d --invert -i --depth --path --format" diff --git a/src/Progmasoft.Tazel/Driver/Actions.cs b/src/Progmasoft.Tazel/Driver/Actions.cs index 31e6de5..5eab3ab 100644 --- a/src/Progmasoft.Tazel/Driver/Actions.cs +++ b/src/Progmasoft.Tazel/Driver/Actions.cs @@ -60,6 +60,9 @@ internal sealed class BuildAction public required string Description { get; init; } + /// <summary>The label of the target the action belongs to, for <c>tazel log why</c>; null for none.</summary> + public string? Target { get; init; } + public required IReadOnlyList<string> Command { get; init; } public required string Directory { get; init; } @@ -156,25 +159,58 @@ internal sealed class Digests internal sealed class ActionCache(Digests digests, bool enabled = true) { /// <summary>Whether <paramref name="action"/> would write what it wrote last time; never, when the cache is off.</summary> - public bool IsCurrent(BuildAction action) + public bool IsCurrent(BuildAction action) => Why(action) is null; + + /// <summary> + /// Why <paramref name="action"/> is not current, the first reason found; null when it is. Inputs are looked at before + /// outputs, in the record's order, so the same files give the same reason. + /// </summary> + public RebuildReason? Why(BuildAction action) { if (!enabled) { - return false; + return Reason(action, RebuildCause.Forced, null, null, null); } var record = Read(RecordOf(action)); - if (record is null || record.Value.Key != action.Key) + if (record is null) { - return false; + return Reason(action, RebuildCause.NoRecord, null, null, null); + } + + if (record.Value.Key != action.Key) + { + return Reason(action, RebuildCause.CommandChanged, null, null, null); } var files = record.Value.Files; - return files.All(entry => digests.Of(entry.Key) == entry.Value) && - action.Outputs.All(output => files.ContainsKey(action.Full(output))) && - action.Inputs.All(input => files.ContainsKey(action.Full(input))); + var outputs = action.Outputs.Select(action.Full).ToHashSet(StringComparer.Ordinal); + foreach (var (file, was) in files.OrderBy(entry => outputs.Contains(entry.Key)).ThenBy(entry => entry.Key, StringComparer.Ordinal)) + { + var now = digests.Of(file); + if (now != was) + { + var cause = outputs.Contains(file) ? RebuildCause.OutputChanged : RebuildCause.InputChanged; + return Reason(action, cause, file, was, now); + } + } + + foreach (var file in action.Inputs.Concat(action.Outputs).Select(action.Full)) + { + if (!files.ContainsKey(file)) + { + var cause = outputs.Contains(file) ? RebuildCause.OutputChanged : RebuildCause.InputAdded; + return Reason(action, cause, file, null, digests.Of(file)); + } + } + + return null; } + /// <summary>A reason for <paramref name="action"/>.</summary> + public static RebuildReason Reason(BuildAction action, RebuildCause cause, string? file, string? was, string? now) => + new(action.Target, action.Description, cause, file, was, now, [.. action.Outputs.Select(action.Full)]); + /// <summary>Records <paramref name="action"/> after it succeeded.</summary> public void Record(BuildAction action) { diff --git a/src/Progmasoft.Tazel/Driver/CCPlanner.cs b/src/Progmasoft.Tazel/Driver/CCPlanner.cs index a49f846..9eae4c1 100644 --- a/src/Progmasoft.Tazel/Driver/CCPlanner.cs +++ b/src/Progmasoft.Tazel/Driver/CCPlanner.cs @@ -174,6 +174,7 @@ internal sealed partial class Planner { Kind = ActionKind.Compile, Description = $"Compiling {target.Label} {relative}", + Target = target.Label.ToString(), Command = command, Directory = Layout.MainRoot, Inputs = context.HeaderInputs.Prepend(source).Distinct(StringComparer.Ordinal).ToList(), @@ -267,6 +268,7 @@ internal sealed partial class Planner { Kind = ActionKind.Archive, Description = $"Archiving {target.Label}", + Target = target.Label.ToString(), Command = command, Directory = Layout.MainRoot, Inputs = objects, @@ -361,6 +363,7 @@ internal sealed partial class Planner { Kind = ActionKind.Link, Description = $"Linking {target.Label}", + Target = target.Label.ToString(), Command = command, Directory = Layout.MainRoot, Inputs = objects.Concat(inputs).Concat(extraFiles).Distinct(StringComparer.Ordinal).ToList(), diff --git a/src/Progmasoft.Tazel/Driver/Executor.cs b/src/Progmasoft.Tazel/Driver/Executor.cs index fd086e1..a8f5495 100644 --- a/src/Progmasoft.Tazel/Driver/Executor.cs +++ b/src/Progmasoft.Tazel/Driver/Executor.cs @@ -18,7 +18,7 @@ namespace Progmasoft.Tazel.Driver; /// </summary> internal sealed class Executor( int jobs, bool keepGoing, ActionCache cache, Reporter reporter, Cache.RemoteActions? remote = null, - CachePolicy policy = CachePolicy.Normal, string? scratch = null) + CachePolicy policy = CachePolicy.Normal, string? scratch = null, RebuildReasonLog? reasons = null) { private readonly System.Collections.Concurrent.ConcurrentDictionary<BuildAction, bool> _made = new(); private int _done; @@ -98,7 +98,8 @@ internal sealed class Executor( private async Task<bool> MakeAsync(BuildAction action, int total, CancellationTokenSource stop) { var forced = Forced(action); - if (!forced && cache.IsCurrent(action)) + var why = forced ? ActionCache.Reason(action, RebuildCause.Forced, null, null, null) : cache.Why(action); + if (why is null) { action.After?.Invoke(); Interlocked.Increment(ref _done); @@ -106,6 +107,7 @@ internal sealed class Executor( return true; } + reasons?.Add(why); foreach (var output in action.Outputs) { var full = action.Full(output); diff --git a/src/Progmasoft.Tazel/Driver/RebuildReasons.cs b/src/Progmasoft.Tazel/Driver/RebuildReasons.cs new file mode 100644 index 0000000..0254357 --- /dev/null +++ b/src/Progmasoft.Tazel/Driver/RebuildReasons.cs @@ -0,0 +1,133 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Progmasoft.Tazel.Driver; + +/// <summary>Why an action ran instead of being taken as current.</summary> +public enum RebuildCause +{ + /// <summary>No record of an earlier run: the first build, or one after <c>tazel clean</c>.</summary> + NoRecord, + + /// <summary>The command, directory or environment changed.</summary> + CommandChanged, + + /// <summary>A file it read has other contents, or is gone.</summary> + InputChanged, + + /// <summary>It reads a file its record does not list: a new source or header.</summary> + InputAdded, + + /// <summary>A file it wrote was changed or removed since.</summary> + OutputChanged, + + /// <summary><c>--no-cache</c> or <c>--recompile</c>, or a local cache turned off, ran it whatever the record said.</summary> + Forced, +} + +/// <summary>Why one action of a build ran.</summary> +/// <param name="Target">The label of the target the action belongs to.</param> +/// <param name="Description">What the action does, as the build printed it.</param> +/// <param name="Cause">The first reason found.</param> +/// <param name="File">The file the cause is about, when it is about one.</param> +/// <param name="Was">The digest the record held for <paramref name="File"/>; null when it held none.</param> +/// <param name="Now">The digest <paramref name="File"/> has now; null when it is gone.</param> +/// <param name="Outputs">What the action writes, as full paths.</param> +public sealed record RebuildReason( + string? Target, string Description, RebuildCause Cause, string? File, string? Was, string? Now, IReadOnlyList<string> Outputs); + +/// <summary> +/// The reasons of the actions that ran in the last build, kept in <c>.tazel/logs/why.json</c> for <c>tazel log why</c>. +/// </summary> +public static class RebuildReasons +{ + /// <summary>The file, below the module's <c>.tazel/</c>.</summary> + public static string RelativePath { get; } = "logs/why.json"; + + /// <summary>Writes <paramref name="reasons"/> as the last build's, replacing what an earlier build wrote.</summary> + public static void Write(string stateDirectory, IEnumerable<RebuildReason> reasons) + { + ArgumentNullException.ThrowIfNull(stateDirectory); + var file = Path.Combine(stateDirectory, RelativePath); + Directory.CreateDirectory(Path.GetDirectoryName(file)!); + var ordered = reasons.OrderBy(reason => reason.Target, StringComparer.Ordinal) + .ThenBy(reason => reason.Description, StringComparer.Ordinal).ToList(); + var partial = file + ".partial"; + File.WriteAllText(partial, JsonSerializer.Serialize(ordered, RebuildReasonsJson.Default.ListRebuildReason)); + File.Move(partial, file, overwrite: true); + } + + /// <summary>The last build's reasons, or null when no build wrote any.</summary> + public static IReadOnlyList<RebuildReason>? Read(string stateDirectory) + { + var file = Path.Combine(stateDirectory, RelativePath); + if (!File.Exists(file)) + { + return null; + } + + try + { + return JsonSerializer.Deserialize(File.ReadAllText(file), RebuildReasonsJson.Default.ListRebuildReason); + } + catch (JsonException) + { + return null; + } + } + + /// <summary> + /// The chain that made <paramref name="reason"/> run, from the first cause to it: while an action ran because a file + /// it reads changed and another action of the same build wrote that file, that action comes before it. The chain + /// stops at a file no action wrote (a source), at any other cause, or at an action already in it. + /// </summary> + public static IReadOnlyList<RebuildReason> Chain(RebuildReason reason, IReadOnlyList<RebuildReason> all) + { + ArgumentNullException.ThrowIfNull(reason); + ArgumentNullException.ThrowIfNull(all); + var writers = new Dictionary<string, RebuildReason>(StringComparer.Ordinal); + foreach (var other in all) + { + foreach (var output in other.Outputs) + { + writers.TryAdd(output, other); + } + } + + var chain = new List<RebuildReason> { reason }; + var current = reason; + while (current.Cause is RebuildCause.InputChanged && current.File is { } file && + writers.TryGetValue(file, out var writer) && !chain.Contains(writer)) + { + chain.Add(writer); + current = writer; + } + + chain.Reverse(); + return chain; + } +} + +/// <summary>Collects the reasons of a build as its actions run, from any thread.</summary> +internal sealed class RebuildReasonLog +{ + private readonly ConcurrentQueue<RebuildReason> _reasons = new(); + + public void Add(RebuildReason reason) => _reasons.Enqueue(reason); + + public IReadOnlyList<RebuildReason> All => [.. _reasons]; +} + +[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true)] +[JsonSerializable(typeof(List<RebuildReason>))] +internal sealed partial class RebuildReasonsJson : JsonSerializerContext +{ +} diff --git a/src/Progmasoft.Tazel/Driver/StepPlanner.cs b/src/Progmasoft.Tazel/Driver/StepPlanner.cs index 9418559..75bddeb 100644 --- a/src/Progmasoft.Tazel/Driver/StepPlanner.cs +++ b/src/Progmasoft.Tazel/Driver/StepPlanner.cs @@ -49,6 +49,7 @@ internal sealed partial class Planner var action = new BuildAction { Description = $"Running {target.Label}", + Target = target.Label.ToString(), Command = command, Directory = Layout.MainRoot, Inputs = inputs.Concat(dependencies.Values.Select(full => FileSets.ToRoot(full, Layout.MainRoot))).ToList(), diff --git a/src/Progmasoft.Tazel/Driver/ZigPlanner.cs b/src/Progmasoft.Tazel/Driver/ZigPlanner.cs index 41356d2..9e13de2 100644 --- a/src/Progmasoft.Tazel/Driver/ZigPlanner.cs +++ b/src/Progmasoft.Tazel/Driver/ZigPlanner.cs @@ -200,6 +200,7 @@ internal sealed partial class Planner return forced; }, Description = $"{(target.Kind == TargetKind.Test ? "Building test" : "Compiling")} {target.Label}", + Target = target.Label.ToString(), Command = command, Directory = Layout.MainRoot, Inputs = inputs.Concat(libraryInputs).Distinct(StringComparer.Ordinal).ToList(), diff --git a/tests/Progmasoft.Tazel.Tests/RebuildReasonsTests.cs b/tests/Progmasoft.Tazel.Tests/RebuildReasonsTests.cs new file mode 100644 index 0000000..9d8cfe2 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/RebuildReasonsTests.cs @@ -0,0 +1,180 @@ +// 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.Cli; +using Progmasoft.Tazel.Driver; +using Progmasoft.Tazel.Output; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +/// <summary>Why actions ran, as the build records it and <c>tazel log why</c> tells it.</summary> +public sealed class RebuildReasonsTests +{ + // src.txt -> (copy) -> mid.txt -> (copy) -> out.txt, each step one action. + private static (BuildAction First, BuildAction Second) Pipeline(string root, string firstCommand = "cp src.txt mid.txt") => + (new BuildAction + { + Description = "Copying //:first", + Target = "//:first", + Command = ["sh", "-c", firstCommand], + Directory = root, + Inputs = ["src.txt"], + Outputs = ["mid.txt"], + }, + new BuildAction + { + Description = "Copying //:second", + Target = "//:second", + Command = ["sh", "-c", "cp mid.txt out.txt"], + Directory = root, + Inputs = ["mid.txt"], + Outputs = ["out.txt"], + }); + + private static async Task<RebuildReasonLog> BuildAsync(string root, string firstCommand = "cp src.txt mid.txt") + { + var (first, second) = Pipeline(root, firstCommand); + second.Prerequisites.Add(first); + var reasons = new RebuildReasonLog(); + using var reporter = new Reporter(MessageFormat.Jsonl, new StringWriter(), When.Never, true, When.Never); + var executor = new Executor(1, false, new ActionCache(new Digests()), reporter, null, CachePolicy.Normal, null, reasons); + Assert.True(await executor.RunAsync([second], TestContext.Current.CancellationToken)); + return reasons; + } + + [Fact] + public async Task EachRebuildRecordsItsFirstCauseAndTheChainLeadsBackToTheSource() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "the commands are sh"); + using var module = new TemporaryModule().Write("src.txt", "one\n"); + + var first = await BuildAsync(module.Root); + Assert.All(first.All, reason => Assert.Equal(RebuildCause.NoRecord, reason.Cause)); + Assert.Equal(2, first.All.Count); + + Assert.Empty((await BuildAsync(module.Root)).All); + + File.WriteAllText(Path.Combine(module.Root, "src.txt"), "two\n"); + var all = (await BuildAsync(module.Root)).All; + var second = Assert.Single(all, reason => reason.Target == "//:second"); + Assert.Equal(RebuildCause.InputChanged, second.Cause); + Assert.Equal(Path.Combine(module.Root, "mid.txt"), second.File); + Assert.NotEqual(second.Was, second.Now); + + var chain = RebuildReasons.Chain(second, all); + Assert.Equal(["//:first", "//:second"], chain.Select(reason => reason.Target)); + Assert.Equal(RebuildCause.InputChanged, chain[0].Cause); + Assert.Equal(Path.Combine(module.Root, "src.txt"), chain[0].File); + } + + [Fact] + public async Task RewritingTheSameBytesRunsNothingAndACommandChangeIsNamed() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "the commands are sh"); + using var module = new TemporaryModule().Write("src.txt", "one\n"); + await BuildAsync(module.Root); + + File.WriteAllText(Path.Combine(module.Root, "src.txt"), "one\n"); + Assert.Empty((await BuildAsync(module.Root)).All); + + // Same output bytes, other command: the first reruns for its command, and the second, reading the same bytes, + // does not run at all. + var reason = Assert.Single((await BuildAsync(module.Root, "cat src.txt > mid.txt")).All); + Assert.Equal(RebuildCause.CommandChanged, reason.Cause); + Assert.Equal("//:first", reason.Target); + } + + [Fact] + public async Task AnOutputChangedBehindTheBuildsBackIsNamed() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "the commands are sh"); + using var module = new TemporaryModule().Write("src.txt", "one\n"); + await BuildAsync(module.Root); + + File.WriteAllText(Path.Combine(module.Root, "out.txt"), "edited by hand\n"); + var reason = Assert.Single((await BuildAsync(module.Root)).All); + Assert.Equal(RebuildCause.OutputChanged, reason.Cause); + Assert.Equal(Path.Combine(module.Root, "out.txt"), reason.File); + } + + [Fact] + public void TheChainStopsAtACycleAndAtOtherCauses() + { + var a = new RebuildReason("//:a", "A", RebuildCause.InputChanged, "/b.out", "1", "2", ["/a.out"]); + var b = new RebuildReason("//:b", "B", RebuildCause.InputChanged, "/a.out", "1", "2", ["/b.out"]); + Assert.Equal(["B", "A"], RebuildReasons.Chain(a, [a, b]).Select(reason => reason.Description)); + + var c = new RebuildReason("//:c", "C", RebuildCause.CommandChanged, null, null, null, ["/c.out"]); + Assert.Equal(["C"], RebuildReasons.Chain(c, [a, b, c]).Select(reason => reason.Description)); + } + + [Fact] + public void ReasonsSurviveTheFileAndAMissingFileReadsAsNoBuild() + { + using var module = new TemporaryModule(); + var state = Path.Combine(module.Root, ".tazel"); + Assert.Null(RebuildReasons.Read(state)); + + var reason = new RebuildReason("//:a", "A", RebuildCause.InputAdded, "/x.h", null, "abc", ["/a.out"]); + RebuildReasons.Write(state, [reason]); + var read = Assert.Single(RebuildReasons.Read(state)!); + Assert.Equal(reason.Target, read.Target); + Assert.Equal(reason.Cause, read.Cause); + Assert.Equal(reason.Outputs, read.Outputs); + Assert.Contains("\"InputAdded\"", File.ReadAllText(Path.Combine(state, RebuildReasons.RelativePath)), StringComparison.Ordinal); + } + + [Theory] + [InlineData("log why")] + [InlineData("log why //:a //:b")] + public void LogWhyTakesExactlyOneLabel(string line) => + Assert.Throws<CommandLineException>(() => CommandLine.Parse(line.Split(' '))); + + [Fact] + public void LogWhyParsesItsLabel() + { + var command = Assert.IsType<LogCommand>(CommandLine.Parse(["log", "why", "//app:greeter"])); + Assert.Equal("why", command.Action); + Assert.Equal("//app:greeter", command.Argument); + } + + [Fact] + public async Task LogWhyTellsTheChainAfterAHeaderChange() + { + Assert.SkipWhen(Host.Which("cc") is null && Host.Which("gcc") is null && Host.Which("clang") is null, "no C compiler"); + using var module = new TemporaryModule() + .Write("MODULE.csx", TemporaryModule.ModuleFile) + .Write("BUILD.csx", """ + using Progmasoft.Tazel.Dsl.Build.Prelude; + CC.StaticLibrary("math", new() { Sources = ["math.c"], Headers = ["math.h"] }); + CC.Executable("app", new() { Sources = ["main.c"], Depends = ["//:math"] }); + """) + .Write("math.h", "int add(int a, int b);\n") + .Write("math.c", "#include \"math.h\"\nint add(int a, int b) { return a + b; }\n") + .Write("main.c", "#include \"math.h\"\nint main(void) { return add(1, 1) - 2; }\n"); + + var (status, output) = await module.TazelAsync(".", ["--color", "never", "log", "why", "//:app"]); + Assert.Equal(0, status); + Assert.Contains("no build has been recorded", output, StringComparison.Ordinal); + + (status, output) = await module.TazelAsync(".", ["--color", "never", "build", "//:app"]); + Assert.True(status == 0, output); + (status, output) = await module.TazelAsync(".", ["--color", "never", "build", "//:app"]); + Assert.True(status == 0, output); + (status, output) = await module.TazelAsync(".", ["--color", "never", "log", "why", "//:app"]); + Assert.Contains("was not rebuilt in the last build", output, StringComparison.Ordinal); + + module.Write("math.h", "int add(int a, int b); /* documented */\nint sub(int a, int b);\n"); + (status, output) = await module.TazelAsync(".", ["--color", "never", "build", "//:app"]); + Assert.True(status == 0, output); + (status, output) = await module.TazelAsync(".", ["--color", "never", "log", "why", "//:app"]); + Assert.Equal(0, status); + Assert.Contains("math.h changed", output, StringComparison.Ordinal); + Assert.Contains("-> Compiling //:app main.c", output, StringComparison.Ordinal); + } +}