File: TarTaskBase.cs
Web Access
Project: Microsoft.Build.Tasks.csproj (Microsoft.Build.Tasks.Core)
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Formats.Tar;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Threading;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Utilities;

namespace Microsoft.Build.Tasks
{
    /// <summary>
    /// Provides the parameters and the archive writing that are shared by the tasks that create tar archives,
    /// <see cref="TarDirectory"/> and <see cref="TarFiles"/>.
    /// </summary>
    /// <include file="TaskDocumentation.xml" path="doc/TarTaskRuntime/remarks" />
    public abstract class TarTaskBase : TaskExtension, ICancelableTask, IIncrementalTask, IMultiThreadableTask
    {
        /// <summary>
        /// Stores a <see cref="CancellationTokenSource"/> used for cancellation.
        /// </summary>
        private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();

        /// <summary>
        /// Initializes a new instance of the <see cref="TarTaskBase"/> class. Only the tasks in this assembly derive from it.
        /// </summary>
        private protected TarTaskBase()
        {
        }

        /// <summary>
        /// Gets or sets a <see cref="ITaskItem"/> with the path to the destination file to create.
        /// </summary>
        /// <remarks>
        /// The path parameters are exposed as <see cref="ITaskItem"/> rather than <see cref="DirectoryInfo"/>/
        /// <see cref="FileInfo"/> so that .NET Framework MSBuild can reflect over the task's parameters when
        /// dispatching it to the .NET task host. That inspection resolves parameter types through a
        /// <c>MetadataLoadContext</c> in which the only available core assembly is .NET Framework's, whose
        /// <c>System.Runtime</c> facade does not forward <see cref="FileInfo"/> or <see cref="DirectoryInfo"/>.
        /// </remarks>
        [Required]
        public ITaskItem DestinationFile { get; set; } = null!;

        /// <summary>
        /// Gets or sets a value indicating whether the destination file should be overwritten.
        /// </summary>
        public bool Overwrite { get; set; }

        /// <summary>
        /// Question the incremental nature of this task.
        /// </summary>
        /// <remarks>This task does not support incremental build and will error out instead.</remarks>
        public bool FailIfNotIncremental { get; set; }

        /// <summary>
        /// Gets or sets the compression to apply to the tar archive. Supported values are <c>None</c> (the default),
        /// <c>GZip</c> and <c>ZStandard</c>, matched case-insensitively.
        /// This parameter is optional; when empty, no compression is applied.
        /// </summary>
        /// <remarks>
        /// Like <see cref="Format"/>, this is typed as <see cref="string"/> rather than <see cref="TarDirectory.TarCompression"/>.
        /// When .NET Framework MSBuild dispatches the task to the .NET task host it resolves each parameter type in
        /// the parent process by assembly-qualified name; <see cref="TarDirectory.TarCompression"/> exists only in the
        /// .NET build of Microsoft.Build.Tasks.Core, so the lookup would bind against the .NET Framework build of that
        /// assembly and fail.
        /// </remarks>
        public string? Compression { get; set; }

        /// <summary>
        /// Gets or sets the tar entry format to use for the archive. Supported values are <c>Pax</c> (the default),
        /// <c>Ustar</c>, <c>V7</c> and <c>Gnu</c>, matched case-insensitively.
        /// This parameter is optional; when empty, <see cref="TarEntryFormat.Pax"/> is used. <c>Pax</c> archives aren't
        /// byte-for-byte reproducible across runs; see <see cref="DeterministicTimestamp"/>.
        /// </summary>
        /// <remarks>
        /// This is deliberately typed as <see cref="string"/> rather than <see cref="TarEntryFormat"/>. When .NET
        /// Framework MSBuild dispatches the task to the .NET task host it must still reflect over the task's
        /// parameters in the parent process, resolving parameter types through a <c>MetadataLoadContext</c> whose
        /// resolver only spans the task assembly's own directory, the MSBuild directory and the .NET Framework
        /// runtime directory. System.Formats.Tar ships in the shared framework and is in none of those, so exposing
        /// a type from it here would make the parameter unresolvable and fail the load in the parent.
        /// </remarks>
        public string? Format { get; set; }

        /// <summary>
        /// Gets or sets an optional timestamp to stamp on every entry in the archive in place of the source files'
        /// last-write times, so that the archive doesn't depend on when its sources were written.
        /// The value may be an RFC 3339 date-time (for example, <c>2024-01-01T00:00:00Z</c>) or an integer number of
        /// seconds since the Unix epoch (for example, <c>1704067200</c>, which is also the form of <c>SOURCE_DATE_EPOCH</c>).
        /// When empty, each entry keeps its source file's last-write time (entries are always written in a
        /// deterministic order regardless of this value).
        /// This parameter is optional.
        /// </summary>
        /// <remarks>
        /// When specified, the task constructs each entry itself: entries record owner and group ID <c>0</c> with empty names
        /// unless ownership is specified (see <see cref="OwnerId"/>), and hard-linked files are stored as separate regular files.
        /// For an archive that is byte-for-byte identical across runs, also use the <c>Gnu</c> or <c>Ustar</c>
        /// <see cref="Format"/>: System.Formats.Tar writes an extended attributes header before every <c>Pax</c> entry and
        /// includes the current process ID in its name.
        /// </remarks>
        public string? DeterministicTimestamp { get; set; }

        /// <summary>
        /// Gets or sets the numeric user ID to record as the owner of every entry in the archive, for example <c>0</c>.
        /// This parameter is optional.
        /// </summary>
        /// <remarks>
        /// By default, each entry records the owner of its source file on Unix, which ties the archive to the account that created
        /// it, and owner ID <c>0</c> on Windows. Entries that the task constructs itself, because <see cref="DeterministicTimestamp"/>
        /// or <c>UnixFileMode</c> metadata is specified, can't read the source owner and record owner and group ID <c>0</c> with
        /// empty names instead.
        /// When any of <see cref="OwnerId"/>, <see cref="GroupId"/>, <see cref="OwnerName"/> or <see cref="GroupName"/> is
        /// specified, every entry records exactly the specified ownership instead: an unspecified ID is recorded as <c>0</c> and
        /// an unspecified name is left empty, so that only the numeric IDs identify the owner (like <c>tar --numeric-owner</c>).
        /// Items of <see cref="TarFiles.SourceFiles"/> can override these parameters with metadata of the same names.
        /// Entries are then constructed the same way as with <see cref="DeterministicTimestamp"/>, so hard-linked files are stored
        /// as separate regular files.
        /// </remarks>
        public string? OwnerId { get; set; }

        /// <summary>
        /// Gets or sets the numeric group ID to record for every entry in the archive, for example <c>0</c>.
        /// This parameter is optional; see <see cref="OwnerId"/> for how the ownership parameters interact.
        /// </summary>
        public string? GroupId { get; set; }

        /// <summary>
        /// Gets or sets the user name to record as the owner of every entry in the archive, for example <c>root</c>.
        /// This parameter is optional and not supported by the <c>V7</c> <see cref="Format"/>; see <see cref="OwnerId"/> for how
        /// the ownership parameters interact.
        /// </summary>
        public string? OwnerName { get; set; }

        /// <summary>
        /// Gets or sets the group name to record for every entry in the archive, for example <c>root</c>.
        /// This parameter is optional and not supported by the <c>V7</c> <see cref="Format"/>; see <see cref="OwnerId"/> for how
        /// the ownership parameters interact.
        /// </summary>
        public string? GroupName { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether symbolic links and junctions are followed, like <c>tar --dereference</c>.
        /// A link to a file is then stored as a regular file with the contents and metadata of its target, and a link to a
        /// directory as a directory, whose contents <see cref="TarDirectory"/> adds too. By default, links are stored as links.
        /// </summary>
        /// <remarks>
        /// A link whose target doesn't exist or can't be resolved fails the task, as does a link in <see cref="TarDirectory"/>
        /// that leads back to a directory being archived. No archive is created in either case.
        /// </remarks>
        public bool FollowSymbolicLinks { get; set; }

        /// <inheritdoc />
        public TaskEnvironment TaskEnvironment { get; set; } = TaskEnvironment.Fallback;

        /// <summary>
        /// Gets the <see cref="DestinationFile"/> item resolved against the task's working directory.
        /// </summary>
        private protected FileInfo DestinationFileInfo { get; private set; } = null!;

        /// <inheritdoc cref="ICancelableTask.Cancel"/>
        public void Cancel()
        {
            _cancellationTokenSource.Cancel();
        }

        public override bool Execute()
        {
            // Evaluate all preconditions before yielding so that failures (which do no real work) don't
            // pay the cost of yielding and reacquiring the build engine node.
            if (!TryPrepare(out DateTimeOffset? deterministicTimestamp, out TarEntryFormat format, out TarDirectory.TarCompression compression, out TarOwnership? ownership))
            {
                return false;
            }

            // Yield() and Reacquire() must be called on the same thread, so they bracket the blocking wait here
            // rather than living inside the async method, whose continuations may resume on a thread-pool thread.
            BuildEngine3.Yield();

            try
            {
                // Bridge from the synchronous ITask.Execute entrypoint to the asynchronous implementation with a
                // single blocking call. The write pipeline is async so it can flow the cancellation token into the
                // runtime's asynchronous I/O; keeping the only GetAwaiter().GetResult() here (rather than in the
                // per-entry loop) avoids repeatedly blocking a thread-pool thread inside the loop.
                WriteArchiveAsync(deterministicTimestamp, format, compression, ownership)
                    .ConfigureAwait(continueOnCapturedContext: false)
                    .GetAwaiter()
                    .GetResult();
            }
            finally
            {
                BuildEngine3.Reacquire();
            }

            return !_cancellationTokenSource.IsCancellationRequested && !Log.HasLoggedErrors;
        }

        /// <summary>
        /// Resolves and validates the parameters that specify what to archive, logging an error for any failed precondition.
        /// </summary>
        /// <returns><see langword="true"/> when the archive can be written; otherwise <see langword="false"/>.</returns>
        private protected abstract bool TryResolveSources();

        /// <summary>
        /// Lets a task identify inputs that refer to the existing destination before it is unlinked.
        /// </summary>
        private protected virtual void BeforeOverwrite()
        {
        }

        /// <summary>
        /// Collects the entries to write to the archive, logging an error for any that can't be added.
        /// </summary>
        /// <param name="format">The tar entry format the archive is written in.</param>
        /// <param name="ownership">The ownership from the task's parameters, or <see langword="null"/> if none was specified.</param>
        /// <returns>The entries, sorted by name using an ordinal comparison so that the archive is deterministic.</returns>
        private protected abstract List<ArchiveEntry> CollectEntries(TarEntryFormat format, TarOwnership? ownership);

        /// <summary>
        /// Logs that the archive is being created.
        /// </summary>
        /// <param name="entryCount">The number of entries in the archive.</param>
        private protected abstract void LogCreatingArchive(int entryCount);

        /// <summary>
        /// Logs that the archive would be created, when incremental build was requested with <see cref="FailIfNotIncremental"/>.
        /// </summary>
        private protected abstract void LogFailIfNotIncremental();

        /// <summary>
        /// Logs that writing the archive failed.
        /// </summary>
        /// <param name="message">The error message.</param>
        /// <param name="lockedFileMessage">Information about processes that lock the destination file, if any.</param>
        private protected abstract void LogFailure(string message, string lockedFileMessage);

        /// <summary>
        /// Logs that a file, directory or link can't be added to the archive.
        /// </summary>
        /// <param name="sourcePath">The full path of the file, directory or link.</param>
        /// <param name="reasonResourceName">The resource with the reason; its MSBuild error code, if any, is removed.</param>
        /// <param name="args">The arguments of the reason.</param>
        private protected void LogCannotAddEntry(string sourcePath, string reasonResourceName, params object?[] args)
        {
            string reason = ResourceUtilities.FormatResourceStringStripCodeAndKeyword(reasonResourceName, args);
            Log.LogErrorWithCodeFromResources("TarTask.ErrorCannotAddEntry", sourcePath, reason);
        }

        /// <summary>
        /// Resolves ownership values, logging an error for any invalid value.
        /// </summary>
        /// <param name="ownerIdValue">The <see cref="OwnerId"/> value.</param>
        /// <param name="groupIdValue">The <see cref="GroupId"/> value.</param>
        /// <param name="ownerNameValue">The <see cref="OwnerName"/> value.</param>
        /// <param name="groupNameValue">The <see cref="GroupName"/> value.</param>
        /// <param name="format">The tar entry format the archive is written in.</param>
        /// <param name="sourcePath">
        /// The full path of the item whose metadata provided the values, or <see langword="null"/> for the task's parameters.
        /// </param>
        /// <param name="ownership">
        /// On success, the ownership to record, or <see langword="null"/> when no value was specified and each entry should
        /// record the owner of its source file.
        /// </param>
        /// <returns><see langword="true"/> if the values are valid; otherwise <see langword="false"/>.</returns>
        private protected bool TryResolveOwnership(string? ownerIdValue, string? groupIdValue, string? ownerNameValue, string? groupNameValue, TarEntryFormat format, string? sourcePath, out TarOwnership? ownership)
        {
            ownership = null;

            if (string.IsNullOrEmpty(ownerIdValue) && string.IsNullOrEmpty(groupIdValue) && string.IsNullOrEmpty(ownerNameValue) && string.IsNullOrEmpty(groupNameValue))
            {
                return true;
            }

            if (!TryParseId(ownerIdValue, nameof(OwnerId), out int ownerId) || !TryParseId(groupIdValue, nameof(GroupId), out int groupId))
            {
                return false;
            }

            if (format == TarEntryFormat.V7)
            {
                string? unsupportedName = !string.IsNullOrEmpty(ownerNameValue) ? nameof(OwnerName) : !string.IsNullOrEmpty(groupNameValue) ? nameof(GroupName) : null;
                if (unsupportedName is not null)
                {
                    ReportError(sourcePath is null ? "TarDirectory.OwnershipNameNotSupportedByFormat" : "TarTask.ReasonOwnershipNameNotSupportedByFormat", unsupportedName);

                    return false;
                }
            }

            // Check the values against the header fields of the format up front, rather than failing while writing the archive.
            if (!FitsFormat(nameof(OwnerId), ownerIdValue, IsIdTooLarge(ownerId))
                || !FitsFormat(nameof(GroupId), groupIdValue, IsIdTooLarge(groupId))
                || !FitsFormat(nameof(OwnerName), ownerNameValue, IsNameTooLong(ownerNameValue))
                || !FitsFormat(nameof(GroupName), groupNameValue, IsNameTooLong(groupNameValue)))
            {
                return false;
            }

            ownership = new TarOwnership(ownerId, groupId, ownerNameValue ?? string.Empty, groupNameValue ?? string.Empty);

            return true;

            bool TryParseId(string? value, string name, out int id)
            {
                id = 0;

                if (string.IsNullOrEmpty(value) || int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out id))
                {
                    return true;
                }

                ReportError("TarDirectory.InvalidOwnershipId", name, value);

                return false;
            }

            // V7 and Ustar headers store IDs as 7 octal digits; Gnu and Pax headers can store any value.
            bool IsIdTooLarge(int id) => format is TarEntryFormat.V7 or TarEntryFormat.Ustar && id > MaxOctalHeaderId;

            // Ustar and Gnu headers store names in 32 bytes; Pax headers can store any name.
            bool IsNameTooLong(string? name) => format is TarEntryFormat.Ustar or TarEntryFormat.Gnu && name is not null && Encoding.UTF8.GetByteCount(name) > MaxHeaderNameBytes;

            bool FitsFormat(string name, string? value, bool isTooLarge)
            {
                if (isTooLarge)
                {
                    ReportError("TarDirectory.OwnershipValueTooLargeForFormat", name, value, format.ToString());

                    return false;
                }

                return true;
            }

            void ReportError(string resourceName, params object?[] args)
            {
                if (sourcePath is null)
                {
                    Log.LogErrorWithCodeFromResources(resourceName, args);
                }
                else
                {
                    LogCannotAddEntry(sourcePath, resourceName, args);
                }
            }
        }

        /// <summary>
        /// Resolves the final target of a link that is followed, logging an error if it doesn't exist or can't be resolved.
        /// </summary>
        /// <param name="link">The link.</param>
        /// <param name="target">On success, the link's final target, as a <see cref="DirectoryInfo"/> if it's a directory.</param>
        /// <returns><see langword="true"/> if the target exists; otherwise <see langword="false"/>.</returns>
        private protected bool TryResolveFollowedLink(FileSystemInfo link, out FileSystemInfo target)
        {
            target = link;

            string? targetPath;
            if (!NativeMethodsShared.IsWindows)
            {
                // On Unix, ".." in a relative link target refers to the parent of the link's real location, which differs from
                // its parent as written when the link is reached through another link. ResolveLinkTarget joins the target to the
                // path as written, so let the operating system resolve the link instead.
                targetPath = NativeMethodsShared.RealPath(link.FullName);
                if (targetPath is null)
                {
                    // The link can't be followed. Don't fall back to the path as written, which may lead to a different file.
                    LogUnresolvableLink(link);
                    return false;
                }
            }
            else
            {
                try
                {
                    targetPath = link.ResolveLinkTarget(returnFinalTarget: true)?.FullName;
                }
                catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e))
                {
                    LogCannotAddEntry(link.FullName, "TarTask.ReasonSymbolicLinkCannotBeResolved", link.LinkTarget, e.Message);
                    return false;
                }

                if (targetPath is null)
                {
                    return true;
                }
            }

            if (Directory.Exists(targetPath))
            {
                target = new DirectoryInfo(targetPath);
            }
            else if (File.Exists(targetPath))
            {
                target = new FileInfo(targetPath);
            }
            else
            {
                LogCannotAddEntry(link.FullName, "TarTask.ReasonSymbolicLinkTargetDoesNotExist", link.LinkTarget);
                return false;
            }

            return true;
        }

        /// <summary>
        /// Gets the location of a directory with links resolved, as the operating system resolves them.
        /// </summary>
        private protected static string GetResolvedDirectoryPath(DirectoryInfo directory)
        {
            if (!NativeMethodsShared.IsWindows)
            {
                return NativeMethodsShared.RealPath(directory.FullName) ?? directory.FullName;
            }

            // ResolveLinkTarget only accepts a link in the final component. Find the nearest linked ancestor: the
            // final target returned by Windows resolves the path through that ancestor, and the suffix contains no links.
            for (DirectoryInfo? ancestor = directory; ancestor is not null; ancestor = ancestor.Parent)
            {
                if (ancestor.LinkTarget is not null && ancestor.ResolveLinkTarget(returnFinalTarget: true) is { } target)
                {
                    return Path.Join(target.FullName, directory.FullName.AsSpan(ancestor.FullName.Length).TrimStart(Path.DirectorySeparatorChar));
                }
            }

            return directory.FullName;
        }

        /// <summary>
        /// Compares the names of two existing entries, accounting for case sensitivity at each directory, not just on the host OS.
        /// Does not follow the final entry if it is a link.
        /// </summary>
        private protected static bool AreSameEntryPaths(ReadOnlySpan<char> left, ReadOnlySpan<char> right)
        {
            if (left.SequenceEqual(right))
            {
                return true;
            }

            if (!left.Equals(right, StringComparison.OrdinalIgnoreCase) || !Path.Exists(left.ToString()) || !Path.Exists(right.ToString()))
            {
                return false;
            }

            // Both paths exist. Compare the on-disk names only where the spellings differ: case sensitivity can
            // change between directories, even on the same volume.
            int start = Path.GetPathRoot(left).Length;
            while (start < left.Length)
            {
                int separator = left.Slice(start).IndexOf(Path.DirectorySeparatorChar);
                int length = separator < 0 ? left.Length - start : separator;
                ReadOnlySpan<char> name = left.Slice(start, length);
                ReadOnlySpan<char> otherName = right.Slice(start, length);
                if (!name.SequenceEqual(otherName))
                {
                    string parent = left.Slice(0, start).ToString();
                    string? actualName = GetOnDiskName(parent, name.ToString());
                    if (actualName is null || actualName != GetOnDiskName(parent, otherName.ToString()))
                    {
                        return false;
                    }
                }

                start += length + 1;
            }

            return true;
        }

        private static string? GetOnDiskName(string parent, string name)
        {
            string? match = null;
            bool ambiguous = false;
            foreach (string path in Directory.EnumerateFileSystemEntries(parent, name, s_caseInsensitiveLookup))
            {
                ReadOnlySpan<char> candidate = Path.GetFileName(path.AsSpan());
                if (candidate.SequenceEqual(name))
                {
                    return name;
                }

                // A Unix name may contain a wildcard. Don't treat an unrelated pattern match as the entry.
                if (candidate.Equals(name, StringComparison.OrdinalIgnoreCase))
                {
                    ambiguous |= match is not null;
                    match = candidate.ToString();
                }
            }

            return ambiguous ? null : match;
        }

        private static readonly EnumerationOptions s_caseInsensitiveLookup = new()
        {
            MatchCasing = MatchCasing.CaseInsensitive,
            AttributesToSkip = 0,
            IgnoreInaccessible = false,
        };

        /// <summary>
        /// Logs why a link that <c>realpath</c> couldn't resolve can't be followed: either its target doesn't exist, or it is part
        /// of a cycle of links.
        /// </summary>
        private void LogUnresolvableLink(FileSystemInfo link)
        {
            try
            {
                // Only used to choose the message; the path it returns is never archived.
                link.ResolveLinkTarget(returnFinalTarget: true);
            }
            catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e))
            {
                LogCannotAddEntry(link.FullName, "TarTask.ReasonSymbolicLinkCannotBeResolved", link.LinkTarget, e.Message);
                return;
            }

            LogCannotAddEntry(link.FullName, "TarTask.ReasonSymbolicLinkTargetDoesNotExist", link.LinkTarget);
        }

        /// <summary>
        /// Resolves the task's paths and validates its parameters, logging an error for any failed precondition.
        /// </summary>
        /// <returns><see langword="true"/> when the archive can be written; otherwise <see langword="false"/>.</returns>
        private bool TryPrepare(out DateTimeOffset? deterministicTimestamp, out TarEntryFormat format, out TarDirectory.TarCompression compression, out TarOwnership? ownership)
        {
            deterministicTimestamp = null;
            format = default;
            compression = default;
            ownership = null;

            DestinationFileInfo = new FileInfo(TaskEnvironment.GetAbsolutePath(DestinationFile.ItemSpec));

            if (!TryResolveSources())
            {
                return false;
            }

            // Check FailIfNotIncremental before the destination-exists handling below. In Question mode writing
            // the archive is itself the "not incremental" condition, so this must win over ErrorFileExists —
            // otherwise a pre-existing destination would surface the (incorrect) "delete or rename" advice instead
            // of the intended not-incremental error.
            if (FailIfNotIncremental)
            {
                LogFailIfNotIncremental();

                return false;
            }

            if (DestinationFileInfo.Exists)
            {
                if (!Overwrite)
                {
                    Log.LogErrorWithCodeFromResources("TarDirectory.ErrorFileExists", DestinationFileInfo.FullName);

                    return false;
                }

                try
                {
                    BeforeOverwrite();
                    File.Delete(DestinationFileInfo.FullName);
                }
                catch (Exception e)
                {
                    string lockedFileMessage = LockCheck.GetLockedFileMessage(DestinationFileInfo.FullName);
                    LogFailure(e.Message, lockedFileMessage);

                    return false;
                }
            }

            if (!TryGetDeterministicTimestamp(out deterministicTimestamp))
            {
                return false;
            }

            if (!TryGetEntryFormat(out format))
            {
                Log.LogErrorWithCodeFromResources("TarDirectory.InvalidFormat", Format);

                return false;
            }

            if (!TryGetCompression(out compression))
            {
                Log.LogErrorWithCodeFromResources("TarDirectory.InvalidCompression", Compression);

                return false;
            }

            if (!TryResolveOwnership(OwnerId, GroupId, OwnerName, GroupName, format, sourcePath: null, out ownership))
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// Asynchronously writes every source entry to the destination archive, logging an error on failure.
        /// </summary>
        private async System.Threading.Tasks.Task WriteArchiveAsync(DateTimeOffset? deterministicTimestamp, TarEntryFormat format, TarDirectory.TarCompression compression, TarOwnership? ownership)
        {
            try
            {
                // Collect and validate every entry before creating the archive, so that an entry that can't be added doesn't
                // leave a partial archive behind.
                List<ArchiveEntry> entries = CollectEntries(format, ownership);

                if (Log.HasLoggedErrors)
                {
                    return;
                }

                LogCreatingArchive(entries.Count);

                // Scope the write streams to this block so they are flushed and closed before Execute returns,
                // and — importantly — before the catch below attempts to delete a partially-written archive.
                // Use FileMode.Create rather than FileInfo.OpenWrite (which is FileMode.OpenOrCreate and does not
                // truncate): if a shorter archive is written over a pre-existing longer file, OpenOrCreate would
                // leave stale trailing bytes and produce a corrupt archive.
                using (FileStream destinationStream = new FileStream(DestinationFileInfo.FullName, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    // Wrap the destination stream in the requested compression, if any. The tar archive is always
                    // written to the (optionally compressed) stream, and the TarWriter is created with the requested
                    // TarEntryFormat so every entry is emitted in that format.
                    using Stream? compressionStream = compression switch
                    {
                        TarDirectory.TarCompression.GZip => new GZipStream(destinationStream, CompressionLevel.Optimal),
                        TarDirectory.TarCompression.ZStandard => new ZstandardStream(destinationStream, CompressionLevel.Optimal),
                        _ => null,
                    };

                    // Write the archive entry-by-entry (rather than the one-shot TarFile.CreateFromDirectory) so that the
                    // entries are emitted in a deterministic, ordinal-sorted order. When a deterministic timestamp, the
                    // ownership or the mode is supplied, each entry is constructed manually so that metadata can be overridden;
                    // otherwise per-entry metadata is written exactly as TarFile.CreateFromDirectory would via WriteEntry.
                    using TarWriter writer = new TarWriter(compressionStream ?? destinationStream, format, leaveOpen: true);

                    CancellationToken cancellationToken = _cancellationTokenSource.Token;

                    foreach (ArchiveEntry entry in entries)
                    {
                        // Check for cancellation on every iteration so a cancelled build stops promptly rather than
                        // writing out the entire remaining archive.
                        if (cancellationToken.IsCancellationRequested)
                        {
                            break;
                        }

                        if (deterministicTimestamp is not null || entry.Ownership is not null || entry.Mode is not null)
                        {
                            DateTimeOffset modificationTime = deterministicTimestamp ?? new DateTimeOffset(entry.Info.LastWriteTimeUtc);

                            // Overriding only the ownership or mode shouldn't change anything else, so use the Windows mode that
                            // WriteEntry records. DeterministicTimestamp has always kept the default mode for each entry type.
                            bool useDefaultWindowsMode = deterministicTimestamp is null;
                            await WriteConstructedEntryAsync(writer, format, entry.Info, entry.EntryName, modificationTime, entry.Ownership, entry.Mode, useDefaultWindowsMode, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
                        }
                        else
                        {
                            // Flow the cancellation token into the runtime's write so a large entry's stream copy
                            // can be interrupted mid-entry rather than only between entries.
                            await writer.WriteEntryAsync(entry.Info.FullName, entry.EntryName, cancellationToken)
                                .ConfigureAwait(continueOnCapturedContext: false);
                        }
                    }
                }

                // A break out of the loop above (rather than an OperationCanceledException from a mid-entry write)
                // leaves a truncated or empty archive on disk. The write streams are now flushed and closed, so the
                // file handle is released and the partial archive can be removed.
                if (_cancellationTokenSource.IsCancellationRequested)
                {
                    TryDeletePartialArchive();
                }
            }
            catch (OperationCanceledException) when (_cancellationTokenSource.IsCancellationRequested)
            {
                // A mid-entry write was interrupted by the cancellation token. Cancellation is a clean stop, not a
                // task failure to report; delete the partially-written archive and let Execute return false via the
                // IsCancellationRequested check.
                TryDeletePartialArchive();
            }
            catch (Exception e)
            {
                LogFailure(e.Message, string.Empty);

                // Best-effort cleanup of the partially-written archive so a subsequent non-Overwrite build does
                // not fail with "already exists" on a corrupt, incomplete file.
                TryDeletePartialArchive();
            }
        }

        /// <summary>
        /// Best-effort deletion of a partially-written destination archive. Any failure is swallowed: cleanup must
        /// not mask the real failure (an already-logged error, or a cancellation) that triggered it.
        /// </summary>
        private void TryDeletePartialArchive()
        {
            try
            {
                DestinationFileInfo.Refresh();
                if (DestinationFileInfo.Exists)
                {
                    DestinationFileInfo.Delete();
                }
            }
            catch
            {
                // Ignore: cleanup is best-effort and must not mask the real failure.
            }
        }

        /// <summary>
        /// Resolves the optional <see cref="DeterministicTimestamp"/> parameter, logging an error and returning
        /// <see langword="false"/> if it is specified but cannot be parsed.
        /// </summary>
        /// <param name="deterministicTimestamp">
        /// On success, the parsed timestamp, or <see langword="null"/> when no <see cref="DeterministicTimestamp"/> was
        /// specified.
        /// </param>
        /// <returns><see langword="true"/> if the timestamp was absent or parsed successfully; otherwise <see langword="false"/>.</returns>
        private bool TryGetDeterministicTimestamp(out DateTimeOffset? deterministicTimestamp)
        {
            deterministicTimestamp = null;

            if (string.IsNullOrEmpty(DeterministicTimestamp))
            {
                return true;
            }

            if (!TryParseTimestamp(DeterministicTimestamp, out DateTimeOffset parsedTimestamp))
            {
                Log.LogErrorWithCodeFromResources("TarDirectory.InvalidDeterministicTimestamp", DeterministicTimestamp);

                return false;
            }

            deterministicTimestamp = parsedTimestamp;

            return true;
        }

        /// <summary>
        /// Parses a <see cref="DeterministicTimestamp"/> value. The value may be an integer number of seconds since the
        /// Unix epoch, or an RFC 3339 date-time. Parsing is culture-invariant and always resolves to a UTC instant.
        /// </summary>
        private static bool TryParseTimestamp(string value, out DateTimeOffset timestamp)
        {
            // A bare integer is interpreted as the number of seconds since the Unix epoch. This matches the
            // SOURCE_DATE_EPOCH convention and NuGet's deterministic-timestamp handling.
            if (long.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out long unixTimeSeconds))
            {
                // Range-check before calling FromUnixTimeSeconds, which throws ArgumentOutOfRangeException for values
                // outside [DateTimeOffset.MinValue, DateTimeOffset.MaxValue]. A common mistake is to supply Unix
                // milliseconds (e.g. 1704067200000) here; treat that — and any other out-of-range value — as a parse
                // failure so the caller surfaces the intended InvalidDeterministicTimestamp error rather than crashing.
                if (unixTimeSeconds is < MinUnixTimeSeconds or > MaxUnixTimeSeconds)
                {
                    timestamp = default;

                    return false;
                }

                timestamp = DateTimeOffset.FromUnixTimeSeconds(unixTimeSeconds);

                return true;
            }

            return DateTimeOffset.TryParseExact(value, s_timestampFormats, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out timestamp);
        }

        /// <summary>
        /// Resolves <see cref="Format"/> to a <see cref="TarEntryFormat"/>. An empty value selects the
        /// <see cref="TarEntryFormat.Pax"/> default.
        /// </summary>
        /// <returns><see langword="true"/> when the value was empty or named a supported format.</returns>
        private bool TryGetEntryFormat(out TarEntryFormat format)
        {
            format = TarEntryFormat.Pax;

            if (string.IsNullOrWhiteSpace(Format))
            {
                return true;
            }

            if (!Enum.TryParse(Format, ignoreCase: true, out TarEntryFormat parsed) || !Enum.IsDefined(typeof(TarEntryFormat), parsed))
            {
                return false;
            }

            // Unknown is not a real on-disk format; treat it as the Pax default so an explicitly supplied
            // "Unknown" behaves as it did when this parameter was typed as TarEntryFormat.
            format = parsed == TarEntryFormat.Unknown ? TarEntryFormat.Pax : parsed;

            return true;
        }

        /// <summary>
        /// Resolves <see cref="Compression"/> to a <see cref="TarDirectory.TarCompression"/>. An empty value selects
        /// <see cref="TarDirectory.TarCompression.None"/>.
        /// </summary>
        /// <returns><see langword="true"/> when the value was empty or named a supported compression.</returns>
        private bool TryGetCompression(out TarDirectory.TarCompression compression)
        {
            compression = TarDirectory.TarCompression.None;

            if (string.IsNullOrWhiteSpace(Compression))
            {
                return true;
            }

            if (!Enum.TryParse(Compression, ignoreCase: true, out TarDirectory.TarCompression parsed) || !Enum.IsDefined(typeof(TarDirectory.TarCompression), parsed))
            {
                return false;
            }

            compression = parsed;

            return true;
        }

        /// <summary>
        /// Writes a single filesystem entry to the archive with the specified modification time, ownership and mode. The entry is
        /// constructed manually (rather than via <see cref="TarWriter.WriteEntry(string, string)"/>) so that this metadata can be
        /// overridden. Without <paramref name="mode"/>, the source file's Unix mode is preserved; on Windows, the entry gets
        /// <see cref="DefaultWindowsMode"/> like WriteEntry records when <paramref name="useDefaultWindowsMode"/> is set, and the
        /// default mode for its type otherwise. Without <paramref name="ownership"/>, owner ids default to 0 because .NET has no API
        /// to read a file's owner; this matches Windows behavior and is the conventional choice for a reproducible archive.
        /// </summary>
        private static async System.Threading.Tasks.Task WriteConstructedEntryAsync(TarWriter writer, TarEntryFormat format, FileSystemInfo info, string entryName, DateTimeOffset modificationTime, TarOwnership? ownership, UnixFileMode? mode, bool useDefaultWindowsMode, CancellationToken cancellationToken)
        {
            bool isSymbolicLink = info.LinkTarget is not null;
            bool isDirectory = info is DirectoryInfo && !isSymbolicLink;

            TarEntryType entryType = (isDirectory, isSymbolicLink, format) switch
            {
                (true, _, _) => TarEntryType.Directory,
                (_, true, _) => TarEntryType.SymbolicLink,
                (_, _, TarEntryFormat.V7) => TarEntryType.V7RegularFile,
                _ => TarEntryType.RegularFile,
            };

            TarEntry entry = CreateEntry(format, entryType, entryName);
            entry.ModificationTime = modificationTime;

            if (ownership is TarOwnership owner)
            {
                entry.Uid = owner.OwnerId;
                entry.Gid = owner.GroupId;

                // Only V7 entries can't store names, and specifying names with V7 is rejected up front.
                if (entry is PosixTarEntry posixEntry)
                {
                    posixEntry.UserName = owner.OwnerName;
                    posixEntry.GroupName = owner.GroupName;
                }
            }

            // Preserve the source's Unix permissions (for example, executable bits). This information does not exist on
            // Windows, where the entry gets either the mode WriteEntry records or the default mode for its type.
            if (!OperatingSystem.IsWindows())
            {
                if (!isSymbolicLink)
                {
                    entry.Mode = info.UnixFileMode;
                }
            }
            else if (useDefaultWindowsMode)
            {
                entry.Mode = DefaultWindowsMode;
            }

            if (mode is UnixFileMode overriddenMode)
            {
                entry.Mode = overriddenMode;
            }

            FileStream? dataStream = null;
            try
            {
                if (isSymbolicLink)
                {
                    entry.LinkName = info.LinkTarget ?? string.Empty;
                }
                else if (!isDirectory)
                {
                    dataStream = ((FileInfo)info).OpenRead();
                    entry.DataStream = dataStream;
                }

                await writer.WriteEntryAsync(entry, cancellationToken)
                    .ConfigureAwait(continueOnCapturedContext: false);
            }
            finally
            {
                dataStream?.Dispose();
            }
        }

        /// <summary>
        /// Creates a <see cref="TarEntry"/> of the concrete type that matches <paramref name="format"/>.
        /// </summary>
        private static TarEntry CreateEntry(TarEntryFormat format, TarEntryType entryType, string entryName) => format switch
        {
            TarEntryFormat.V7 => new V7TarEntry(entryType, entryName),
            TarEntryFormat.Ustar => new UstarTarEntry(entryType, entryName),
            TarEntryFormat.Gnu => new GnuTarEntry(entryType, entryName),
            _ => new PaxTarEntry(entryType, entryName),
        };

        /// <summary>
        /// The inclusive lower bound, in seconds since the Unix epoch, of the range accepted by
        /// <see cref="DateTimeOffset.FromUnixTimeSeconds(long)"/> — corresponding to <see cref="DateTimeOffset.MinValue"/>.
        /// </summary>
        private const long MinUnixTimeSeconds = -62135596800L;

        /// <summary>
        /// The inclusive upper bound, in seconds since the Unix epoch, of the range accepted by
        /// <see cref="DateTimeOffset.FromUnixTimeSeconds(long)"/> — corresponding to <see cref="DateTimeOffset.MaxValue"/>.
        /// </summary>
        private const long MaxUnixTimeSeconds = 253402300799L;

        /// <summary>
        /// The largest user or group ID that V7 and Ustar headers can store, as 7 octal digits.
        /// </summary>
        private const int MaxOctalHeaderId = (1 << 21) - 1;

        /// <summary>
        /// The number of bytes that Ustar and Gnu headers store user and group names in.
        /// </summary>
        private const int MaxHeaderNameBytes = 32;

        /// <summary>
        /// The mode that <see cref="TarWriter.WriteEntry(string, string)"/> records for every entry on Windows, where files don't
        /// have a Unix mode.
        /// </summary>
        private const UnixFileMode DefaultWindowsMode = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute
            | UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute;

        /// <summary>
        /// The RFC 3339 date-time formats accepted for <see cref="DeterministicTimestamp"/>, mirroring NuGet's
        /// deterministic-timestamp parsing.
        /// </summary>
        private static readonly string[] s_timestampFormats =
        [
            "yyyy-MM-dd'T'HH:mm:ss'Z'",
            "yyyy-MM-dd'T'HH:mm:sszzz",
            "yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK",
        ];

        /// <summary>
        /// The ownership recorded for an entry when any ownership parameter or metadata is specified.
        /// </summary>
        private protected readonly record struct TarOwnership(int OwnerId, int GroupId, string OwnerName, string GroupName);

        /// <summary>
        /// An entry to write to the archive.
        /// </summary>
        /// <param name="Info">The file, directory or link to write; for a link that is followed, its target.</param>
        /// <param name="EntryName">The name of the entry in the archive; directory names end with '/'.</param>
        /// <param name="SourcePath">The full path that the entry was found at, for messages.</param>
        /// <param name="Ownership">The ownership to record, or <see langword="null"/> to record the owner of the source.</param>
        /// <param name="Mode">The mode to record, or <see langword="null"/> for the default.</param>
        private protected readonly record struct ArchiveEntry(FileSystemInfo Info, string EntryName, string SourcePath, TarOwnership? Ownership, UnixFileMode? Mode);
    }
}