跳转到内容
标准库Zig 0.17.0官方原文
源码std/tar.zig

第 1 行

Tar 归档是一个普通文件,其中可以包含多个文件(或 目录、符号链接等)。它由一系列大小为 512 字节的块组成。每个条目的首块是头部,定义类型、名称、大小、 权限及其他属性。若条目有内容,头部后跟一系列 文件内容块。内容会填充至块大小, 因此下一个头部始终从块边界开始。

GNU 和 POSIX pax 扩展对此简单格式进行扩充,以支持 超过 256 字节的文件名和更多属性。

此处并非完整的 tar 解析器,仅实现 Zig 包管理器所需的 文件类型:普通文件、目录、符号链接, 以及部分属性:名称、大小和权限。

GNU tar 参考:https://www.gnu.org/software/tar/manual/html_node/Standard.html pax 参考:https://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html#tag_20_92_13

std.tar.assert

别名

第 21 行

别名目标 std.debug.assert

std.tar.builtin

常量

第 19 行

std.tar.createDirAndFile

函数

第 650 行

fn createDirAndFile(io: Io, dir: Io.Dir, file_name: []const u8, permissions: Io.File.Permissions) !Io.File

参数

io: Io
dir: Io.Dir
file_name: []const u8
permissions: Io.File.Permissions

std.tar.createDirAndSymlink

函数

第 664 行

fn createDirAndSymlink(io: Io, dir: Io.Dir, link_name: []const u8, file_name: []const u8) !void

参数

io: Io
dir: Io.Dir
link_name: []const u8
file_name: []const u8

std.tar.Diagnostics

容器

第 30 行

提供此结构体以接收详细错误消息。 提供后,某些原本会立即返回的错误 改为加入此结构体。API 用户必须检查诊断信息中的 错误,才能知道操作成功还是失败。

字段

allocator: std.mem.Allocator
errors: std.ArrayList(Error) = .empty
entries: usize = 0
root_dir: []const u8 = ""

std.tar.Diagnostics.deinit

函数

第 99 行

pub fn deinit(d: *Diagnostics) void

参数

std.tar.Diagnostics.Error

容器

第 37 行

字段

unable_to_create_sym_link: struct {
    code: anyerror,
    file_name: []const u8,
    link_name: []const u8,
}
unable_to_create_file: struct {
    code: anyerror,
    file_name: []const u8,
}
unsupported_file_type: struct {
    file_name: []const u8,
    file_type: Header.Kind,
}
components_outside_stripped_prefix: struct {
    file_name: []const u8,
}

std.tar.Diagnostics.findRoot

函数

第 56 行

fn findRoot(d: *Diagnostics, kind: FileKind, path: []const u8) !void

参数

d: *Diagnostics
kind: FileKind
path: []const u8

std.tar.Diagnostics.rootDir

函数

第 72 行

fn rootDir(path: []const u8, kind: FileKind) []const u8

参数

path: []const u8
kind: FileKind

用法示例

test rootDir {
    const expectEqualStrings = testing.expectEqualStrings;
    try expectEqualStrings("", rootDir("a", .file));
    try expectEqualStrings("a", rootDir("a", .directory));
    try expectEqualStrings("b", rootDir("b", .directory));
    try expectEqualStrings("c", rootDir("/c", .directory));
    try expectEqualStrings("d", rootDir("/d/", .directory));
    try expectEqualStrings("a", rootDir("a/b", .directory));
    try expectEqualStrings("a", rootDir("a/b", .file));
    try expectEqualStrings("a", rootDir("a/b/c", .directory));
}

std.tar.extract

函数

第 590 行

从 reader 读取 tar 文件,将文件内容填入 dir。 若任何文件将被提取到 dir 之外,则改为返回错误。

pub fn extract(io: Io, dir: Io.Dir, reader: *Io.Reader, options: ExtractOptions) !void

参数

io: Io
dir: Io.Dir
reader: *Io.Reader
options: ExtractOptions

用法示例

test extract {
    const io = testing.io;
    // 示例 tar 文件由以下目录树创建:
    // $ tree example
    //    example
    //    ├── a
    //    │   └── file
    //    ├── b
    //    │   └── symlink -> ../a/file
    //    └── empty
    // $ cat example/a/file
    //   content
    // $ tar -cf example.tar example
    // $ tar -tvf example.tar
    //    example/
    //    example/b/
    //    example/b/symlink -> ../a/file
    //    example/a/
    //    example/a/file
    //    example/empty/

    const data = @embedFile("tar/testdata/example.tar");
    var reader: Io.Reader = .fixed(data);

    var tmp = testing.tmpDir(.{ .follow_symlinks = false });
    defer tmp.cleanup();
    const dir = tmp.dir;

    // 将读取器中的 tar 保存至文件系统 `dir`
    extract(io, dir, &reader, .{
        .mode_mode = .ignore,
        .strip_components = 1,
        .exclude_empty_directories = true,
    }) catch |err| {
        // 在不支持符号链接的平台上跳过
        if (err == error.UnableToCreateSymLink) return error.SkipZigTest;
        return err;
    };

    try testing.expectError(error.FileNotFound, dir.statFile(io, "empty", .{}));
    try testing.expect((try dir.statFile(io, "a/file", .{})).kind == .file);
    try testing.expect((try dir.statFile(io, "b/symlink", .{})).kind == .file); // statFile 会跟随符号链接

    var buf: [32]u8 = undefined;
    try testing.expectEqualSlices(
        u8,
        "../a/file",
        normalizePath(buf[0..try dir.readLink(io, "b/symlink", &buf)]),
    );
}

std.tar.ExtractOptions

容器

第 126 行

字段

strip_components: u32 = 0

提取文件时跳过的目录层级数。

mode_mode: ModeMode = .executable_bit_only

如何处理 tar 文件中文件的“mode”属性。

exclude_empty_directories: bool = false

防止创建空目录。

diagnostics: ?*Diagnostics = null

收集解包时的错误消息

std.tar.ExtractOptions.ModeMode

容器

第 136 行

字段

ignore

完全忽略 tar 文件中的模式。 创建文件时使用默认文件模式。

executable_bit_only

仅检查 tar 文件权限模式中的所有者可执行位。 将此位复制到组和其他用户的可执行位。 创建文件时,模式的其他位保持默认值。

std.tar.FileKind

容器

第 301 行

迭代器 next 方法返回的文件类型。

字段

directory
sym_link
file

std.tar.filePermissions

函数

第 1167 行

fn filePermissions(mode: u32, options: ExtractOptions) Io.File.Permissions

参数

mode: u32
options: ExtractOptions

用法示例

test filePermissions {
    if (!Io.File.Permissions.has_executable_bit) return error.SkipZigTest;
    try testing.expectEqual(Io.File.Permissions.default_file, filePermissions(0o744, .{ .mode_mode = .ignore }));
    try testing.expectEqual(Io.File.Permissions.executable_file, filePermissions(0o744, .{}));
    try testing.expectEqual(Io.File.Permissions.default_file, filePermissions(0o644, .{}));
    try testing.expectEqual(Io.File.Permissions.default_file, filePermissions(0o655, .{}));
}

std.tar.Header

容器

第 147 行

字段

bytes: *const [SIZE]u8

std.tar.Header.checkChksum

函数

第 283 行

pub fn checkChksum(header: Header) !u64

参数

header: Header

std.tar.Header.chksum

函数

第 230 行

pub fn chksum(header: Header) !u64

参数

header: Header

std.tar.Header.Chksums

容器

第 263 行

字段

unsigned: u64
signed: i64

std.tar.Header.computeChksum

函数

第 270 行

fn computeChksum(header: Header) Chksums

参数

header: Header

std.tar.Header.fullName

函数

第 177 行

包含拼接的前缀(如果有)。 TODO: 检查 "../" 及其他恶意内容。

pub fn fullName(header: Header, buffer: []u8) ![]const u8

参数

header: Header
buffer: []u8

std.tar.Header.is_ustar

函数

第 234 行

pub fn is_ustar(header: Header) bool

参数

header: Header

std.tar.Header.kind

函数

第 243 行

pub fn kind(header: Header) Kind

参数

header: Header

std.tar.Header.Kind

容器

第 154 行

字段

normal_alias = 0
normal = '0'
hard_link = '1'
symbolic_link = '2'
character_special = '3'
block_special = '4'
directory = '5'
fifo = '6'
contiguous = '7'
global_extended_header = 'g'
extended_header = 'x'
gnu_long_name = 'L'
gnu_long_link = 'K'
gnu_sparse = 'S'
solaris_extended_header = 'X'
_

std.tar.Header.LINK_NAME_SIZE

常量

第 150 行

std.tar.Header.linkName

函数

第 193 行

当 kind 为 symbolic_link 时,链接目标名称(target_path)位于 linkname 字段。

pub fn linkName(header: Header, buffer: []u8) ![]const u8

参数

header: Header
buffer: []u8

std.tar.Header.MAX_NAME_SIZE

常量

第 149 行

std.tar.Header.mode

函数

第 208 行

pub fn mode(header: Header) !u32

参数

header: Header

std.tar.Header.name

函数

第 204 行

pub fn name(header: Header) []const u8

参数

header: Header

std.tar.Header.octal

函数

第 253 行

fn octal(header: Header, start: usize, len: usize) !u64

参数

header: Header
start: usize
len: usize

std.tar.Header.prefix

函数

第 239 行

pub fn prefix(header: Header) []const u8

参数

header: Header

std.tar.Header.size

函数

第 212 行

pub fn size(header: Header) !u64

参数

header: Header

std.tar.Header.SIZE

常量

第 148 行

std.tar.Header.str

函数

第 249 行

fn str(header: Header, start: usize, len: usize) []const u8

参数

header: Header
start: usize
len: usize

std.tar.Io

别名

第 20 行

别名目标 std.Io

std.tar.Iterator

容器

第 308 行

遍历 reader 所表示的 tar 文件中各条目的迭代器。

字段

reader: *Io.Reader
diagnostics: ?*Diagnostics = null
header_buffer: [Header.SIZE]u8 = undefined
file_name_buffer: []u8
link_name_buffer: []u8
padding: usize = 0
unread_file_bytes: u64 = 0

std.tar.Iterator.blockPadding

函数

第 379 行

fn blockPadding(size: u64) usize

参数

size: u64

std.tar.Iterator.File

容器

第 344 行

字段

name: []const u8
link_name: []const u8
size: u64 = 0
mode: u32 = 0
kind: FileKind = .file

std.tar.Iterator.init

函数

第 335 行

遍历 tar 归档中的文件。 next 返回 tar 归档中的每个文件。

pub fn init(reader: *Io.Reader, options: Options) Iterator

参数

reader: *Io.Reader
options: Options

std.tar.Iterator.newFile

函数

第 371 行

fn newFile(self: *Iterator) File

参数

self: *Iterator

std.tar.Iterator.next

函数

第 390 行

将 tar 归档视为一系列文件进行迭代。 在内部,tar 格式经常使用条目,即报头及可选内容,添加描述下一个文件的元数据。这些条目通常不应对外可见。 因此,此循环遍历一个或多个条目,直到收集到某个文件的全部属性。

pub fn next(self: *Iterator) !?File

参数

self: *Iterator

std.tar.Iterator.Options

容器

第 324 行

迭代器选项。 缓冲区应由调用方提供。

字段

file_name_buffer: []u8

使用长度为 std.fs.max_path_bytes 的缓冲区,以匹配文件系统能力。

link_name_buffer: []u8

使用长度为 std.fs.max_path_bytes 的缓冲区,以匹配文件系统能力。

diagnostics: ?*Diagnostics = null

收集解包时的错误消息

std.tar.Iterator.readHeader

函数

第 352 行

fn readHeader(self: *Iterator) !?Header

参数

self: *Iterator

std.tar.Iterator.readString

函数

第 364 行

fn readString(self: *Iterator, size: usize, buffer: []u8) ![]const u8

参数

self: *Iterator
size: usize
buffer: []u8

std.tar.Iterator.skipGnuSparseExtendedHeaders

函数

第 485 行

fn skipGnuSparseExtendedHeaders(self: *Iterator, header: Header) !void

参数

self: *Iterator
header: Header

std.tar.Iterator.streamRemaining

函数

第 480 行

pub fn streamRemaining(it: *Iterator, file: File, w: *Io.Writer) Io.Reader.StreamError!void

参数

it: *Iterator
file: File
w: *Io.Writer

错误

EndOfStream

Reader 指示流结束。此错误不会从 Writer 产生。

ReadFailed

详细诊断参见 Reader 的实现。

WriteFailed

详细诊断信息见 Writer 实现。

std.tar.normalizePath

函数

第 1159 行

fn normalizePath(bytes: []u8) []u8

参数

bytes: []u8

std.tar.nullStr

函数

第 293 行

fn nullStr(str: []const u8) []const u8

参数

str: []const u8

std.tar.pax_max_size_attr_len

常量

第 502 行

std.tar.PaxAttributeKind

容器

第 495 行

字段

path
linkpath
size

std.tar.PaxIterator

容器

第 504 行

字段

size: usize
reader: *Io.Reader

std.tar.PaxIterator.Attribute

容器

第 510 行

字段

kind: PaxAttributeKind
len: usize
reader: *Io.Reader

std.tar.PaxIterator.Attribute.value

函数

第 517 行

pub fn value(self: Attribute, dst: []u8) ![]const u8

参数

self: Attribute
dst: []u8

std.tar.PaxIterator.eql

函数

第 571 行

fn eql(a: []const u8, b: []const u8) bool

参数

a: []const u8
b: []const u8

std.tar.PaxIterator.hasNull

函数

第 575 行

fn hasNull(str: []const u8) bool

参数

str: []const u8

std.tar.PaxIterator.next

函数

第 531 行

pub fn next(self: *Self) !?Attribute

参数

self: *Self

std.tar.PaxIterator.Self

别名

第 508 行

别名目标 std.tar.PaxIterator

std.tar.PaxIterator.validateAttributeEnding

函数

第 580 行

fn validateAttributeEnding(reader: *Io.Reader) !void

参数

reader: *Io.Reader

std.tar.PipeOptions

别名

第 124 行

已弃用,已重命名为 ExtractOptions。

别名目标 std.tar.ExtractOptions

std.tar.pipeToFileSystem

别名

第 586 行

已弃用,重命名为 extract。

别名目标 std.tar.extract

std.tar.sanitizePath

函数

第 676 行

fn sanitizePath(buffer: []u8, path: []const u8, strip_components: u32) error{Invalid}!usize

参数

buffer: []u8
path: []const u8
strip_components: u32

错误

Invalid

用法示例

test sanitizePath {
    try testSanitizePath("a/b/c", "a/b/c", 0);
    try testSanitizePath("a/b/c", "a/x/y/../../b/c", 0);
    try testSanitizePath("b/c", "a/b/c", 1);
    try testSanitizePath("c", "a/b/c", 2);
    try testSanitizePath("", "a/b/c", 3);
    try testSanitizePath("", "a/b/c/../../..", 0);
    try testSanitizePathError(error.Invalid, "a/b/c", 4);
    try testSanitizePathError(error.Invalid, "..", 0);
    try testSanitizePathError(error.Invalid, "a/b/../../..", 0);
    try testSanitizePathError(error.Invalid, "a/b/../..", 1);
}

std.tar.std

别名

第 18 行

别名目标 std

std.tar.testing

别名

第 22 行

别名目标 std.testing

std.tar.testSanitizePath

函数

第 707 行

fn testSanitizePath(expected: []const u8, input: []const u8, strip: u32) !void

参数

expected: []const u8
input: []const u8
strip: u32

std.tar.testSanitizePathError

函数

第 713 行

fn testSanitizePathError(expected: anyerror, input: []const u8, strip: u32) !void

参数

expected: anyerror
input: []const u8
strip: u32

std.tar.Writer

别名

第 24 行

别名目标 std.tar.Writer

源码

std/tar.zig

//! Tar 归档是一个普通文件,其中可以包含多个文件(或
//! 目录、符号链接等)。它由一系列大小为 512
//! 字节的块组成。每个条目的首块是头部,定义类型、名称、大小、
//! 权限及其他属性。若条目有内容,头部后跟一系列
//! 文件内容块。内容会填充至块大小,
//! 因此下一个头部始终从块边界开始。
//!
//! GNU 和 POSIX pax 扩展对此简单格式进行扩充,以支持
//! 超过 256 字节的文件名和更多属性。
//!
//! 此处并非完整的 tar 解析器,仅实现 Zig 包管理器所需的
//! 文件类型:普通文件、目录、符号链接,
//! 以及部分属性:名称、大小和权限。
//!
//! GNU tar 参考:https://www.gnu.org/software/tar/manual/html_node/Standard.html
//! pax 参考:https://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html#tag_20_92_13

const std = @import("std");
const builtin = @import("builtin");
const Io = std.Io;
const assert = std.debug.assert;
const testing = std.testing;

pub const Writer = @import("tar/Writer.zig");

/// 提供此结构体以接收详细错误消息。
/// 提供后,某些原本会立即返回的错误
/// 改为加入此结构体。API 用户必须检查诊断信息中的
/// 错误,才能知道操作成功还是失败。
pub const Diagnostics = struct {
    allocator: std.mem.Allocator,
    errors: std.ArrayList(Error) = .empty,

    entries: usize = 0,
    root_dir: []const u8 = "",

    pub const Error = union(enum) {
        unable_to_create_sym_link: struct {
            code: anyerror,
            file_name: []const u8,
            link_name: []const u8,
        },
        unable_to_create_file: struct {
            code: anyerror,
            file_name: []const u8,
        },
        unsupported_file_type: struct {
            file_name: []const u8,
            file_type: Header.Kind,
        },
        components_outside_stripped_prefix: struct {
            file_name: []const u8,
        },
    };

    fn findRoot(d: *Diagnostics, kind: FileKind, path: []const u8) !void {
        if (path.len == 0) return;

        d.entries += 1;
        const root_dir = rootDir(path, kind);
        if (d.entries == 1) {
            d.root_dir = try d.allocator.dupe(u8, root_dir);
            return;
        }
        if (d.root_dir.len == 0 or std.mem.eql(u8, root_dir, d.root_dir))
            return;
        d.allocator.free(d.root_dir);
        d.root_dir = "";
    }

    // 返回路径的根目录,假定路径非空。
    fn rootDir(path: []const u8, kind: FileKind) []const u8 {
        const start_index: usize = if (path[0] == '/') 1 else 0;
        const end_index: usize = if (path[path.len - 1] == '/') path.len - 1 else path.len;
        const buf = path[start_index..end_index];
        if (std.mem.findScalarPos(u8, buf, 0, '/')) |idx| {
            return buf[0..idx];
        }

        return switch (kind) {
            .file => "",
            .sym_link => "",
            .directory => buf,
        };
    }

    test rootDir {
        const expectEqualStrings = testing.expectEqualStrings;
        try expectEqualStrings("", rootDir("a", .file));
        try expectEqualStrings("a", rootDir("a", .directory));
        try expectEqualStrings("b", rootDir("b", .directory));
        try expectEqualStrings("c", rootDir("/c", .directory));
        try expectEqualStrings("d", rootDir("/d/", .directory));
        try expectEqualStrings("a", rootDir("a/b", .directory));
        try expectEqualStrings("a", rootDir("a/b", .file));
        try expectEqualStrings("a", rootDir("a/b/c", .directory));
    }

    pub fn deinit(d: *Diagnostics) void {
        for (d.errors.items) |item| {
            switch (item) {
                .unable_to_create_sym_link => |info| {
                    d.allocator.free(info.file_name);
                    d.allocator.free(info.link_name);
                },
                .unable_to_create_file => |info| {
                    d.allocator.free(info.file_name);
                },
                .unsupported_file_type => |info| {
                    d.allocator.free(info.file_name);
                },
                .components_outside_stripped_prefix => |info| {
                    d.allocator.free(info.file_name);
                },
            }
        }
        d.errors.deinit(d.allocator);
        d.allocator.free(d.root_dir);
        d.* = undefined;
    }
};

/// 已弃用,已重命名为 `ExtractOptions`。
pub const PipeOptions = ExtractOptions;

pub const ExtractOptions = struct {
    /// 提取文件时跳过的目录层级数。
    strip_components: u32 = 0,
    /// 如何处理 tar 文件中文件的“mode”属性。
    mode_mode: ModeMode = .executable_bit_only,
    /// 防止创建空目录。
    exclude_empty_directories: bool = false,
    /// 收集解包时的错误消息
    diagnostics: ?*Diagnostics = null,

    pub const ModeMode = enum {
        /// 完全忽略 tar 文件中的模式。
        /// 创建文件时使用默认文件模式。
        ignore,
        /// 仅检查 tar 文件权限模式中的所有者可执行位。
        /// 将此位复制到组和其他用户的可执行位。
        /// 创建文件时,模式的其他位保持默认值。
        executable_bit_only,
    };
};

const Header = struct {
    const SIZE = 512;
    const MAX_NAME_SIZE = 100 + 1 + 155; // name(100) + separator(1) + prefix(155)
    const LINK_NAME_SIZE = 100;

    bytes: *const [SIZE]u8,

    const Kind = enum(u8) {
        normal_alias = 0,
        normal = '0',
        hard_link = '1',
        symbolic_link = '2',
        character_special = '3',
        block_special = '4',
        directory = '5',
        fifo = '6',
        contiguous = '7',
        global_extended_header = 'g',
        extended_header = 'x',
        // GNU 格式使用类型“L”和“K”表示元文件,
        // 用于存储下一个文件的路径或链接名称。
        gnu_long_name = 'L',
        gnu_long_link = 'K',
        gnu_sparse = 'S',
        solaris_extended_header = 'X',
        _,
    };

    /// 包含拼接的前缀(如果有)。
    /// TODO: 检查 "../" 及其他恶意内容。
    pub fn fullName(header: Header, buffer: []u8) ![]const u8 {
        const n = name(header);
        const p = prefix(header);
        if (buffer.len < n.len + p.len + 1) return error.TarInsufficientBuffer;
        if (!is_ustar(header) or p.len == 0) {
            @memcpy(buffer[0..n.len], n);
            return buffer[0..n.len];
        }
        @memcpy(buffer[0..p.len], p);
        buffer[p.len] = '/';
        @memcpy(buffer[p.len + 1 ..][0..n.len], n);
        return buffer[0 .. p.len + 1 + n.len];
    }

    /// 当 kind 为 symbolic_link 时,链接目标名称(target_path)位于 linkname 字段。
    ///
    pub fn linkName(header: Header, buffer: []u8) ![]const u8 {
        const link_name = header.str(157, 100);
        if (link_name.len == 0) {
            return buffer[0..0];
        }
        if (buffer.len < link_name.len) return error.TarInsufficientBuffer;
        const buf = buffer[0..link_name.len];
        @memcpy(buf, link_name);
        return buf;
    }

    pub fn name(header: Header) []const u8 {
        return header.str(0, 100);
    }

    pub fn mode(header: Header) !u32 {
        return @intCast(try header.octal(100, 8));
    }

    pub fn size(header: Header) !u64 {
        const start = 124;
        const len = 12;
        const raw = header.bytes[start..][0..len];
        // 若首字节为 0xff(255),则将该字段的所有字节
        // (包括首字节)按大端序拼接,
        // 得到的结果为以二进制补码形式
        // 表示的负数。
        if (raw[0] == 0xff) return error.TarNumericValueNegative;
        // 若首字节为 0x80(128),则将字段中的
        // 其余字节按大端序连接。
        if (raw[0] == 0x80) {
            if (raw[1] != 0 or raw[2] != 0 or raw[3] != 0) return error.TarNumericValueTooBig;
            return std.mem.readInt(u64, raw[4..12], .big);
        }
        return try header.octal(start, len);
    }

    pub fn chksum(header: Header) !u64 {
        return header.octal(148, 8);
    }

    pub fn is_ustar(header: Header) bool {
        const magic = header.bytes[257..][0..6];
        return std.mem.eql(u8, magic[0..5], "ustar") and (magic[5] == 0 or magic[5] == ' ');
    }

    pub fn prefix(header: Header) []const u8 {
        return header.str(345, 155);
    }

    pub fn kind(header: Header) Kind {
        const result: Kind = @fromBackingInt(@intCast(header.bytes[156]));
        if (result == .normal_alias) return .normal;
        return result;
    }

    fn str(header: Header, start: usize, len: usize) []const u8 {
        return nullStr(header.bytes[start .. start + len]);
    }

    fn octal(header: Header, start: usize, len: usize) !u64 {
        const raw = header.bytes[start..][0..len];
        // 以零填充的 ASCII 八进制数。宽度为 w 的每个数值字段
        // 包含 w 减 1 个数字,以及一个空字符。
        const ltrimmed = std.mem.trimStart(u8, raw, "0 ");
        const rtrimmed = std.mem.trimEnd(u8, ltrimmed, " \x00");
        if (rtrimmed.len == 0) return 0;
        return std.fmt.parseInt(u64, rtrimmed, 8) catch return error.TarHeader;
    }

    const Chksums = struct {
        unsigned: u64,
        signed: i64,
    };

    // 头部块所有字节的总和。chksum 字段按
    // 全部填充为空格(ASCII 32)处理。
    fn computeChksum(header: Header) Chksums {
        var cs: Chksums = .{ .signed = 0, .unsigned = 0 };
        for (header.bytes, 0..) |v, i| {
            const b = if (148 <= i and i < 156) 32 else v; // 将校验和字节视为空格。
            cs.unsigned += b;
            cs.signed += @as(i8, @bitCast(b));
        }
        return cs;
    }

    // 比较计算得到的 chksum 与 chksum 字段值。
    // 返回错误或有效的 chksum 值。
    // 零值表示空块。
    pub fn checkChksum(header: Header) !u64 {
        const field = try header.chksum();
        const cs = header.computeChksum();
        if (field == 0 and cs.unsigned == 256) return 0;
        if (field != cs.unsigned and field != cs.signed) return error.TarHeaderChksum;
        return field;
    }
};

// 在首个空字符处截断字符串。
fn nullStr(str: []const u8) []const u8 {
    for (str, 0..) |c, i| {
        if (c == 0) return str[0..i];
    }
    return str;
}

/// 迭代器 `next` 方法返回的文件类型。
pub const FileKind = enum {
    directory,
    sym_link,
    file,
};

/// 遍历 reader 所表示的 tar 文件中各条目的迭代器。
pub const Iterator = struct {
    reader: *Io.Reader,
    diagnostics: ?*Diagnostics = null,

    // 存放头部和文件属性的缓冲区
    header_buffer: [Header.SIZE]u8 = undefined,
    file_name_buffer: []u8,
    link_name_buffer: []u8,

    // 到数据块末尾的填充字节数
    padding: usize = 0,
    // 上次 next 迭代遗留的文件中未消费字节。
    unread_file_bytes: u64 = 0,

    /// 迭代器选项。
    /// 缓冲区应由调用方提供。
    pub const Options = struct {
        /// 使用长度为 `std.fs.max_path_bytes` 的缓冲区,以匹配文件系统能力。
        file_name_buffer: []u8,
        /// 使用长度为 `std.fs.max_path_bytes` 的缓冲区,以匹配文件系统能力。
        link_name_buffer: []u8,
        /// 收集解包时的错误消息
        diagnostics: ?*Diagnostics = null,
    };

    /// 遍历 tar 归档中的文件。
    /// `next` 返回 tar 归档中的每个文件。
    pub fn init(reader: *Io.Reader, options: Options) Iterator {
        return .{
            .reader = reader,
            .diagnostics = options.diagnostics,
            .file_name_buffer = options.file_name_buffer,
            .link_name_buffer = options.link_name_buffer,
        };
    }

    pub const File = struct {
        name: []const u8, // 文件、符号链接或目录的名称
        link_name: []const u8, // 符号链接的目标名称
        size: u64 = 0, // 文件的字节大小
        mode: u32 = 0,
        kind: FileKind = .file,
    };

    fn readHeader(self: *Iterator) !?Header {
        if (self.padding > 0) {
            try self.reader.discardAll(self.padding);
        }
        const n = try self.reader.readSliceShort(&self.header_buffer);
        if (n == 0) return null;
        if (n < Header.SIZE) return error.UnexpectedEndOfStream;
        const header = Header{ .bytes = self.header_buffer[0..Header.SIZE] };
        if (try header.checkChksum() == 0) return null;
        return header;
    }

    fn readString(self: *Iterator, size: usize, buffer: []u8) ![]const u8 {
        if (size > buffer.len) return error.TarInsufficientBuffer;
        const buf = buffer[0..size];
        try self.reader.readSliceAll(buf);
        return nullStr(buf);
    }

    fn newFile(self: *Iterator) File {
        return .{
            .name = self.file_name_buffer[0..0],
            .link_name = self.link_name_buffer[0..0],
        };
    }

    // 最后一个文件块中的填充字节数。
    fn blockPadding(size: u64) usize {
        const block_rounded = std.mem.alignForward(u64, size, Header.SIZE); // 大小向上取整到块边界
        return @intCast(block_rounded - size);
    }

    /// 将 tar 归档视为一系列文件进行迭代。
    /// 在内部,tar 格式经常使用条目,即报头及可选内容,添加描述下一个文件的元数据。这些条目通常不应对外可见。
    /// 因此,此循环遍历一个或多个条目,直到收集到某个文件的全部属性。
    ///
    ///
    ///
    pub fn next(self: *Iterator) !?File {
        if (self.unread_file_bytes > 0) {
            // 若调用者尚未消耗文件内容
            try self.reader.discardAll64(self.unread_file_bytes);
            self.unread_file_bytes = 0;
        }
        var file: File = self.newFile();

        while (try self.readHeader()) |header| {
            const kind = header.kind();
            const size: u64 = try header.size();
            self.padding = blockPadding(size);

            switch (kind) {
                // 向上游返回的文件类型
                .directory, .normal, .symbolic_link => {
                    file.kind = switch (kind) {
                        .directory => .directory,
                        .normal => .file,
                        .symbolic_link => .sym_link,
                        else => unreachable,
                    };
                    file.mode = try header.mode();

                    // 若 prefix/扩展头尚未设置文件属性,则设置它们
                    if (file.size == 0) {
                        file.size = size;
                    }
                    if (file.link_name.len == 0) {
                        file.link_name = try header.linkName(self.link_name_buffer);
                    }
                    if (file.name.len == 0) {
                        file.name = try header.fullName(self.file_name_buffer);
                    }

                    self.padding = blockPadding(file.size);
                    self.unread_file_bytes = file.size;
                    return file;
                },
                // 前缀头部类型
                .gnu_long_name => {
                    file.name = try self.readString(@intCast(size), self.file_name_buffer);
                },
                .gnu_long_link => {
                    file.link_name = try self.readString(@intCast(size), self.link_name_buffer);
                },
                .extended_header => {
                    // 仅使用最后一个扩展头部中的属性。
                    file = self.newFile();

                    var rdr: PaxIterator = .{
                        .reader = self.reader,
                        .size = @intCast(size),
                    };
                    while (try rdr.next()) |attr| {
                        switch (attr.kind) {
                            .path => {
                                file.name = try attr.value(self.file_name_buffer);
                            },
                            .linkpath => {
                                file.link_name = try attr.value(self.link_name_buffer);
                            },
                            .size => {
                                var buf: [pax_max_size_attr_len]u8 = undefined;
                                file.size = try std.fmt.parseInt(u64, try attr.value(&buf), 10);
                            },
                        }
                    }
                },
                // 忽略的头部类型
                .global_extended_header => {
                    self.reader.discardAll64(size) catch return error.TarHeadersTooBig;
                },
                // 其余均为不支持的头部类型
                else => {
                    const d = self.diagnostics orelse return error.TarUnsupportedHeader;
                    try d.errors.append(d.allocator, .{ .unsupported_file_type = .{
                        .file_name = try d.allocator.dupe(u8, header.name()),
                        .file_type = kind,
                    } });
                    if (kind == .gnu_sparse) {
                        try self.skipGnuSparseExtendedHeaders(header);
                    }
                    self.reader.discardAll64(size) catch return error.TarHeadersTooBig;
                },
            }
        }
        return null;
    }

    pub fn streamRemaining(it: *Iterator, file: File, w: *Io.Writer) Io.Reader.StreamError!void {
        try it.reader.streamExact64(w, file.size);
        it.unread_file_bytes = 0;
    }

    fn skipGnuSparseExtendedHeaders(self: *Iterator, header: Header) !void {
        var is_extended = header.bytes[482] > 0;
        while (is_extended) {
            var buf: [Header.SIZE]u8 = undefined;
            try self.reader.readSliceAll(&buf);
            is_extended = buf[504] > 0;
        }
    }
};

const PaxAttributeKind = enum {
    path,
    linkpath,
    size,
};

// maxInt(u64) 有 20 个十进制字符,实际得到 24 个字符。
const pax_max_size_attr_len = 64;

pub const PaxIterator = struct {
    size: usize, // 所有 pax 属性的累计大小
    reader: *Io.Reader,

    const Self = @This();

    const Attribute = struct {
        kind: PaxAttributeKind,
        len: usize, // 属性值的长度
        reader: *Io.Reader, // 读取器位于值的起始位置

        // 将 pax 属性值复制到目标缓冲区。
        // 目标缓冲区大小必须至少为 Attribute.len。
        pub fn value(self: Attribute, dst: []u8) ![]const u8 {
            if (self.len > dst.len) return error.TarInsufficientBuffer;
            // assert(self.len <= dst.len);
            const buf = dst[0..self.len];
            const n = try self.reader.readSliceShort(buf);
            if (n < self.len) return error.UnexpectedEndOfStream;
            try validateAttributeEnding(self.reader);
            if (hasNull(buf)) return error.PaxNullInValue;
            return buf;
        }
    };

    // 遍历 pax 属性,仅返回已知属性。
    // 调用方必须调用 Attribute 中的 value,以推进读取器越过属性值。
    pub fn next(self: *Self) !?Attribute {
        // Pax 扩展头由一个或多个属性组成,每个属性的构造如下:
        // "%d %s=%s\n", <length>, <keyword>, <value>
        while (self.size > 0) {
            const length_buf = try self.reader.takeSentinel(' ');
            const length = try std.fmt.parseInt(usize, length_buf, 10); // 记录长度,单位为字节

            const keyword = try self.reader.takeSentinel('=');
            if (hasNull(keyword)) return error.PaxNullInKeyword;

            // 计算 value_len
            const value_start = length_buf.len + keyword.len + 2; // 2 个分隔符
            if (length < value_start + 1 or self.size < length) return error.UnexpectedEndOfStream;
            const value_len = length - value_start - 1; // 末尾的 \n 分隔符
            self.size -= length;

            const kind: PaxAttributeKind = if (eql(keyword, "path"))
                .path
            else if (eql(keyword, "linkpath"))
                .linkpath
            else if (eql(keyword, "size"))
                .size
            else {
                try self.reader.discardAll(value_len);
                try validateAttributeEnding(self.reader);
                continue;
            };
            if (kind == .size and value_len > pax_max_size_attr_len) {
                return error.PaxSizeAttrOverflow;
            }
            return .{
                .kind = kind,
                .len = value_len,
                .reader = self.reader,
            };
        }

        return null;
    }

    fn eql(a: []const u8, b: []const u8) bool {
        return std.mem.eql(u8, a, b);
    }

    fn hasNull(str: []const u8) bool {
        return (std.mem.findScalar(u8, str, 0)) != null;
    }

    // 检查每条记录是否以换行符结束。
    fn validateAttributeEnding(reader: *Io.Reader) !void {
        if (try reader.takeByte() != '\n') return error.PaxInvalidAttributeEnd;
    }
};

/// 已弃用,重命名为 `extract`。
pub const pipeToFileSystem = extract;

/// 从 `reader` 读取 tar 文件,将文件内容填入 `dir`。
/// 若任何文件将被提取到 `dir` 之外,则改为返回错误。
pub fn extract(io: Io, dir: Io.Dir, reader: *Io.Reader, options: ExtractOptions) !void {
    var file_name_buffer: [Io.Dir.max_path_bytes]u8 = undefined;
    var link_name_buffer: [Io.Dir.max_path_bytes]u8 = undefined;
    var sanitize_buffer: [Io.Dir.max_path_bytes]u8 = undefined;
    var file_contents_buffer: [1024]u8 = undefined;
    var it: Iterator = .init(reader, .{
        .file_name_buffer = &file_name_buffer,
        .link_name_buffer = &link_name_buffer,
        .diagnostics = options.diagnostics,
    });

    while (try it.next()) |file| {
        const n = sanitizePath(&sanitize_buffer, file.name, options.strip_components) catch 0;
        if (n == 0 and file.kind != .directory) {
            const d = options.diagnostics orelse return error.TarComponentsOutsideStrippedPrefix;
            try d.errors.append(d.allocator, .{ .components_outside_stripped_prefix = .{
                .file_name = try d.allocator.dupe(u8, file.name),
            } });
            continue;
        }
        const file_name = sanitize_buffer[0..n];
        if (options.diagnostics) |d| {
            try d.findRoot(file.kind, file_name);
        }

        switch (file.kind) {
            .directory => {
                if (file_name.len > 0 and !options.exclude_empty_directories) {
                    try dir.createDirPath(io, file_name);
                }
            },
            .file => {
                if (createDirAndFile(io, dir, file_name, filePermissions(file.mode, options))) |fs_file| {
                    defer fs_file.close(io);
                    var file_writer = fs_file.writer(io, &file_contents_buffer);
                    try it.streamRemaining(file, &file_writer.interface);
                    try file_writer.interface.flush();
                } else |err| {
                    const d = options.diagnostics orelse return err;
                    try d.errors.append(d.allocator, .{ .unable_to_create_file = .{
                        .code = err,
                        .file_name = try d.allocator.dupe(u8, file_name),
                    } });
                }
            },
            .sym_link => {
                const link_name = file.link_name;
                createDirAndSymlink(io, dir, link_name, file_name) catch |err| {
                    const d = options.diagnostics orelse return error.UnableToCreateSymLink;
                    try d.errors.append(d.allocator, .{ .unable_to_create_sym_link = .{
                        .code = err,
                        .file_name = try d.allocator.dupe(u8, file_name),
                        .link_name = try d.allocator.dupe(u8, link_name),
                    } });
                };
            },
        }
    }
}

fn createDirAndFile(io: Io, dir: Io.Dir, file_name: []const u8, permissions: Io.File.Permissions) !Io.File {
    const fs_file = dir.createFile(io, file_name, .{ .exclusive = true, .permissions = permissions }) catch |err| {
        if (err == error.FileNotFound) {
            if (std.fs.path.dirname(file_name)) |dir_name| {
                try dir.createDirPath(io, dir_name);
                return try dir.createFile(io, file_name, .{ .exclusive = true, .permissions = permissions });
            }
        }
        return err;
    };
    return fs_file;
}

// 在路径 `file_name` 创建指向 `link_name` 的符号链接。
fn createDirAndSymlink(io: Io, dir: Io.Dir, link_name: []const u8, file_name: []const u8) !void {
    dir.symLink(io, link_name, file_name, .{}) catch |err| {
        if (err == error.FileNotFound) {
            if (std.fs.path.dirname(file_name)) |dir_name| {
                try dir.createDirPath(io, dir_name);
                return try dir.symLink(io, link_name, file_name, .{});
            }
        }
        return err;
    };
}

fn sanitizePath(buffer: []u8, path: []const u8, strip_components: u32) error{Invalid}!usize {
    if (path.len == 0 or path[0] == '/') return error.Invalid;
    var i: usize = 0;
    var c = strip_components;
    var it = std.mem.tokenizeScalar(u8, path, '/');
    while (it.next()) |component| {
        if (std.mem.eql(u8, component, ".")) continue;
        if (std.mem.eql(u8, component, "..")) {
            if (i == 0) return error.Invalid;
            while (true) {
                const ends_with_slash = buffer[i - 1] == '/';
                i -= 1;
                if (ends_with_slash or i == 0) break;
            }
            continue;
        }
        if (c > 0) {
            c -= 1;
            continue;
        }
        if (i > 0) {
            buffer[i] = '/';
            i += 1;
        }
        @memcpy(buffer[i..][0..component.len], component);
        i += component.len;
    }
    if (c > 0) return error.Invalid;
    return i;
}

fn testSanitizePath(expected: []const u8, input: []const u8, strip: u32) !void {
    var buffer: [Io.Dir.max_path_bytes]u8 = undefined;
    const result = buffer[0..try sanitizePath(&buffer, input, strip)];
    try testing.expectEqualStrings(expected, result);
}

fn testSanitizePathError(expected: anyerror, input: []const u8, strip: u32) !void {
    var buffer: [Io.Dir.max_path_bytes]u8 = undefined;
    try testing.expectError(expected, sanitizePath(&buffer, input, strip));
}

test sanitizePath {
    try testSanitizePath("a/b/c", "a/b/c", 0);
    try testSanitizePath("a/b/c", "a/x/y/../../b/c", 0);
    try testSanitizePath("b/c", "a/b/c", 1);
    try testSanitizePath("c", "a/b/c", 2);
    try testSanitizePath("", "a/b/c", 3);
    try testSanitizePath("", "a/b/c/../../..", 0);
    try testSanitizePathError(error.Invalid, "a/b/c", 4);
    try testSanitizePathError(error.Invalid, "..", 0);
    try testSanitizePathError(error.Invalid, "a/b/../../..", 0);
    try testSanitizePathError(error.Invalid, "a/b/../..", 1);
}

test PaxIterator {
    const Attr = struct {
        kind: PaxAttributeKind,
        value: []const u8 = undefined,
        err: ?anyerror = null,
    };
    const long_path: *const [1000]u8 = comptime path: {
        const buf: [100][10]u8 = @splat("0123456789".*);
        break :path @ptrCast(&buf);
    };
    const cases = [_]struct {
        data: []const u8,
        attrs: []const Attr,
        err: ?anyerror = null,
    }{
        .{ // 有效但未知的键
            .data =
            \\30 mtime=1350244992.023960108
            \\6 k=1
            \\13 key1=val1
            \\10 a=name
            \\9 a=name
            \\
            ,
            .attrs = &[_]Attr{},
        },
        .{ // 已知键与未知键混合
            .data =
            \\6 k=1
            \\13 path=name
            \\17 linkpath=link
            \\13 key1=val1
            \\12 size=123
            \\13 key2=val2
            \\
            ,
            .attrs = &[_]Attr{
                .{ .kind = .path, .value = "name" },
                .{ .kind = .linkpath, .value = "link" },
                .{ .kind = .size, .value = "123" },
            },
        },
        .{ // 第二个键值对的大小过短
            .data =
            \\13 path=name
            \\10 linkpath=value
            \\
            ,
            .attrs = &[_]Attr{
                .{ .kind = .path, .value = "name" },
            },
            .err = error.UnexpectedEndOfStream,
        },
        .{ // 第二个键值对的大小过长
            .data =
            \\13 path=name
            \\6 k=1
            \\19 linkpath=value
            \\
            ,
            .attrs = &[_]Attr{
                .{ .kind = .path, .value = "name" },
            },
            .err = error.UnexpectedEndOfStream,
        },

        .{ // 第二个键值对的大小过长
            .data =
            \\13 path=name
            \\19 linkpath=value
            \\6 k=1
            \\
            ,
            .attrs = &[_]Attr{
                .{ .kind = .path, .value = "name" },
                .{ .kind = .linkpath, .err = error.PaxInvalidAttributeEnd },
            },
        },
        .{ // 关键字中不允许 null
            .data = "13 path=name\n" ++ "7 k\x00b=1\n",
            .attrs = &[_]Attr{
                .{ .kind = .path, .value = "name" },
            },
            .err = error.PaxNullInKeyword,
        },
        .{ // value 中的 null 无效
            .data = "23 path=name\x00with null\n",
            .attrs = &[_]Attr{
                .{ .kind = .path, .err = error.PaxNullInValue },
            },
        },
        .{ // 长度为 1000 个字符的路径
            .data = "1011 path=" ++ long_path ++ "\n",
            .attrs = &[_]Attr{
                .{ .kind = .path, .value = long_path },
            },
        },
    };
    var buffer: [1024]u8 = undefined;

    outer: for (cases) |case| {
        var reader: Io.Reader = .fixed(case.data);
        var it: PaxIterator = .{
            .size = case.data.len,
            .reader = &reader,
        };

        var i: usize = 0;
        while (it.next() catch |err| {
            if (case.err) |e| {
                try testing.expectEqual(e, err);
                continue;
            }
            return err;
        }) |attr| : (i += 1) {
            const exp = case.attrs[i];
            try testing.expectEqual(exp.kind, attr.kind);
            const value = attr.value(&buffer) catch |err| {
                if (exp.err) |e| {
                    try testing.expectEqual(e, err);
                    break :outer;
                }
                return err;
            };
            try testing.expectEqualStrings(exp.value, value);
        }
        try testing.expectEqual(case.attrs.len, i);
        try testing.expect(case.err == null);
    }
}

test "header parse size" {
    const cases = [_]struct {
        in: []const u8,
        want: u64 = 0,
        err: ?anyerror = null,
    }{
        // 测试 base-256(二进制)编码值。
        .{ .in = "", .want = 0 },
        .{ .in = "\x80", .want = 0 },
        .{ .in = "\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01", .want = 1 },
        .{ .in = "\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02", .want = 0x0102 },
        .{ .in = "\x80\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08", .want = 0x0102030405060708 },
        .{ .in = "\x80\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09", .err = error.TarNumericValueTooBig },
        .{ .in = "\x80\x00\x00\x00\x07\x76\xa2\x22\xeb\x8a\x72\x61", .want = 537795476381659745 },
        .{ .in = "\x80\x80\x80\x00\x01\x02\x03\x04\x05\x06\x07\x08", .err = error.TarNumericValueTooBig },

        // // 测试以 8 为基数(八进制)的编码值。
        .{ .in = "00000000227\x00", .want = 0o227 },
        .{ .in = "  000000227\x00", .want = 0o227 },
        .{ .in = "00000000228\x00", .err = error.TarHeader },
        .{ .in = "11111111111\x00", .want = 0o11111111111 },
    };

    for (cases) |case| {
        var bytes: [Header.SIZE]u8 = @splat(0);
        @memcpy(bytes[124 .. 124 + case.in.len], case.in);
        var header = Header{ .bytes = &bytes };
        if (case.err) |err| {
            try testing.expectError(err, header.size());
        } else {
            try testing.expectEqual(case.want, try header.size());
        }
    }
}

test "header parse mode" {
    const cases = [_]struct {
        in: []const u8,
        want: u64 = 0,
        err: ?anyerror = null,
    }{
        .{ .in = "0000644\x00", .want = 0o644 },
        .{ .in = "0000777\x00", .want = 0o777 },
        .{ .in = "7777777\x00", .want = 0o7777777 },
        .{ .in = "7777778\x00", .err = error.TarHeader },
        .{ .in = "77777777", .want = 0o77777777 },
        .{ .in = "777777777777", .want = 0o77777777 },
    };
    for (cases) |case| {
        var bytes: [Header.SIZE]u8 = @splat(0);
        @memcpy(bytes[100 .. 100 + case.in.len], case.in);
        var header = Header{ .bytes = &bytes };
        if (case.err) |err| {
            try testing.expectError(err, header.mode());
        } else {
            try testing.expectEqual(case.want, try header.mode());
        }
    }
}

test "create file and symlink" {
    const io = testing.io;

    var root = testing.tmpDir(.{});
    defer root.cleanup();

    var file = try createDirAndFile(io, root.dir, "file1", .default_file);
    file.close(io);
    file = try createDirAndFile(io, root.dir, "a/b/c/file2", .default_file);
    file.close(io);

    createDirAndSymlink(io, root.dir, "a/b/c/file2", "symlink1") catch |err| switch (err) {
        // 在 Windows 上,符号链接要求开发者模式或管理员权限,且底层文件系统必须支持符号链接。
        error.AccessDenied, error.PermissionDenied, error.FileSystem => if (builtin.os.tag == .windows) return error.SkipZigTest else return err,
        else => return err,
    };
    try createDirAndSymlink(io, root.dir, "../../../file1", "d/e/f/symlink2");

    // 悬空符号链接,稍后创建文件
    try createDirAndSymlink(io, root.dir, "../../../g/h/i/file4", "j/k/l/symlink3");
    file = try createDirAndFile(io, root.dir, "g/h/i/file4", .default_file);
    file.close(io);
}

test Iterator {
    // 示例 tar 文件由以下目录树创建:
    // $ tree example
    //    example
    //    ├── a
    //    │   └── file
    //    ├── b
    //    │   └── symlink -> ../a/file
    //    └── empty
    // $ cat example/a/file
    //   content
    // $ tar -cf example.tar example
    // $ tar -tvf example.tar
    //    example/
    //    example/b/
    //    example/b/symlink -> ../a/file
    //    example/a/
    //    example/a/file
    //    example/empty/

    const data = @embedFile("tar/testdata/example.tar");
    var reader: Io.Reader = .fixed(data);

    // 用户提供给迭代器的缓冲区
    var file_name_buffer: [std.fs.max_path_bytes]u8 = undefined;
    var link_name_buffer: [std.fs.max_path_bytes]u8 = undefined;
    // 创建迭代器
    var it: Iterator = .init(&reader, .{
        .file_name_buffer = &file_name_buffer,
        .link_name_buffer = &link_name_buffer,
    });
    // 遍历 example.tar 中的文件
    var file_no: usize = 0;
    while (try it.next()) |file| : (file_no += 1) {
        switch (file.kind) {
            .directory => {
                switch (file_no) {
                    0 => try testing.expectEqualStrings("example/", file.name),
                    1 => try testing.expectEqualStrings("example/b/", file.name),
                    3 => try testing.expectEqualStrings("example/a/", file.name),
                    5 => try testing.expectEqualStrings("example/empty/", file.name),
                    else => unreachable,
                }
            },
            .file => {
                try testing.expectEqualStrings("example/a/file", file.name);
                var buf: [16]u8 = undefined;
                var w: Io.Writer = .fixed(&buf);
                try it.streamRemaining(file, &w);
                try testing.expectEqualStrings("content\n", w.buffered());
            },
            .sym_link => {
                try testing.expectEqualStrings("example/b/symlink", file.name);
                try testing.expectEqualStrings("../a/file", file.link_name);
            },
        }
    }
}

test extract {
    const io = testing.io;
    // 示例 tar 文件由以下目录树创建:
    // $ tree example
    //    example
    //    ├── a
    //    │   └── file
    //    ├── b
    //    │   └── symlink -> ../a/file
    //    └── empty
    // $ cat example/a/file
    //   content
    // $ tar -cf example.tar example
    // $ tar -tvf example.tar
    //    example/
    //    example/b/
    //    example/b/symlink -> ../a/file
    //    example/a/
    //    example/a/file
    //    example/empty/

    const data = @embedFile("tar/testdata/example.tar");
    var reader: Io.Reader = .fixed(data);

    var tmp = testing.tmpDir(.{ .follow_symlinks = false });
    defer tmp.cleanup();
    const dir = tmp.dir;

    // 将读取器中的 tar 保存至文件系统 `dir`
    extract(io, dir, &reader, .{
        .mode_mode = .ignore,
        .strip_components = 1,
        .exclude_empty_directories = true,
    }) catch |err| {
        // 在不支持符号链接的平台上跳过
        if (err == error.UnableToCreateSymLink) return error.SkipZigTest;
        return err;
    };

    try testing.expectError(error.FileNotFound, dir.statFile(io, "empty", .{}));
    try testing.expect((try dir.statFile(io, "a/file", .{})).kind == .file);
    try testing.expect((try dir.statFile(io, "b/symlink", .{})).kind == .file); // statFile 会跟随符号链接

    var buf: [32]u8 = undefined;
    try testing.expectEqualSlices(
        u8,
        "../a/file",
        normalizePath(buf[0..try dir.readLink(io, "b/symlink", &buf)]),
    );
}

test "extract root_dir" {
    const io = testing.io;
    const data = @embedFile("tar/testdata/example.tar");
    var reader: Io.Reader = .fixed(data);

    // 采用 strip_components = 1
    {
        var tmp = testing.tmpDir(.{ .follow_symlinks = false });
        defer tmp.cleanup();
        var diagnostics: Diagnostics = .{ .allocator = testing.allocator };
        defer diagnostics.deinit();

        extract(io, tmp.dir, &reader, .{
            .strip_components = 1,
            .diagnostics = &diagnostics,
        }) catch |err| {
            // 在不支持符号链接的平台上跳过
            if (err == error.UnableToCreateSymLink) return error.SkipZigTest;
            return err;
        };

        // 没有 root_dir
        try testing.expectEqual(0, diagnostics.root_dir.len);
        try testing.expectEqual(5, diagnostics.entries);
    }

    // strip_components = 0 时
    {
        reader = .fixed(data);
        var tmp = testing.tmpDir(.{ .follow_symlinks = false });
        defer tmp.cleanup();
        var diagnostics: Diagnostics = .{ .allocator = testing.allocator };
        defer diagnostics.deinit();

        extract(io, tmp.dir, &reader, .{
            .strip_components = 0,
            .diagnostics = &diagnostics,
        }) catch |err| {
            // 在不支持符号链接的平台上跳过
            if (err == error.UnableToCreateSymLink) return error.SkipZigTest;
            return err;
        };

        // 已找到 root_dir
        try testing.expectEqualStrings("example", diagnostics.root_dir);
        try testing.expectEqual(6, diagnostics.entries);
    }
}

test "findRoot with single file archive" {
    const io = testing.io;
    const data = @embedFile("tar/testdata/22752.tar");
    var reader: Io.Reader = .fixed(data);

    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();

    var diagnostics: Diagnostics = .{ .allocator = testing.allocator };
    defer diagnostics.deinit();
    try extract(io, tmp.dir, &reader, .{ .diagnostics = &diagnostics });

    try testing.expectEqualStrings("", diagnostics.root_dir);
}

test "findRoot without explicit root dir" {
    const io = testing.io;
    const data = @embedFile("tar/testdata/19820.tar");
    var reader: Io.Reader = .fixed(data);

    var tmp = testing.tmpDir(.{});
    defer tmp.cleanup();

    var diagnostics: Diagnostics = .{ .allocator = testing.allocator };
    defer diagnostics.deinit();
    try extract(io, tmp.dir, &reader, .{ .diagnostics = &diagnostics });

    try testing.expectEqualStrings("root", diagnostics.root_dir);
}

test "extract strip_components" {
    const io = testing.io;
    const data = @embedFile("tar/testdata/example.tar");
    var reader: Io.Reader = .fixed(data);

    var tmp = testing.tmpDir(.{ .follow_symlinks = false });
    defer tmp.cleanup();
    var diagnostics: Diagnostics = .{ .allocator = testing.allocator };
    defer diagnostics.deinit();

    extract(io, tmp.dir, &reader, .{
        .strip_components = 3,
        .diagnostics = &diagnostics,
    }) catch |err| {
        // 在不支持符号链接的平台上跳过
        if (err == error.UnableToCreateSymLink) return error.SkipZigTest;
        return err;
    };

    try testing.expectEqual(2, diagnostics.errors.items.len);
    try testing.expectEqualStrings("example/b/symlink", diagnostics.errors.items[0].components_outside_stripped_prefix.file_name);
    try testing.expectEqualStrings("example/a/file", diagnostics.errors.items[1].components_outside_stripped_prefix.file_name);
}

fn normalizePath(bytes: []u8) []u8 {
    const canonical_sep = std.fs.path.sep_posix;
    if (std.fs.path.sep == canonical_sep) return bytes;
    std.mem.replaceScalar(u8, bytes, std.fs.path.sep, canonical_sep);
    return bytes;
}

// 根据 tar 头部模式和 mode_mode 选项确定文件系统模式。
fn filePermissions(mode: u32, options: ExtractOptions) Io.File.Permissions {
    return if (!Io.File.Permissions.has_executable_bit or options.mode_mode == .ignore or (mode & 0o100) == 0)
        .default_file
    else
        .executable_file;
}

test filePermissions {
    if (!Io.File.Permissions.has_executable_bit) return error.SkipZigTest;
    try testing.expectEqual(Io.File.Permissions.default_file, filePermissions(0o744, .{ .mode_mode = .ignore }));
    try testing.expectEqual(Io.File.Permissions.executable_file, filePermissions(0o744, .{}));
    try testing.expectEqual(Io.File.Permissions.default_file, filePermissions(0o644, .{}));
    try testing.expectEqual(Io.File.Permissions.default_file, filePermissions(0o655, .{}));
}

test "executable bit" {
    if (!Io.File.Permissions.has_executable_bit) return error.SkipZigTest;

    const io = testing.io;
    const S = std.posix.S;
    const data = @embedFile("tar/testdata/example.tar");

    for ([_]ExtractOptions.ModeMode{ .ignore, .executable_bit_only }) |opt| {
        var reader: Io.Reader = .fixed(data);

        var tmp = testing.tmpDir(.{ .follow_symlinks = false });
        // defer tmp.cleanup();

        extract(io, tmp.dir, &reader, .{
            .strip_components = 1,
            .exclude_empty_directories = true,
            .mode_mode = opt,
        }) catch |err| {
            // 在不支持符号链接的平台上跳过
            if (err == error.UnableToCreateSymLink) return error.SkipZigTest;
            return err;
        };

        const fs = try tmp.dir.statFile(io, "a/file", .{});
        try testing.expect(fs.kind == .file);

        const mode = fs.permissions.toMode();

        if (opt == .executable_bit_only) {
            // 已为用户、组及其他用户设置可执行位。
            try testing.expect(mode & S.IXUSR > 0);
            try testing.expect(mode & S.IXGRP > 0);
            try testing.expect(mode & S.IXOTH > 0);
        }
        if (opt == .ignore) {
            try testing.expect(mode & S.IXUSR == 0);
            try testing.expect(mode & S.IXGRP == 0);
            try testing.expect(mode & S.IXOTH == 0);
        }
    }
}

test {
    _ = @import("tar/test.zig");
    _ = Writer;
    _ = Diagnostics;
}