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 --recompile and --no-cache to build, run, test and coverage
- Commit
1760f37492bc6db7733cee56941fd9e90c0e5692- Author
- Leitwolf11 ·
- Parents
bbc8dbef71de
Changes
CHANGELOG.md | 3 + docs/commands.md | 22 +++ src/Progmasoft.Tazel/Cli/CommandLine.cs | 10 ++ src/Progmasoft.Tazel/Cli/Commands.cs | 7 +- src/Progmasoft.Tazel/Cli/Help.cs | 2 + src/Progmasoft.Tazel/Driver/Actions.cs | 53 +++++++ src/Progmasoft.Tazel/Driver/BuildOptions.cs | 3 + src/Progmasoft.Tazel/Driver/CCPlanner.cs | 3 + src/Progmasoft.Tazel/Driver/Executor.cs | 71 +++++++-- src/Progmasoft.Tazel/Driver/TestRunner.cs | 20 ++- src/Progmasoft.Tazel/Driver/ZigPlanner.cs | 9 ++ tests/Progmasoft.Tazel.Tests/CachePolicyTests.cs | 177 +++++++++++++++++++++++ 12 files changed, 361 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 06c0ef1..7b3691e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ ## Unreleased +- `--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. + - `tazel tool launch <name>` runs `TAZEL_TOOL_EXECUTABLE`, or the first `tazel-<name>` of `PATH` this user may run, with its arguments as written, and passes its exit status on; `tazel tool create-wrapper <name> [-o dir]` writes a `tazel-<name>` that runs `<name>`. Error `E0507`. diff --git a/docs/commands.md b/docs/commands.md index bdb04cf..0a1f6a4 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -42,6 +42,8 @@ A misspelt command, option or value gets a hint that keeps how it was written: ` | `--platform <name>` | build, run, test | the platform to build for | | `--jobs <n>` | build, run, test | how many actions run at once | | `--keep-going` | build, run, test | go on with what does not depend on a failed action | +| `--recompile` | build, run, test, coverage | compile every source again ([below](#recompile-and-no-cache)) | +| `--no-cache` | build, run, test, coverage | run every action and test, and read and write no cache | | `--feature <name>`, `--no-feature <name>` | build, run, test | turn a toolchain feature on or off for every target | | `--compiler-options <option>` | build, run, test | every C, C++, Objective-C and Objective-C++ file | | `--c-compiler-options <option>` | build, run, test | .c and .m files | @@ -55,6 +57,26 @@ the compiler takes the last flag, and they are part of the key of each action. The platform comes from `--platform`, else from `tazel_options.txt`, else it is this machine's. `--jobs` and `--keep-going` win over `Execution` of `MODULE.csx`. +## Recompile and no-cache + +| | default | `--recompile` | `--no-cache` | +| --- | --- | --- | --- | +| compiling (C family), compiling and linking (zig) | when something changed | always | always | +| linking, archiving | when something changed | when an object came out different | always | +| plugin and custom build steps | when something changed | when something changed | always | +| local and remote action cache reads | as configured | none for compilations | none | +| action cache writes | as configured | as configured | none | +| test results | as configured | as configured | not read, not written | + +Neither flag deletes a cache, changes `--jobs` or changes a key: a record written before is kept, and the next build +checks it against the files, as it checks every record. With both, `--no-cache` holds. A test that fails under +`--no-cache` loses the pass recorded before it. The tag `no-cache` of a test keeps its meaning. Fetched modules are +fetched as always. + +zig keeps what it compiled in a cache of its own: a forced zig action runs with an empty one in `.tazel/forced/`, +removed after, so it does compile; zig's global cache, of its standard library and of libc, is kept. A compiler that +caches by itself, such as ccache behind `cc`, is not bypassed. + ## Message formats `--message-format` chooses how Tazel prints its messages. `--color` and `--progress` change `rich-stdio` alone; diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs index 6a872a4..32ca366 100644 --- a/src/Progmasoft.Tazel/Cli/CommandLine.cs +++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs @@ -46,6 +46,12 @@ internal sealed record BuildFlags public bool KeepGoing { get; init; } + /// <summary><c>--recompile</c>: every compilation runs.</summary> + public bool Recompile { get; init; } + + /// <summary><c>--no-cache</c>: every action and test runs, and no cache is read or written.</summary> + public bool NoCache { get; init; } + public List<string> FeaturesOn { get; } = []; public List<string> FeaturesOff { get; } = []; @@ -172,6 +178,8 @@ internal static class CommandLine new("mode", Kind.Value, ["debug", "release"], Building), new("jobs", Kind.Value, null, Building), new("keep-going", Kind.Flag, null, Building), + new("recompile", Kind.Flag, null, "build", "run", "test", "coverage"), + new("no-cache", Kind.Flag, null, "build", "run", "test", "coverage"), new("feature", Kind.List, null, Building), new("no-feature", Kind.List, null, Building), new("compiler-options", Kind.List, null, Building), @@ -651,6 +659,8 @@ internal static class CommandLine Platform = platform, Jobs = jobs, KeepGoing = seen.Any(entry => entry.Option.Long == "keep-going"), + Recompile = seen.Any(entry => entry.Option.Long == "recompile"), + NoCache = seen.Any(entry => entry.Option.Long == "no-cache"), }; flags.FeaturesOn.AddRange(All(seen, "feature")); flags.FeaturesOff.AddRange(All(seen, "no-feature")); diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index d805d94..7b049cd 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -368,6 +368,7 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector LinkerOptions = flags.LinkerOptions, ZigCompilerOptions = flags.ZigCompilerOptions, Coverage = kind == BuildKind.Coverage, + CachePolicy = flags.NoCache ? CachePolicy.NoCache : flags.Recompile ? CachePolicy.Recompile : CachePolicy.Normal, }; /// <summary>The targets of a command: tests for test and coverage, one program for run, anything for build.</summary> @@ -411,7 +412,8 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector : null; var remoteActions = remoteCache is null ? null : RemoteActionsOf(remoteCache, cacheSettings!.Remote!.Settings, digests); var executor = new Executor(buildOptions.Jobs, buildOptions.KeepGoing || kind is BuildKind.Test or BuildKind.Coverage, - new ActionCache(digests, enabled: cacheSettings?.Local ?? true), reporter, remoteActions); + 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); return new Built(buildOptions, planner, chooser, executor, succeeded, planned); } @@ -445,7 +447,8 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector { var tests = built.Planned.Select(entry => (entry.Target, entry.Products, Built: entry.Products.Main is { } main && built.Executor.Succeeded(main))).ToList(); - var outcomes = await new TestRunner(built.Planner.Layout, built.Options.Jobs, reporter, built.Options.Coverage) + var outcomes = await new TestRunner(built.Planner.Layout, built.Options.Jobs, reporter, built.Options.Coverage, + built.Options.CachePolicy == CachePolicy.NoCache) .RunAsync(tests, cancel).ConfigureAwait(false); reporter.TestSummary(outcomes); var passed = outcomes.All(outcome => outcome.Status is TestStatus.Passed or TestStatus.Cached or TestStatus.Flaky); diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index 8303e17..a2b01f3 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -15,6 +15,8 @@ internal static class Help --platform <name> the platform to build for; default: tazel_options.txt, else this machine's --jobs <n> how many actions run at once; default: MODULE.csx, else the processors --keep-going go on with what does not depend on a failed action + --recompile compile every source again; links follow from what changed + --no-cache run every action and test; read and write no cache --feature <name> turn a toolchain feature on for every target --no-feature <name> turn a toolchain feature off for every target --compiler-options <option> for every C, C++, Objective-C and Objective-C++ file diff --git a/src/Progmasoft.Tazel/Driver/Actions.cs b/src/Progmasoft.Tazel/Driver/Actions.cs index 8fb1c48..31e6de5 100644 --- a/src/Progmasoft.Tazel/Driver/Actions.cs +++ b/src/Progmasoft.Tazel/Driver/Actions.cs @@ -15,8 +15,49 @@ namespace Progmasoft.Tazel.Driver; /// One action of a build: a command line with its environment, the files it reads and the files it writes, all relative /// to the directory it runs in. Inputs the command finds by itself, such as headers, come from its depfile. /// </summary> +/// <summary>What an action does, which decides what <c>--recompile</c> forces.</summary> +internal enum ActionKind +{ + /// <summary>A step of a plugin or a custom build action.</summary> + Step, + + /// <summary>Compiling one source file to an object file.</summary> + Compile, + + /// <summary>Compiling and linking in one command, as zig does.</summary> + CompileAndLink, + + /// <summary>Linking objects and libraries into a program or a shared library.</summary> + Link, + + /// <summary>Archiving objects into a static library.</summary> + Archive, +} + +/// <summary>What a build may take from its caches: everything, nothing for compilations, or nothing at all.</summary> +internal enum CachePolicy +{ + /// <summary>The caches as configured.</summary> + Normal, + + /// <summary><c>--recompile</c>: compilations run, and other actions follow from what they wrote.</summary> + Recompile, + + /// <summary><c>--no-cache</c>: every action runs, and no cache is read or written.</summary> + NoCache, +} + internal sealed class BuildAction { + /// <summary>What the action does; a step unless a planner says otherwise.</summary> + public ActionKind Kind { get; init; } = ActionKind.Step; + + /// <summary> + /// The command with the compiler's own cache moved to the directory it is given, for a run that must really compile; + /// null when the compiler keeps no cache of its own that Tazel knows of. The key stays that of <see cref="Command"/>. + /// </summary> + public Func<string, IReadOnlyList<string>>? WithCompilerCache { get; init; } + public required string Description { get; init; } public required IReadOnlyList<string> Command { get; init; } @@ -160,6 +201,18 @@ internal sealed class ActionCache(Digests digests, bool enabled = true) File.WriteAllText(RecordOf(action), text.ToString()); } + /// <summary> + /// Forgets what this process knows of the outputs of <paramref name="action"/> and keeps its record, which a later + /// build checks against the files before it trusts it. + /// </summary> + public void ForgetOutputs(BuildAction action) + { + foreach (var output in action.Outputs) + { + digests.Forget(action.Full(output)); + } + } + /// <summary>Forgets <paramref name="action"/>, so that a failed or stopped run is redone.</summary> public void Forget(BuildAction action) { diff --git a/src/Progmasoft.Tazel/Driver/BuildOptions.cs b/src/Progmasoft.Tazel/Driver/BuildOptions.cs index 9492dc1..5e4a826 100644 --- a/src/Progmasoft.Tazel/Driver/BuildOptions.cs +++ b/src/Progmasoft.Tazel/Driver/BuildOptions.cs @@ -36,6 +36,9 @@ internal sealed record BuildOptions /// <summary>Whether C-family code is built with LLVM source-based coverage, for <c>tazel coverage</c>.</summary> public bool Coverage { get; init; } + + /// <summary>What the build may take from its caches: <c>--recompile</c> and <c>--no-cache</c>.</summary> + public CachePolicy CachePolicy { get; init; } = CachePolicy.Normal; } /// <summary>Where a build writes, below the state directory of the main module.</summary> diff --git a/src/Progmasoft.Tazel/Driver/CCPlanner.cs b/src/Progmasoft.Tazel/Driver/CCPlanner.cs index 8622acd..0a59d20 100644 --- a/src/Progmasoft.Tazel/Driver/CCPlanner.cs +++ b/src/Progmasoft.Tazel/Driver/CCPlanner.cs @@ -170,6 +170,7 @@ internal sealed partial class Planner command.AddRange(["-MD", "-MF", objectFile + ".d", "-c", source, "-o", objectFile]); var compile = new BuildAction { + Kind = ActionKind.Compile, Description = $"Compiling {target.Label} {relative}", Command = command, Directory = Layout.MainRoot, @@ -262,6 +263,7 @@ internal sealed partial class Planner command.AddRange(objects); var archive = new BuildAction { + Kind = ActionKind.Archive, Description = $"Archiving {target.Label}", Command = command, Directory = Layout.MainRoot, @@ -354,6 +356,7 @@ internal sealed partial class Planner command.AddRange(Options.LinkerOptions); var link = new BuildAction { + Kind = ActionKind.Link, Description = $"Linking {target.Label}", Command = command, Directory = Layout.MainRoot, diff --git a/src/Progmasoft.Tazel/Driver/Executor.cs b/src/Progmasoft.Tazel/Driver/Executor.cs index 977c156..fd086e1 100644 --- a/src/Progmasoft.Tazel/Driver/Executor.cs +++ b/src/Progmasoft.Tazel/Driver/Executor.cs @@ -17,7 +17,8 @@ namespace Progmasoft.Tazel.Driver; /// behind the back of the command. /// </summary> internal sealed class Executor( - int jobs, bool keepGoing, ActionCache cache, Reporter reporter, Cache.RemoteActions? remote = null) + int jobs, bool keepGoing, ActionCache cache, Reporter reporter, Cache.RemoteActions? remote = null, + CachePolicy policy = CachePolicy.Normal, string? scratch = null) { private readonly System.Collections.Concurrent.ConcurrentDictionary<BuildAction, bool> _made = new(); private int _done; @@ -96,7 +97,8 @@ internal sealed class Executor( /// </summary> private async Task<bool> MakeAsync(BuildAction action, int total, CancellationTokenSource stop) { - if (cache.IsCurrent(action)) + var forced = Forced(action); + if (!forced && cache.IsCurrent(action)) { action.After?.Invoke(); Interlocked.Increment(ref _done); @@ -111,25 +113,36 @@ internal sealed class Executor( File.Delete(full); } - cache.Forget(action); - if (remote is not null && await remote.FetchAsync(action, stop.Token).ConfigureAwait(false)) + // --no-cache writes no record, and so erases none: a later build checks the old one against the files. + var writes = policy != CachePolicy.NoCache; + if (writes) + { + cache.Forget(action); + } + else + { + cache.ForgetOutputs(action); + } + + if (!forced && remote is not null && await remote.FetchAsync(action, stop.Token).ConfigureAwait(false)) { Made(action, total, $"{action.Description} (remote cache)", "", record: true); return true; } - var result = action.Work is { } work - ? await work(stop.Token).ConfigureAwait(false) - : await Processes.RunAsync(action.Command, action.Directory, action.Environment, null, stop.Token) - .ConfigureAwait(false); + var result = await RunAsync(action, forced, stop.Token).ConfigureAwait(false); // Stopped because another action failed: that one is reported, this one did not fail. if (result.Canceled || await FailedAsync(action, result, stop).ConfigureAwait(false)) { return false; } - cache.Record(action); - if (remote is { Writes: true }) + if (writes) + { + cache.Record(action); + } + + if (writes && remote is { Writes: true }) { await remote.StoreAsync(action, stop.Token).ConfigureAwait(false); } @@ -138,6 +151,44 @@ internal sealed class Executor( return true; } + /// <summary> + /// Whether <paramref name="action"/> runs whatever the caches say: every action with <c>--no-cache</c>, the + /// compilations with <c>--recompile</c>. A link or an archive under <c>--recompile</c> runs only when the objects it + /// reads came out different. + /// </summary> + internal bool Forced(BuildAction action) => policy switch + { + CachePolicy.NoCache => true, + CachePolicy.Recompile => action.Kind is ActionKind.Compile or ActionKind.CompileAndLink, + _ => false, + }; + + // The action's work or command; a forced compilation with a cache of the compiler's own gets a fresh one, which + // is removed after. + private async Task<ProcessResult> RunAsync(BuildAction action, bool forced, CancellationToken cancel) + { + if (action.Work is { } work) + { + return await work(cancel).ConfigureAwait(false); + } + + if (!forced || action.WithCompilerCache is not { } withCache || scratch is null) + { + return await Processes.RunAsync(action.Command, action.Directory, action.Environment, null, cancel).ConfigureAwait(false); + } + + var fresh = Path.Combine(scratch, Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(fresh); + try + { + return await Processes.RunAsync(withCache(fresh), action.Directory, action.Environment, null, cancel).ConfigureAwait(false); + } + finally + { + Directory.Delete(fresh, recursive: true); + } + } + /// <summary>Marks <paramref name="action"/> made and says so; with <paramref name="record"/>, the local cache records it.</summary> private void Made(BuildAction action, int total, string description, string output, bool record) { diff --git a/src/Progmasoft.Tazel/Driver/TestRunner.cs b/src/Progmasoft.Tazel/Driver/TestRunner.cs index bb422a8..fa8bd0c 100644 --- a/src/Progmasoft.Tazel/Driver/TestRunner.cs +++ b/src/Progmasoft.Tazel/Driver/TestRunner.cs @@ -59,7 +59,7 @@ internal static class Runfiles } /// <summary>Runs tests: each with a small environment, its own temporary directory, a timeout, and retries when flaky.</summary> -internal sealed class TestRunner(OutputLayout layout, int jobs, Reporter reporter, bool coverage = false) +internal sealed class TestRunner(OutputLayout layout, int jobs, Reporter reporter, bool coverage = false, bool noCache = false) { /// <summary>The timeout of a size, as in Bazel.</summary> public static TimeSpan TimeoutOf(TestSize size) => size switch @@ -120,8 +120,8 @@ internal sealed class TestRunner(OutputLayout layout, int jobs, Reporter reporte var settings = (ITestSettings)target.Settings; var runfiles = Runfiles.Prepare(target, products, layout); var name = Sanitize(target.Label.ToString()); - // Coverage needs the run itself, and a test tagged no-cache runs every time. - var key = coverage || target.Settings.Tags.Contains("no-cache", StringComparer.Ordinal) + // Coverage needs the run itself, a test tagged no-cache runs every time, and so does every test of --no-cache. + var key = coverage || noCache || target.Settings.Tags.Contains("no-cache", StringComparer.Ordinal) ? null : CacheKey(target, settings, products, runfiles); var run = new TestRun(target, settings, products, runfiles, layout.Full($"{layout.TestLogs}/{name}"), @@ -131,7 +131,8 @@ internal sealed class TestRunner(OutputLayout layout, int jobs, Reporter reporte return cached; } - Forget(run); + // --no-cache keeps an earlier pass; only a failure below makes it untrue. + Forget(run, keepPass: noCache); var attempts = settings.Flaky ? 3 : 1; var watch = Stopwatch.StartNew(); var log = new StringBuilder(); @@ -153,13 +154,18 @@ internal sealed class TestRunner(OutputLayout layout, int jobs, Reporter reporte } } + if (File.Exists(run.Passed)) + { + File.Delete(run.Passed); + } + return new TestOutcome(run.Label, timedOut ? TestStatus.TimedOut : TestStatus.Failed, watch.Elapsed, log.ToString()); } - /// <summary>Clears what an earlier run left: its pass and its logs.</summary> - private static void Forget(TestRun run) + /// <summary>Clears what an earlier run left: its logs, and its pass unless <paramref name="keepPass"/>.</summary> + private static void Forget(TestRun run, bool keepPass) { - if (File.Exists(run.Passed)) + if (!keepPass && File.Exists(run.Passed)) { File.Delete(run.Passed); } diff --git a/src/Progmasoft.Tazel/Driver/ZigPlanner.cs b/src/Progmasoft.Tazel/Driver/ZigPlanner.cs index 0af514a..41356d2 100644 --- a/src/Progmasoft.Tazel/Driver/ZigPlanner.cs +++ b/src/Progmasoft.Tazel/Driver/ZigPlanner.cs @@ -188,8 +188,17 @@ internal sealed partial class Planner var inputs = AddModules(target, settings, defaultOptimization, includeDirectories, command); + // zig keeps what it compiled in its cache: a forced run gets a cache of its own, so it compiles again. + var cacheAt = command.IndexOf("--cache-dir") + 1; var action = new BuildAction { + Kind = ActionKind.CompileAndLink, + WithCompilerCache = fresh => + { + var forced = command.ToList(); + forced[cacheAt] = fresh; + return forced; + }, Description = $"{(target.Kind == TargetKind.Test ? "Building test" : "Compiling")} {target.Label}", Command = command, Directory = Layout.MainRoot, diff --git a/tests/Progmasoft.Tazel.Tests/CachePolicyTests.cs b/tests/Progmasoft.Tazel.Tests/CachePolicyTests.cs new file mode 100644 index 0000000..7c71738 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/CachePolicyTests.cs @@ -0,0 +1,177 @@ +// 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.Threading.Tasks; +using Progmasoft.Tazel.Cli; +using Progmasoft.Tazel.Driver; +using Progmasoft.Tazel.Output; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class CachePolicyTests +{ + private const string Build = """ + 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"] }); + CC.Test("math_test", new() { Sources = ["math_test.c"], Depends = ["//:math"] }); + """; + + private static TemporaryModule Sample() => new TemporaryModule() + .Write("MODULE.csx", TemporaryModule.ModuleFile) + .Write("BUILD.csx", Build) + .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") + .Write("math_test.c", "#include \"math.h\"\nint main(void) { return add(2, 2) == 4 ? 0 : 1; }\n"); + + private static async Task<string> Ok(TemporaryModule module, params string[] arguments) + { + var (status, output) = await module.TazelAsync(".", ["--color", "never", "--progress", "always", .. arguments]); + Assert.True(status == 0, output); + return output; + } + + private static int Count(string output, string what) => + output.Split('\n').Count(line => line.Contains(what, StringComparison.Ordinal)); + + [Fact] + public void TheFlagsBelongToTheBuildingCommandsOnly() + { + foreach (var command in new[] { "build", "run", "test", "coverage" }) + { + Assert.NotNull(CommandLine.Parse([command, "//...", "--recompile", "--no-cache"])); + } + + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["query", "//...", "--recompile"])); + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["clean", "--no-cache"])); + } + + [Fact] + public async Task RecompileCompilesAgainAndLinksOnlyWhatChanged() + { + Assert.SkipWhen(Host.Which("cc") is null && Host.Which("gcc") is null && Host.Which("clang") is null, "no C compiler"); + using var module = Sample(); + await Ok(module, "build", "//:app"); + Assert.Equal(0, Count(await Ok(module, "build", "//:app"), "Compiling")); + var forced = await Ok(module, "build", "//:app", "--recompile"); + Assert.Equal(2, Count(forced, "Compiling")); + // The objects came out the same, so the archive and the program are current. + Assert.Equal(0, Count(forced, "Archiving")); + Assert.Equal(0, Count(forced, "Linking")); + Assert.Equal(0, Count(await Ok(module, "build", "//:app"), "Compiling")); + } + + [Fact] + public async Task NoCacheRunsEverythingAndLeavesTheRecordsForTheNextBuild() + { + Assert.SkipWhen(Host.Which("cc") is null && Host.Which("gcc") is null && Host.Which("clang") is null, "no C compiler"); + using var module = Sample(); + await Ok(module, "build", "//:app"); + var records = Directory.EnumerateFiles(Path.Combine(module.Root, ".tazel"), "*.action", SearchOption.AllDirectories) + .ToDictionary(file => file, File.ReadAllText); + var forced = await Ok(module, "build", "//:app", "--no-cache"); + Assert.Equal(2, Count(forced, "Compiling")); + Assert.Equal(1, Count(forced, "Archiving")); + Assert.Equal(1, Count(forced, "Linking")); + // Nothing was written to the cache and nothing erased: the records are those of the first build. + Assert.All(records, entry => Assert.Equal(entry.Value, File.ReadAllText(entry.Key))); + var after = await Ok(module, "build", "//:app"); + Assert.Equal(0, Count(after, "Compiling") + Count(after, "Linking") + Count(after, "Archiving")); + } + + [Fact] + public async Task NoCacheRunsATestThatPassedAndKeepsItsPass() + { + Assert.SkipWhen(Host.Which("cc") is null && Host.Which("gcc") is null && Host.Which("clang") is null, "no C compiler"); + using var module = Sample(); + Assert.Contains("PASSED", await Ok(module, "test", "//:math_test"), StringComparison.Ordinal); + Assert.Contains("PASSED (cached)", await Ok(module, "test", "//:math_test"), StringComparison.Ordinal); + var forced = await Ok(module, "test", "//:math_test", "--no-cache"); + Assert.Contains("PASSED", forced, StringComparison.Ordinal); + Assert.DoesNotContain("(cached)", forced, StringComparison.Ordinal); + Assert.Contains("PASSED (cached)", await Ok(module, "test", "//:math_test"), StringComparison.Ordinal); + // --recompile leaves the test result cache to its own rules: the same program is the same test. + Assert.Contains("PASSED (cached)", await Ok(module, "test", "//:math_test", "--recompile"), StringComparison.Ordinal); + } + + [Fact] + public async Task NoCacheDominatesRecompile() + { + Assert.SkipWhen(Host.Which("cc") is null && Host.Which("gcc") is null && Host.Which("clang") is null, "no C compiler"); + using var module = Sample(); + await Ok(module, "build", "//:app"); + Assert.Equal(1, Count(await Ok(module, "build", "//:app", "--recompile", "--no-cache"), "Linking")); + } + + [Theory] + [InlineData("Normal", "Compile", false)] + [InlineData("Recompile", "Compile", true)] + [InlineData("Recompile", "CompileAndLink", true)] + [InlineData("Recompile", "Link", false)] + [InlineData("Recompile", "Archive", false)] + [InlineData("Recompile", "Step", false)] + [InlineData("NoCache", "Link", true)] + [InlineData("NoCache", "Step", true)] + public void ForcesWhatTheTableSays(string policy, string kind, bool forced) + { + 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, Enum.Parse<CachePolicy>(policy)); + var action = new BuildAction { Kind = Enum.Parse<ActionKind>(kind), Description = "x", Command = ["true"], Directory = ".", Inputs = [], Outputs = ["x"] }; + Assert.Equal(forced, executor.Forced(action)); + } + + [Fact] + public async Task AForcedCompilationGetsAFreshCompilerCacheThatIsRemovedAfter() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "the command is sh"); + using var module = new TemporaryModule(); + var scratch = Path.Combine(module.Root, "forced"); + string? seen = null; + var action = new BuildAction + { + Kind = ActionKind.CompileAndLink, + Description = "Compiling x", + // Run as written, it fails: only the command with the fresh cache writes the output. + Command = ["sh", "-c", "exit 3"], + WithCompilerCache = fresh => + { + seen = fresh; + return ["sh", "-c", $"test -d '{fresh}' && test -z \"$(ls -A '{fresh}')\" && echo made > out.o"]; + }, + Directory = module.Root, + Inputs = [], + Outputs = ["out.o"], + }; + 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.Recompile, scratch); + Assert.True(await executor.RunAsync([action], TestContext.Current.CancellationToken)); + Assert.NotNull(seen); + Assert.StartsWith(scratch, seen, StringComparison.Ordinal); + Assert.False(Directory.Exists(seen)); + Assert.Equal("made\n", File.ReadAllText(Path.Combine(module.Root, "out.o"))); + } + + [Fact] + public async Task ZigCompilesAgainUnderRecompile() + { + Assert.SkipWhen(Host.Which("zig") is null, "no zig on PATH"); + using var module = new TemporaryModule() + .Write("MODULE.csx", TemporaryModule.ModuleFile) + .Write("BUILD.csx", "using Progmasoft.Tazel.Dsl.Build.Prelude;\nZig.Executable(\"app\", new() { RootSourceFile = \"main.zig\" });\n") + .Write("main.zig", "pub fn main() void {}\n"); + await Ok(module, "build", "//:app"); + var zigCache = Path.Combine(module.Root, ".tazel", "zig-cache"); + var before = Directory.EnumerateFiles(zigCache, "*", SearchOption.AllDirectories).Count(); + var forced = await Ok(module, "build", "//:app", "--recompile"); + Assert.Equal(1, Count(forced, "Compiling //:app")); + // The run used a cache of its own, which is gone, and the module's zig cache took nothing from it. + Assert.Equal(before, Directory.EnumerateFiles(zigCache, "*", SearchOption.AllDirectories).Count()); + Assert.Empty(Directory.EnumerateFileSystemEntries(Path.Combine(module.Root, ".tazel", "forced"))); + } +}