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): move expunged caches to a Trash and clone large copies
- Commit
f97f2014b5187f0b0b2d6c4f450b67b26e2d1b04- Author
- Leitwolf11 ·
- Parents
0f38a394a852
Changes
CHANGELOG.md | 8 + docs/commands.md | 3 +- src/Progmasoft.Tazel/Cli/CommandLine.cs | 5 +- src/Progmasoft.Tazel/Cli/CommandMakers.cs | 36 +++ src/Progmasoft.Tazel/Cli/CommandTypes.cs | 4 + src/Progmasoft.Tazel/Cli/Commands.cs | 30 ++- src/Progmasoft.Tazel/Cli/Help.cs | 14 ++ src/Progmasoft.Tazel/Cli/ShellCompletion.cs | 1 + src/Progmasoft.Tazel/Cli/TrashCommands.cs | 73 ++++++ src/Progmasoft.Tazel/Driver/TestRunner.cs | 2 +- src/Progmasoft.Tazel/Output/ErrorCodes.cs | 6 + src/Progmasoft.Tazel/Progmasoft.Tazel.csproj | 2 + src/Progmasoft.Tazel/Program.cs | 6 + src/Progmasoft.Tazel/Project/FileClone.cs | 143 ++++++++++++ src/Progmasoft.Tazel/Project/Trash.cs | 325 +++++++++++++++++++++++++++ tests/Progmasoft.Tazel.Tests/TrashTests.cs | 207 +++++++++++++++++ 16 files changed, 852 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 74eefca..16e222d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,14 @@ ## Unreleased +- `tazel clean --expunge` moves `.tazel/` to `$TAZEL_HOME/Projects/<key>/Trash/.tazel-<fingerprint>`, named by the + SHA-256 of its contents, instead of deleting it; an entry is never overwritten, and a move across file systems is + copied, checked and only then deleted. New `tazel trash list|size|restore <fingerprint>|empty [--older-than <days>] + [--dry-run]` and error code `E0511`. +- Files copied by Tazel (test data now, cache outputs later) are cloned where the file system allows: `ioctl(FICLONE)` + on Linux (Btrfs, XFS, bcachefs) and `clonefile` on macOS (APFS), for files of 64 KiB and more; elsewhere they are + copied as before. Windows block cloning is not wired yet. + ## 0.5.0 - 2026-12-03 - Renamed the evaluation engine from `Progmasoft.Tazel.CedreCeleste` (`--cedre-celeste`) to `Progmasoft.Tazel.CadreCeleste` (`--cadre-celeste`, JSON key `cadreCeleste`). diff --git a/docs/commands.md b/docs/commands.md index 8dc4fec..1fb41b5 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -21,7 +21,8 @@ | `tazel ide compdb [labels] [-o <file>]` | writes a deterministic `compile_commands.json` for C/C++/ObjC targets (default `//...`) | | `tazel fetch` | downloads and checks the modules and plugins the module depends on, without building | | `tazel vendor` | copies the modules of Tazel Portal Modules and their indexes into `vendor/` | -| `tazel clean [--expunge] [--dry-run]` | removes the outputs, the test logs, zig's cache and the compiled project files; `--expunge` removes all of `.tazel`; `--dry-run` lists what would be removed without deleting | +| `tazel clean [--expunge] [--dry-run]` | removes the outputs, the test logs, zig's cache and the compiled project files; `--expunge` moves all of `.tazel` to the Trash (see `tazel trash`); `--dry-run` lists what would be removed or moved, and changes nothing | +| `tazel trash list\|size\|restore <fingerprint>\|empty [--older-than <days>] [--dry-run]` | the caches `clean --expunge` moved to `$TAZEL_HOME/Projects/<key>/Trash/`: lists them (newest first), sums their size, moves one back to its module's `.tazel/` (refused while one exists; a fingerprint is given by at least 8 digits), or removes them, all or those older than `--older-than` days | | `tazel cache keygen [--algorithm ed25519\|rsa-4096\|ml-dsa]` | prints a key pair for signing the results of a remote cache ([Remote cache](remote-cache.md)) | | `tazel cache validate [--remote]` | checks the records of `.tazel`, and with `--remote` the remote cache and its keys; changes nothing | | `tazel cache repair [--remote]` | removes broken records; with `--remote`, stores again what the remote cache lacks | diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs index 5e593e6..cbbe653 100644 --- a/src/Progmasoft.Tazel/Cli/CommandLine.cs +++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs @@ -20,7 +20,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", "new", "init", "git", "log", "doctor", "dump", "ide", "modules", "update", "fetch", "vendor", "clean", "package", "custom", + ["build", "run", "test", "coverage", "query", "cquery", "aquery", "new", "init", "git", "log", "doctor", "dump", "ide", "modules", "update", "fetch", "vendor", "clean", "trash", "package", "custom", "cache", "explain", "version", "help", "license", "shell-completion", "dotnet", "limited-time", "options", "custom-cmds", "envs", "tool", "ignore"]; private static readonly string[] Building = ["build", "run", "test", "coverage", "cquery", "aquery", "ide"]; @@ -38,7 +38,8 @@ internal static class CommandLine new("create", OptionKind.Flag, null, "options"), new("output-dir", OptionKind.Value, null, "tool", "package"), new("remote", OptionKind.Flag, null, "cache"), - new("dry-run", OptionKind.Flag, null, "clean"), + new("dry-run", OptionKind.Flag, null, "clean", "trash"), + new("older-than", OptionKind.Value, null, "trash"), new("force", OptionKind.Flag, null, "new", "init"), new("list", OptionKind.Flag, null, "package"), new("allow-dirty", OptionKind.Flag, null, "package"), diff --git a/src/Progmasoft.Tazel/Cli/CommandMakers.cs b/src/Progmasoft.Tazel/Cli/CommandMakers.cs index b094914..227da41 100644 --- a/src/Progmasoft.Tazel/Cli/CommandMakers.cs +++ b/src/Progmasoft.Tazel/Cli/CommandMakers.cs @@ -39,6 +39,7 @@ internal static class CommandMakers scanned.Has("offline") || scanned.Has("frozen"))), ["vendor"] = (scanned, output) => Bare(scanned, new VendorCommand(output)), ["clean"] = (scanned, output) => Bare(scanned, new CleanCommand(output, scanned.Has("expunge"), scanned.Has("dry-run"))), + ["trash"] = MakeTrash, ["package"] = (scanned, output) => Bare(scanned, new PackageCommand(output, scanned.Has("list"), scanned.Has("allow-dirty"), scanned.Last("output-dir"))), ["custom"] = (scanned, output) => scanned.Positional.Count == 0 ? throw new CommandLineException("tazel custom needs the name of a command of tazel_custom.txt") @@ -78,6 +79,41 @@ internal static class CommandMakers : throw new CommandLineException("tazel git takes add: tazel git add" + (scanned.Positional.Count > 0 && Suggestions.Nearest(scanned.Positional[0], ["add"]) is { } near ? $"; did you mean {near}?" : "")); + private static TrashCommand MakeTrash(ScannedCommand scanned, OutputOptions output) + { + var actions = new[] { "list", "size", "restore", "empty" }; + var action = scanned.Positional.Count > 0 ? scanned.Positional[0] : null; + if (action is null || !actions.Contains(action, StringComparer.Ordinal)) + { + var near = action is null ? null : Suggestions.Nearest(action, actions); + throw new CommandLineException( + $"tazel trash takes {string.Join(", ", actions)}{(near is null ? "" : $"; did you mean {near}?")}"); + } + + var expected = action == "restore" ? 2 : 1; + if (scanned.Positional.Count != expected) + { + throw new CommandLineException(action == "restore" + ? "tazel trash restore takes one fingerprint, as tazel trash list shows it" + : $"tazel trash {action} takes no other word"); + } + + if (action != "empty" && (scanned.Has("older-than") || scanned.Has("dry-run"))) + { + throw new CommandLineException("--older-than and --dry-run belong to tazel trash empty"); + } + + TimeSpan? olderThan = null; + if (scanned.Last("older-than") is { } days) + { + olderThan = int.TryParse(days, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var count) && count >= 0 + ? TimeSpan.FromDays(count) + : throw new CommandLineException($"--older-than takes a whole number of days, not '{days}'"); + } + + return new TrashCommand(output, action, expected == 2 ? scanned.Positional[1] : null, olderThan, scanned.Has("dry-run")); + } + private static Command MakeLog(ScannedCommand scanned, OutputOptions output) { var actions = new[] { "cache", "workspace", "what-ran", "what-failed", "what-up", "snoop", "daemon", "registries" }; diff --git a/src/Progmasoft.Tazel/Cli/CommandTypes.cs b/src/Progmasoft.Tazel/Cli/CommandTypes.cs index be55211..77da924 100644 --- a/src/Progmasoft.Tazel/Cli/CommandTypes.cs +++ b/src/Progmasoft.Tazel/Cli/CommandTypes.cs @@ -205,6 +205,10 @@ internal sealed record InitCommand(OutputOptions Output, bool Force) : Command(O /// <summary><c>tazel git add</c>: stages the module's files with system <c>git</c>.</summary> internal sealed record GitAddCommand(OutputOptions Output) : Command(Output); +/// <summary><c>tazel trash list|size|restore <fingerprint>|empty [--older-than <days>] [--dry-run]</c>.</summary> +internal sealed record TrashCommand(OutputOptions Output, string Action, string? Fingerprint, TimeSpan? OlderThan, bool DryRun) + : 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); diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index 657b878..4f34f5e 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -49,6 +49,7 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector 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)), + TrashCommand trash => Task.FromResult(new TrashCommands(reporter).Run(trash)), DoctorCommand => new DoctorCommands(reporter, TazelVersion).RunAsync(cancel), DumpCommand dump => new DumpCommands(reporter).RunAsync(dump, cancel), IdeCompdbCommand compdb => new IdeCommands(reporter, workingDirectory, TazelVersion).CompdbAsync(compdb), @@ -97,13 +98,13 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector case CleanCommand clean: return Clean(clean.Expunge, clean.DryRun); case CacheKeygenCommand keygen: - { - var (publicKey, signingKey) = Cache.CacheKey.Generate(keygen.Algorithm); - reporter.Plain($"PublicKey: {publicKey}"); - reporter.Plain($"SigningKey: {signingKey}"); - reporter.Status("give the PublicKey to every machine that reads; keep the SigningKey secret, for the machines that write"); - return 0; - } + { + var (publicKey, signingKey) = Cache.CacheKey.Generate(keygen.Algorithm); + reporter.Plain($"PublicKey: {publicKey}"); + reporter.Plain($"SigningKey: {signingKey}"); + reporter.Status("give the PublicKey to every machine that reads; keep the SigningKey secret, for the machines that write"); + return 0; + } default: throw new InvalidOperationException($"no handler for {command.GetType().Name}"); @@ -321,7 +322,18 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector reporter.Status(existing.Count == 0 ? "nothing to remove (dry run)" - : $"would remove {existing.Count} directories ({total} bytes)"); + : expunge + ? $"would move {state} to the Trash ({total} bytes)" + : $"would remove {existing.Count} directories ({total} bytes)"); + return 0; + } + + if (expunge && existing.Count > 0) + { + // USER, 2026-11-29: --expunge moves .tazel/ to the Trash instead of deleting it; tazel trash brings it back. + var entry = Project.Trash.MoveIn(root, state); + reporter.Success($"moved {state} to the Trash as {entry.Fingerprint[..12]} ({entry.Bytes} bytes); " + + $"tazel trash restore {entry.Fingerprint[..12]} brings it back"); return 0; } @@ -330,7 +342,7 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector Directory.Delete(directory, recursive: true); } - reporter.Success(expunge ? $"removed {state}" : "removed the outputs"); + reporter.Success(expunge ? $"{state} does not exist; nothing to move" : "removed the outputs"); return 0; } diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index 624b111..de55f7d 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -368,6 +368,20 @@ internal static class Help Stages MODULE.csx, reachable BUILD.csx files, target sources/headers/data, configuration files, LOCK.sqlite3, .tazelignore and .gitignore using system git add -- <paths>, respecting .gitignore. """), + ["trash"] = new("tazel trash list|size|restore|empty: caches moved by tazel clean --expunge.", """ + tazel trash list + tazel trash size + tazel trash restore <fingerprint> + tazel trash empty [--older-than <days>] [--dry-run] + + tazel clean --expunge moves .tazel/ to $TAZEL_HOME/Projects/<key>/Trash/.tazel-<fingerprint>, named by the + SHA-256 of its contents, instead of deleting it. + list every entry of every project, newest first: fingerprint, date, size, module + size the total size of the Trash + restore moves an entry back to its module's .tazel/; refused while that .tazel/ exists + 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 diff --git a/src/Progmasoft.Tazel/Cli/ShellCompletion.cs b/src/Progmasoft.Tazel/Cli/ShellCompletion.cs index c20549f..0b4c27d 100644 --- a/src/Progmasoft.Tazel/Cli/ShellCompletion.cs +++ b/src/Progmasoft.Tazel/Cli/ShellCompletion.cs @@ -75,6 +75,7 @@ internal static class ShellCompletion ("fetch", "Download and verify dependencies"), ("vendor", "Copy dependencies into vendor/"), ("clean", "Remove build outputs"), + ("trash", "List, measure, restore or empty caches moved by clean --expunge"), ("package", "Create a module archive"), ("custom", "Run a custom command from tazel_custom.txt"), ("cache", "Manage remote cache keys and validate or repair caches"), diff --git a/src/Progmasoft.Tazel/Cli/TrashCommands.cs b/src/Progmasoft.Tazel/Cli/TrashCommands.cs new file mode 100644 index 0000000..9145cf2 --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/TrashCommands.cs @@ -0,0 +1,73 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using Progmasoft.Tazel.Output; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Cli; + +/// <summary><c>tazel trash</c>: the caches that <c>tazel clean --expunge</c> moved to the Trash.</summary> +internal sealed class TrashCommands(Reporter reporter) +{ + public int Run(TrashCommand command) => command.Action switch + { + "list" => List(), + "size" => Size(), + "restore" => Restore(command.Fingerprint!), + _ => Empty(command), + }; + + private int List() + { + var entries = Trash.List(); + if (entries.Count == 0) + { + reporter.Status("the Trash is empty"); + return 0; + } + + reporter.Table( + ["fingerprint", "moved", "bytes", "module"], + [.. entries.Select(entry => (IReadOnlyList<string>)[ + entry.Fingerprint[..12], + entry.MovedAt.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) + " UTC", + entry.Bytes.ToString(CultureInfo.InvariantCulture), + entry.ModuleRoot, + ])]); + return 0; + } + + private int Size() + { + var entries = Trash.List(); + var total = entries.Sum(entry => entry.Bytes); + reporter.Plain($"{total.ToString(CultureInfo.InvariantCulture)} bytes in {entries.Count} entries"); + return 0; + } + + private int Restore(string fingerprint) + { + var entry = Trash.Find(fingerprint); + var state = Trash.Restore(entry); + reporter.Success($"restored {entry.Fingerprint[..12]} to {state}"); + return 0; + } + + private int Empty(TrashCommand command) + { + var removed = Trash.Empty(command.OlderThan, command.DryRun); + var bytes = removed.Sum(entry => entry.Bytes).ToString(CultureInfo.InvariantCulture); + foreach (var entry in removed) + { + reporter.Plain($"{entry.Fingerprint[..12]} {entry.ModuleRoot}"); + } + + reporter.Status(command.DryRun + ? $"would remove {removed.Count} entries ({bytes} bytes) (dry run)" + : $"removed {removed.Count} entries ({bytes} bytes)"); + return 0; + } +} diff --git a/src/Progmasoft.Tazel/Driver/TestRunner.cs b/src/Progmasoft.Tazel/Driver/TestRunner.cs index 9f4246d..c2515c7 100644 --- a/src/Progmasoft.Tazel/Driver/TestRunner.cs +++ b/src/Progmasoft.Tazel/Driver/TestRunner.cs @@ -38,7 +38,7 @@ internal static class Runfiles { var destination = Path.Combine(directory, file); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); - File.Copy(Path.Combine(target.Module.Root, file), destination); + Project.FileClone.Copy(Path.Combine(target.Module.Root, file), destination); } return directory; diff --git a/src/Progmasoft.Tazel/Output/ErrorCodes.cs b/src/Progmasoft.Tazel/Output/ErrorCodes.cs index 7131741..c91162a 100644 --- a/src/Progmasoft.Tazel/Output/ErrorCodes.cs +++ b/src/Progmasoft.Tazel/Output/ErrorCodes.cs @@ -91,6 +91,7 @@ internal static partial class ErrorCodes public const string CacheBroken = "E0508"; public const string License = "E0509"; public const string RegistriesInvalid = "E0510"; + public const string Trash = "E0511"; public const string Label = "E0600"; private const string Lexer = "the text files: tazel_custom.txt, tazel_options.txt and tazel_envs.txt"; @@ -351,6 +352,11 @@ internal static partial class ErrorCodes "when containing spaces) with indented quoted https://, tazel+https://, tazel+ssh://, or tazel:// URLs (no http://, " + "query, fragment, or embedded credentials); 'portal-modules' is a built-in keyword with no address line.", "1. custom\n \"http://tazel.example.com\"", "1. portal-modules\n2. \"Title Case\"\n \"https://tazel.example.com\"", "tazel_registries.txt"), + new(Trash, "a Trash operation that was refused", + "tazel clean --expunge moves .tazel/ to $TAZEL_HOME/Projects/<key>/Trash/.tazel-<fingerprint>, named by the " + + "SHA-256 of its contents. An entry is never overwritten, a restore needs the module's .tazel/ to be gone, and " + + "a fingerprint is given by at least 8 of its digits. A refused operation changes nothing.", + "tazel trash restore 3fa", "tazel trash restore 3fa2c41b", "tazel trash"), new(Label, "a label Tazel cannot read", "A label names a target: //dir:name, //:name, :name in the current package, @dependency//dir:name; //dir/... " + "and //... are patterns of packages. Names hold letters, digits and _ + . -.", diff --git a/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj b/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj index fa47255..3567933 100644 --- a/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj +++ b/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj @@ -8,6 +8,8 @@ <RootNamespace>Progmasoft.Tazel</RootNamespace> <ServerGarbageCollection>false</ServerGarbageCollection> <TieredPGO>true</TieredPGO> + <!-- [LibraryImport] (FileClone) generates unsafe marshalling code. --> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup> <ProjectReference Include="../Progmasoft.Tazel.CadreCeleste/Progmasoft.Tazel.CadreCeleste.csproj" /> diff --git a/src/Progmasoft.Tazel/Program.cs b/src/Progmasoft.Tazel/Program.cs index 0336e87..1feae48 100644 --- a/src/Progmasoft.Tazel/Program.cs +++ b/src/Progmasoft.Tazel/Program.cs @@ -99,6 +99,12 @@ internal static class Program "Tazel ignores many things, but not a file it cannot read."); return 1; } + catch (Project.TrashException error) + { + reporter.Error(ErrorCodes.Trash, error.Message, "tazel explain E0511 says how the Trash works", + "Nothing was thrown away, not even the error."); + return 1; + } catch (ToolException error) { reporter.Error(ErrorCodes.Tool, error.Message, "tazel explain E0507 says where Tazel looks for tools", diff --git a/src/Progmasoft.Tazel/Project/FileClone.cs b/src/Progmasoft.Tazel/Project/FileClone.cs new file mode 100644 index 0000000..2a28d0f --- /dev/null +++ b/src/Progmasoft.Tazel/Project/FileClone.cs @@ -0,0 +1,143 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Concurrent; +using System.IO; +using System.Runtime.InteropServices; + +namespace Progmasoft.Tazel.Project; + +/// <summary> +/// Copies a file by cloning it where the file system can (a reflink: the copy shares the original's blocks until one +/// of them is written), and by an ordinary copy everywhere else. A clone is safe for build outputs: writing to the copy +/// never changes the original, which is why hard links are never used instead. +/// </summary> +/// <remarks> +/// Linux uses <c>ioctl(FICLONE)</c> (Btrfs, XFS with reflink, bcachefs) and macOS <c>clonefile</c> (APFS). Windows +/// block cloning (ReFS, Dev Drive) is not wired yet, so Windows copies. A file system that refused a clone once is not +/// asked again during this process. +/// </remarks> +public static partial class FileClone +{ + /// <summary>Files smaller than this are copied: for them a copy costs less than the clone attempt.</summary> + public static long Threshold { get; } = 64 * 1024; + + private const uint FiClone = 0x40049409; + private const int OCreat = 0x40; + private const int OWronly = 0x01; + private const int OExcl = 0x80; + private const int ORdonly = 0x00; + + private static readonly ConcurrentDictionary<string, bool> Refused = new(StringComparer.Ordinal); + + /// <summary>How a file was copied.</summary> + public enum Result + { + /// <summary>Cloned: the copy shares the original's blocks.</summary> + Cloned, + + /// <summary>Copied byte by byte.</summary> + Copied, + } + + /// <summary> + /// Copies <paramref name="source"/> to <paramref name="destination"/>, which must not exist; clones it when it is + /// at least <see cref="Threshold"/> bytes and the file system allows. + /// </summary> + public static Result Copy(string source, string destination) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(destination); + var length = new FileInfo(source).Length; + if (length >= Threshold && TryClone(source, destination)) + { + return Result.Cloned; + } + + File.Copy(source, destination); + return Result.Copied; + } + + private static bool TryClone(string source, string destination) + { + var volume = Path.GetPathRoot(Path.GetFullPath(destination)) ?? ""; + var key = $"{volume}|{Path.GetDirectoryName(Path.GetFullPath(destination))}"; + if (Refused.ContainsKey(key)) + { + return false; + } + + bool cloned; + try + { + cloned = OperatingSystem.IsLinux() ? CloneLinux(source, destination) + : OperatingSystem.IsMacOS() && CloneMacOS(source, destination); + } + catch (DllNotFoundException) + { + cloned = false; + } + catch (EntryPointNotFoundException) + { + cloned = false; + } + + if (!cloned) + { + Refused[key] = true; + if (File.Exists(destination) && new FileInfo(destination).Length == 0) + { + // A failed FICLONE leaves the empty file it opened; the ordinary copy needs the path free. + File.Delete(destination); + } + } + + return cloned; + } + + private static bool CloneLinux(string source, string destination) + { + var from = Open(source, ORdonly, 0); + if (from < 0) + { + return false; + } + + try + { + var to = Open(destination, OWronly | OCreat | OExcl, Convert.ToInt32("644", 8)); + if (to < 0) + { + return false; + } + + try + { + return Ioctl(to, FiClone, from) == 0; + } + finally + { + _ = Close(to); + } + } + finally + { + _ = Close(from); + } + } + + private static bool CloneMacOS(string source, string destination) => CloneFile(source, destination, 0) == 0; + + [LibraryImport("libc", EntryPoint = "open", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)] + private static partial int Open(string path, int flags, int mode); + + [LibraryImport("libc", EntryPoint = "ioctl", SetLastError = true)] + private static partial int Ioctl(int fd, uint request, int argument); + + [LibraryImport("libc", EntryPoint = "close", SetLastError = true)] + private static partial int Close(int fd); + + [LibraryImport("libc", EntryPoint = "clonefile", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)] + private static partial int CloneFile(string source, string destination, uint flags); +} diff --git a/src/Progmasoft.Tazel/Project/Trash.cs b/src/Progmasoft.Tazel/Project/Trash.cs new file mode 100644 index 0000000..6fa6d51 --- /dev/null +++ b/src/Progmasoft.Tazel/Project/Trash.cs @@ -0,0 +1,325 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Progmasoft.Tazel.Dsl.Configuration; + +namespace Progmasoft.Tazel.Project; + +/// <summary> +/// The Trash of <c>.tazel/</c> directories: <c>tazel clean --expunge</c> moves a module's <c>.tazel/</c> to +/// <c>$TAZEL_HOME/Projects/<key>/Trash/.tazel-<fingerprint></c> instead of deleting it, and +/// <c>tazel trash</c> lists, measures, restores and empties what is there. +/// </summary> +/// <remarks> +/// The fingerprint is the SHA-256 of a canonical description of the directory's contents (relative paths in ordinal +/// order, each file's length and SHA-256, each symbolic link's target), so the same contents always get the same name. +/// An entry is never overwritten. A move across file systems copies, checks the copy's fingerprint, renames it into +/// place, and only then deletes the source. +/// </remarks> +public static class Trash +{ + /// <summary>The prefix of an entry's directory name.</summary> + public static string EntryPrefix { get; } = ".tazel-"; + + /// <summary>The suffix of the file beside an entry that records when and from where it came.</summary> + public static string InfoSuffix { get; } = ".info.json"; + + /// <summary>The shortest prefix of a fingerprint that <see cref="Find"/> accepts.</summary> + public static int MinimumPrefix { get; } = 8; + + /// <summary>One entry of a Trash.</summary> + /// <param name="Fingerprint">The 64 hexadecimal digits of the contents' SHA-256.</param> + /// <param name="Directory">The entry's directory.</param> + /// <param name="ModuleRoot">The canonical root of the module it came from.</param> + /// <param name="MovedAt">When it was moved in, in UTC.</param> + /// <param name="Bytes">The total size of its files.</param> + public sealed record Entry(string Fingerprint, string Directory, string ModuleRoot, DateTimeOffset MovedAt, long Bytes); + + /// <summary> + /// Moves <paramref name="state"/>, the <c>.tazel/</c> of the module rooted at <paramref name="moduleRoot"/>, into the + /// module's Trash and returns the new entry. Refuses, leaving the source as it is, when an entry with the same + /// fingerprint exists. + /// </summary> + public static Entry MoveIn(string moduleRoot, string state) + { + ArgumentNullException.ThrowIfNull(moduleRoot); + ArgumentNullException.ThrowIfNull(state); + var trash = Path.Combine(ProjectKey.Directory(moduleRoot, create: true), "Trash"); + Directory.CreateDirectory(trash); + var fingerprint = Fingerprint(state); + var destination = Path.Combine(trash, EntryPrefix + fingerprint); + if (Directory.Exists(destination) || File.Exists(destination)) + { + throw new TrashException( + $"{destination} already holds the same contents; nothing was moved, and {state} is unchanged. " + + $"Empty it first with tazel trash empty, or remove {state} yourself"); + } + + var bytes = Size(state); + Move(state, destination, fingerprint); + var info = new TrashInfo(ConfigurationResolver.Canonical(moduleRoot), DateTimeOffset.UtcNow, bytes); + WriteInfo(destination, info); + return new Entry(fingerprint, destination, info.ModuleRoot, info.MovedAt, bytes); + } + + /// <summary>Every entry of every project under <c>$TAZEL_HOME/Projects/</c>, newest first.</summary> + public static IReadOnlyList<Entry> List() + { + var projects = Path.Combine(TazelHome.Directory(), "Projects"); + if (!Directory.Exists(projects)) + { + return []; + } + + var entries = new List<Entry>(); + foreach (var trash in Directory.EnumerateDirectories(projects).Select(project => Path.Combine(project, "Trash"))) + { + if (!Directory.Exists(trash)) + { + continue; + } + + foreach (var directory in Directory.EnumerateDirectories(trash, EntryPrefix + "*")) + { + var name = Path.GetFileName(directory); + if (name.EndsWith(".partial", StringComparison.Ordinal)) + { + continue; + } + + entries.Add(ReadEntry(directory, name[EntryPrefix.Length..])); + } + } + + return [.. entries.OrderByDescending(entry => entry.MovedAt).ThenBy(entry => entry.Fingerprint, StringComparer.Ordinal)]; + } + + /// <summary>The entry whose fingerprint is or starts with <paramref name="prefix"/> (at least 8 digits).</summary> + public static Entry Find(string prefix) + { + ArgumentNullException.ThrowIfNull(prefix); + if (prefix.Length < MinimumPrefix || !prefix.All(Uri.IsHexDigit)) + { + throw new TrashException( + $"'{prefix}' is not a fingerprint: give at least {MinimumPrefix} hexadecimal digits, as tazel trash list shows them"); + } + + var matches = List().Where(entry => entry.Fingerprint.StartsWith(prefix.ToLowerInvariant(), StringComparison.Ordinal)).ToList(); + return matches.Count switch + { + 1 => matches[0], + 0 => throw new TrashException($"no Trash entry starts with {prefix}; tazel trash list shows them"), + _ => throw new TrashException( + $"{matches.Count} Trash entries start with {prefix}; give more digits: " + + string.Join(", ", matches.Select(entry => entry.Fingerprint[..12]))), + }; + } + + /// <summary> + /// Moves <paramref name="entry"/> back to the <c>.tazel/</c> of the module it came from. Refused while that + /// <c>.tazel/</c> exists or the module is gone. + /// </summary> + public static string Restore(Entry entry) + { + ArgumentNullException.ThrowIfNull(entry); + if (!Directory.Exists(entry.ModuleRoot)) + { + throw new TrashException($"{entry.ModuleRoot}, where this entry came from, no longer exists; nothing was restored"); + } + + var state = Path.Combine(entry.ModuleRoot, ModuleFiles.StateDirectory); + if (Directory.Exists(state) || File.Exists(state)) + { + throw new TrashException( + $"{state} exists; nothing was restored. Move it to Trash first with tazel clean --expunge"); + } + + Move(entry.Directory, state, entry.Fingerprint); + File.Delete(InfoPath(entry.Directory)); + return state; + } + + /// <summary> + /// Removes the entries moved in at least <paramref name="olderThan"/> ago (every entry when it is null) and returns + /// them; with <paramref name="dryRun"/>, only returns them. + /// </summary> + public static IReadOnlyList<Entry> Empty(TimeSpan? olderThan, bool dryRun) + { + var now = DateTimeOffset.UtcNow; + var chosen = List().Where(entry => olderThan is null || now - entry.MovedAt >= olderThan).ToList(); + if (!dryRun) + { + foreach (var entry in chosen) + { + Directory.Delete(entry.Directory, recursive: true); + File.Delete(InfoPath(entry.Directory)); + } + } + + return chosen; + } + + /// <summary>The fingerprint of a directory's contents: 64 lowercase hexadecimal digits.</summary> + public static string Fingerprint(string directory) + { + ArgumentNullException.ThrowIfNull(directory); + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var root = new DirectoryInfo(directory); + foreach (var item in root.EnumerateFileSystemInfos("*", new EnumerationOptions + { + RecurseSubdirectories = true, + AttributesToSkip = 0, + IgnoreInaccessible = false, + }).OrderBy(item => Relative(root, item), StringComparer.Ordinal)) + { + var relative = Relative(root, item); + if (item.LinkTarget is { } target) + { + Append(hash, $"L\0{relative}\0{target}\n"); + } + else if (item is DirectoryInfo) + { + Append(hash, $"D\0{relative}\n"); + } + else + { + var file = (FileInfo)item; + using var stream = file.OpenRead(); + var content = Convert.ToHexStringLower(SHA256.HashData(stream)); + Append(hash, $"F\0{relative}\0{file.Length.ToString(CultureInfo.InvariantCulture)}\0{content}\n"); + } + } + + return Convert.ToHexStringLower(hash.GetHashAndReset()); + } + + /// <summary>The total size of the files below <paramref name="directory"/>, symbolic links not followed.</summary> + public static long Size(string directory) => + new DirectoryInfo(directory) + .EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = 0 }) + .Where(file => file.LinkTarget is null) + .Sum(file => file.Length); + + /// <summary> + /// Moves <paramref name="source"/> to <paramref name="destination"/>: a rename on one file system; across file + /// systems a copy to <c><destination>.partial</c>, a check of its fingerprint, a rename, then the deletion of + /// the source. + /// </summary> + internal static void Move(string source, string destination, string fingerprint, bool forceCopy = false) + { + if (!forceCopy) + { + try + { + Directory.Move(source, destination); + return; + } + catch (IOException) when (Directory.Exists(source) && !Directory.Exists(destination)) + { + // Another file system: copy and check below. + } + } + + var partial = destination + ".partial"; + if (Directory.Exists(partial)) + { + Directory.Delete(partial, recursive: true); + } + + CopyTree(source, partial); + var copied = Fingerprint(partial); + if (copied != fingerprint) + { + Directory.Delete(partial, recursive: true); + throw new TrashException( + $"the copy of {source} differs from it ({copied[..12]} against {fingerprint[..12]}); nothing was moved"); + } + + Directory.Move(partial, destination); + Directory.Delete(source, recursive: true); + } + + private static void CopyTree(string source, string destination) + { + Directory.CreateDirectory(destination); + foreach (var item in new DirectoryInfo(source).EnumerateFileSystemInfos()) + { + var target = Path.Combine(destination, item.Name); + if (item.LinkTarget is { } link) + { + if (item is DirectoryInfo) + { + Directory.CreateSymbolicLink(target, link); + } + else + { + File.CreateSymbolicLink(target, link); + } + } + else if (item is DirectoryInfo) + { + CopyTree(item.FullName, target); + } + else + { + FileClone.Copy(item.FullName, target); + } + } + } + + private static Entry ReadEntry(string directory, string fingerprint) + { + var path = InfoPath(directory); + TrashInfo? info = null; + if (File.Exists(path)) + { + try + { + info = JsonSerializer.Deserialize(File.ReadAllText(path), TrashJsonContext.Default.TrashInfo); + } + catch (JsonException) + { + info = null; + } + } + + // Without its record the entry is still listed, dated by its directory and measured on the spot. + info ??= new TrashInfo("(unknown)", new DateTimeOffset(Directory.GetLastWriteTimeUtc(directory), TimeSpan.Zero), Size(directory)); + return new Entry(fingerprint, directory, info.ModuleRoot, info.MovedAt, info.Bytes); + } + + private static void WriteInfo(string entryDirectory, TrashInfo info) + { + var path = InfoPath(entryDirectory); + var partial = path + ".partial"; + File.WriteAllText(partial, JsonSerializer.Serialize(info, TrashJsonContext.Default.TrashInfo)); + File.Move(partial, path, overwrite: true); + } + + private static string InfoPath(string entryDirectory) => entryDirectory + InfoSuffix; + + private static string Relative(DirectoryInfo root, FileSystemInfo item) => + Path.GetRelativePath(root.FullName, item.FullName).Replace('\\', '/'); + + private static void Append(IncrementalHash hash, string text) => hash.AppendData(Encoding.UTF8.GetBytes(text)); + +} + +/// <summary>The record beside a Trash entry: where it came from, when, and how large it is.</summary> +internal sealed record TrashInfo(string ModuleRoot, DateTimeOffset MovedAt, long Bytes); + +[System.Text.Json.Serialization.JsonSerializable(typeof(TrashInfo))] +internal sealed partial class TrashJsonContext : System.Text.Json.Serialization.JsonSerializerContext +{ +} + +/// <summary>A Trash operation that was refused; nothing was changed.</summary> +public sealed class TrashException(string message) : Exception(message); diff --git a/tests/Progmasoft.Tazel.Tests/TrashTests.cs b/tests/Progmasoft.Tazel.Tests/TrashTests.cs new file mode 100644 index 0000000..92636bf --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/TrashTests.cs @@ -0,0 +1,207 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Threading.Tasks; +using Progmasoft.Tazel.Cli; +using Progmasoft.Tazel.Dsl.Configuration; +using Progmasoft.Tazel.Project; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +/// <summary>The Trash of .tazel/ directories and the copying it uses; they set TAZEL_HOME, so one at a time.</summary> +[Collection(nameof(TazelHomeCollection))] +public sealed class TrashTests : IDisposable +{ + private readonly string _was = Environment.GetEnvironmentVariable(TazelHome.Variable) ?? ""; + private readonly string _home = Path.Combine(Path.GetTempPath(), "tazel-trash-home-" + Guid.NewGuid().ToString("N")); + private readonly TemporaryModule _module = new(); + + public TrashTests() + { + Directory.CreateDirectory(_home); + Environment.SetEnvironmentVariable(TazelHome.Variable, _home); + _module.Write("MODULE.csx", TemporaryModule.ModuleFile); + } + + public void Dispose() + { + Environment.SetEnvironmentVariable(TazelHome.Variable, _was.Length == 0 ? null : _was); + _module.Dispose(); + Directory.Delete(_home, recursive: true); + } + + private string State => Path.Combine(_module.Root, ".tazel"); + + private void FillState(string text = "object code") + { + Directory.CreateDirectory(Path.Combine(State, "out", "lib")); + File.WriteAllText(Path.Combine(State, "out", "lib", "a.o"), text); + File.WriteAllText(Path.Combine(State, "notes.txt"), "kept"); + } + + private static async Task<(int Status, string Output)> RunAsync(string directory, params string[] args) + { + using var output = new StringWriter(); + var status = await Program.RunAsync(["--color", "never", .. args], directory, output, TestContext.Current.CancellationToken); + return (status, output.ToString()); + } + + [Fact] + public void TheFingerprintFollowsContentsAndNamesNotTimes() + { + FillState(); + var first = Trash.Fingerprint(State); + Assert.Matches("^[0-9a-f]{64}$", first); + File.SetLastWriteTimeUtc(Path.Combine(State, "notes.txt"), DateTime.UtcNow.AddDays(-3)); + Assert.Equal(first, Trash.Fingerprint(State)); + + File.WriteAllText(Path.Combine(State, "notes.txt"), "changed"); + Assert.NotEqual(first, Trash.Fingerprint(State)); + File.WriteAllText(Path.Combine(State, "notes.txt"), "kept"); + File.Move(Path.Combine(State, "notes.txt"), Path.Combine(State, "renamed.txt")); + Assert.NotEqual(first, Trash.Fingerprint(State)); + } + + [Fact] + public async Task ExpungeMovesTheCacheToTheTrashAndRestoreBringsItBack() + { + FillState(); + var fingerprint = Trash.Fingerprint(State); + + var (status, output) = await RunAsync(_module.Root, "clean", "--expunge"); + Assert.Equal(0, status); + Assert.False(Directory.Exists(State)); + Assert.Contains(fingerprint[..12], output, StringComparison.Ordinal); + + var entry = Assert.Single(Trash.List()); + Assert.Equal(fingerprint, entry.Fingerprint); + Assert.Equal(ConfigurationResolver.Canonical(_module.Root), entry.ModuleRoot); + Assert.Equal("object code".Length + "kept".Length, entry.Bytes); + + (status, output) = await RunAsync(_module.Root, "trash", "list"); + Assert.Equal(0, status); + Assert.Contains(fingerprint[..12], output, StringComparison.Ordinal); + + (status, output) = await RunAsync(_module.Root, "trash", "size"); + Assert.Equal(0, status); + Assert.Contains("15 bytes in 1 entries", output, StringComparison.Ordinal); + + (status, _) = await RunAsync(_module.Root, "trash", "restore", fingerprint[..10]); + Assert.Equal(0, status); + Assert.Equal("object code", File.ReadAllText(Path.Combine(State, "out", "lib", "a.o"))); + Assert.Empty(Trash.List()); + } + + [Fact] + public async Task RestoreIsRefusedWhileTheModuleHasACache() + { + FillState(); + await RunAsync(_module.Root, "clean", "--expunge"); + var entry = Assert.Single(Trash.List()); + FillState("a newer build"); + + var (status, output) = await RunAsync(_module.Root, "trash", "restore", entry.Fingerprint); + Assert.Equal(1, status); + Assert.Contains("E0511", output, StringComparison.Ordinal); + Assert.Equal("a newer build", File.ReadAllText(Path.Combine(State, "out", "lib", "a.o"))); + Assert.Single(Trash.List()); + } + + [Fact] + public async Task TheSameContentsTwiceAreRefusedAndLeaveTheSourceAlone() + { + FillState(); + await RunAsync(_module.Root, "clean", "--expunge"); + FillState(); + + var (status, output) = await RunAsync(_module.Root, "clean", "--expunge"); + Assert.Equal(1, status); + Assert.Contains("E0511", output, StringComparison.Ordinal); + Assert.True(File.Exists(Path.Combine(State, "out", "lib", "a.o"))); + Assert.Single(Trash.List()); + } + + [Fact] + public async Task EmptyHonoursOlderThanAndDryRun() + { + FillState(); + await RunAsync(_module.Root, "clean", "--expunge"); + + var (_, output) = await RunAsync(_module.Root, "trash", "empty", "--older-than", "1"); + Assert.Contains("removed 0 entries", output, StringComparison.Ordinal); + (_, output) = await RunAsync(_module.Root, "trash", "empty", "--dry-run"); + Assert.Contains("would remove 1 entries", output, StringComparison.Ordinal); + Assert.Single(Trash.List()); + + var (status, _) = await RunAsync(_module.Root, "trash", "empty"); + Assert.Equal(0, status); + Assert.Empty(Trash.List()); + } + + [Fact] + public void AMoveAcrossFileSystemsCopiesChecksAndOnlyThenDeletes() + { + FillState(); + var fingerprint = Trash.Fingerprint(State); + var destination = Path.Combine(_home, "moved"); + + Trash.Move(State, destination, fingerprint, forceCopy: true); + Assert.False(Directory.Exists(State)); + Assert.Equal(fingerprint, Trash.Fingerprint(destination)); + Assert.False(Directory.Exists(destination + ".partial")); + } + + [Fact] + public void AMoveWhoseCopyDiffersIsRefusedAndKeepsTheSource() + { + FillState(); + var destination = Path.Combine(_home, "moved"); + + Assert.Throws<TrashException>(() => Trash.Move(State, destination, new string('0', 64), forceCopy: true)); + Assert.True(File.Exists(Path.Combine(State, "out", "lib", "a.o"))); + Assert.False(Directory.Exists(destination)); + Assert.False(Directory.Exists(destination + ".partial")); + } + + [Theory] + [InlineData("trash")] + [InlineData("trash lst")] + [InlineData("trash restore")] + [InlineData("trash list --dry-run")] + [InlineData("trash empty --older-than soon")] + public void BadTrashCommandLinesAreRefused(string line) => + Assert.Throws<CommandLineException>(() => CommandLine.Parse(line.Split(' '))); + + [Fact] + public void AShortOrUnknownFingerprintIsRefused() + { + Assert.Throws<TrashException>(() => Trash.Find("abc")); + Assert.Throws<TrashException>(() => Trash.Find("0123456789")); + } + + [Theory] + [InlineData(10)] + [InlineData(200_000)] + public void FileCloneCopiesExactlyWhicheverWayItCopies(int length) + { + var bytes = new byte[length]; + new Random(length).NextBytes(bytes); + var source = Path.Combine(_home, "source.bin"); + var destination = Path.Combine(_home, "copy.bin"); + File.WriteAllBytes(source, bytes); + + var how = FileClone.Copy(source, destination); + Assert.Equal(bytes, File.ReadAllBytes(destination)); + if (length < FileClone.Threshold) + { + Assert.Equal(FileClone.Result.Copied, how); + } + + // Writing to the copy never changes the original, cloned or not. + File.WriteAllBytes(destination, [1, 2, 3]); + Assert.Equal(bytes, File.ReadAllBytes(source)); + } +}