跟踪与 Zig 编译器和构建系统产物相关的文件输入元数据, 据此确定是否必须重新生成这些产物, 或者可以从文件系统中的缓存目录中取回。
字段
gpa: Allocator
io: Io
manifest_dir: Io.Dir
hash: HashHelper = .{}
recent_problematic_timestamp: Io.Timestamp = .zero多个线程会访问此值,由互斥锁保护。
mutex: Io.Mutex = .init
prefixes_buffer: [5]Directory = undefined一组字符串,例如 Zig 库目录或项目源码根目录,在将文件路径放入缓存之前会从路径中移除,并替换为单字符标记。 目的不是节省空间,而是消除绝对文件路径,从而提高缓存的可移植性,以及在高级用例中的实用性。
prefixes_len: usize = 0
cwd: []const u8用于识别前缀。引用外部内存。
CachebuiltinstdIocryptoasserttestingmemfmtAllocatorlogPathDirectoryDepTokenizeraddPrefixobtainprefixesPrefixIndexPrefixedPathappendPrefixedPathresolveAppendPathbin_digest_lenhex_digest_lenBinDigestHexDigestHasherhasher_initHashHelperbinToHexLockManifesttestGetCurrentFileTimestamp
std.Build.Cache.addPrefix
函数
pub fn addPrefix(cache: *Cache, directory: Directory) void
参数
std.Build.Cache.Allocator
别名
别名目标 std.mem.Allocator
std.Build.Cache.appendPrefixedPath
函数
fn appendPrefixedPath(cache: *const Cache, contents: *std.ArrayList(u8), prefixed_path: PrefixedPath) !PrefixIndex
参数
std.Build.Cache.assert
别名
别名目标 std.debug.assert
std.Build.Cache.bin_digest_len
常量
这是 128 位值;即使有 2^54 个缓存条目,冲突概率仍低于 10^-6。
std.Build.Cache.BinDigest
类型
std.Build.Cache.binToHex
函数
pub fn binToHex(bin_digest: BinDigest) HexDigest
参数
bin_digest: BinDigest
std.Build.Cache.builtin
常量
std.Build.Cache.Cache
别名
别名目标 std.Build.Cache
std.Build.Cache.crypto
别名
别名目标 std.crypto
std.Build.Cache.DepTokenizer
别名
std.Build.Cache.Directory
别名
std.Build.Cache.fmt
别名
别名目标 std.fmt
std.Build.Cache.Hasher
类型
用于对文件内容进行哈希的类型。目前是 SipHash128(1, 3), 因为它为 Manifest 的用例提供了足够的抗碰撞性, 同时也是当前最快的选项之一。
std.Build.Cache.hasher_init
常量
包含随机字节、可以复制的初始状态。 当清单格式以不向后兼容的方式修改时,使用新的随机字节更新它。
Hasher
std.Build.Cache.HashHelper
容器
字段
hasher: Hasher = hasher_init
std.Build.Cache.HashHelper.add
函数
将输入值转换为字节,并记录为被缓存进程的依赖项。
pub fn add(hh: *HashHelper, x: anytype) void
参数
hh: *HashHelper
std.Build.Cache.HashHelper.addBytes
函数
pub fn addBytes(hh: *HashHelper, bytes: []const u8) void
参数
hh: *HashHelper
bytes: []const u8
std.Build.Cache.HashHelper.addBytesZ
函数
pub fn addBytesZ(hh: *HashHelper, bytes: [:0]const u8) void
参数
hh: *HashHelper
bytes: [:0]const u8
std.Build.Cache.HashHelper.addListOfBytes
函数
pub fn addListOfBytes(hh: *HashHelper, list_of_bytes: []const []const u8) void
参数
hh: *HashHelper
list_of_bytes: []const []const u8
std.Build.Cache.HashHelper.addOptional
函数
pub fn addOptional(hh: *HashHelper, optional: anytype) void
参数
hh: *HashHelper
std.Build.Cache.HashHelper.addOptionalBytes
函数
pub fn addOptionalBytes(hh: *HashHelper, optional_bytes: ?[]const u8) void
参数
hh: *HashHelper
optional_bytes: ?[]const u8
std.Build.Cache.HashHelper.addOptionalListOfBytes
函数
pub fn addOptionalListOfBytes(hh: *HashHelper, optional_list_of_bytes: ?[]const []const u8) void
参数
hh: *HashHelper
optional_list_of_bytes: ?[]const []const u8
std.Build.Cache.HashHelper.final
函数
返回输入的十六进制编码哈希,并修改哈希器状态。
pub fn final(hh: *HashHelper) HexDigest
参数
hh: *HashHelper
std.Build.Cache.HashHelper.oneShot
函数
pub fn oneShot(bytes: []const u8) [hex_digest_len]u8
参数
bytes: []const u8
std.Build.Cache.HashHelper.peek
函数
返回输入的十六进制编码哈希,不修改状态。
pub fn peek(hh: HashHelper) [hex_digest_len]u8
参数
hh: HashHelper
std.Build.Cache.HashHelper.peekBin
函数
pub fn peekBin(hh: HashHelper) BinDigest
参数
hh: HashHelper
std.Build.Cache.hex_digest_len
常量
std.Build.Cache.HexDigest
类型
std.Build.Cache.Io
别名
别名目标 std.Io
std.Build.Cache.Lock
容器
字段
std.Build.Cache.Lock.release
函数
pub fn release(lock: *Lock, io: Io) void
参数
std.Build.Cache.log
类型
std.Build.Cache.Manifest
容器
格式:连续的 Manifest.File 序列,后跟最终的零终止字节,以区分空清单文件和包含零个文件的清单。
字段
cache: *Cache
hash: HashHelper用于增量哈希的当前状态。
manifest_file: ?Io.File此值为 null 时,Manifest 处于“检查前”阶段,否则处于“检查后”阶段。
state: State
want_shared_lock: bool = true调用 check 前将此标志设为 true,表示缓存命中后,使用缓存的代码
不会修改缓存目录中的文件。这样多个进程
就可以同时使用同一缓存目录。
have_exclusive_lock: bool = false
want_refresh_timestamp: bool = true
files: Files = .empty使用 Cache.gpa。
input_paths: std.ArrayList(InputPath) = .empty索引与 files 对齐,但仅在调用 hit 之前如此。使用 Cache.gpa。
recent_problematic_timestamp: Io.Timestamp = .zero记录上次写入文件系统的时间,以观察文件系统按自身时间粒度认定的当前时间。
contents: std.ArrayList(u8) = .empty完整的清单文件内容,但不包括末尾的
零字节。不过,始终保留至少 1 字节未使用容量,以便
无需分配即可追加末尾终止字节。使用
Cache.gpa。
all_input_content: std.ArrayList(u8) = .empty所有已请求内容的 input_paths 中的全部内容,
拼接而成。总字节大小必须小于 max_input_content_len,
否则返回错误。
调用 addDiscoveredPath 后,此数据失效。
max_input_content_len: usize = std.math.maxInt(u32)
FilesStateInputPathFileCheckDiagnosticStatPathHandleAddInputPathOptionsaddInputPathaddInputPathOptionalAddInputDepFileErroraddInputDepFileCheckResultCheckErrorcheckcheckProgresslesstransitionToMissDiscoveredshrinkFilesToInputcheckLockedmissInputpopulateMissingInputFileHashespopulateInputPathcheckInputPathcheckDiscoveredPathfailisProblematicTimestampAddDiscoveredPathOptionsDiscoveredPathAddDiscoveredPathDiagnosticAddDiscoveredPathErroraddDiscoveredPathAddDiscoveredDepFileErrorAddDiscoveredDepFileDiagnosticaddDiscoveredDepFilepopulateFilepopulateDirectoryhitDigesthitDigestHexmissDigestmissDigestHexfinalDigestfinalizedowngradeToSharedLockupgradeToExclusiveLocktoOwnedLockSelfContainedFilestakeFilesborrowFilesdeinitpopulateFileSystemInputsaddDiscoveredManifesthashFilehashFileAppendHashDirErrorhashDir
std.Build.Cache.Manifest.addDiscoveredDepFile
函数
缓存未命中后,将 GNU make 风格的依赖文件添加为被缓存进程的依赖。
另见:
addDiscoveredPathaddDiscoveredManifest
pub fn addDiscoveredDepFile( m: *Manifest, path: Path, diagnostic: ?*AddDiscoveredDepFileDiagnostic, ) AddDiscoveredDepFileError!void
参数
错误
- AccessDenied OpenError
在 WASI 中,若文件描述符不具有相对于它 打开新资源所需的权限,可能发生此错误。
- AntivirusInterference OpenError
Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。
- BadPathName PathNameError
文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。
- Canceled Cancelable
调用方请求停止异步操作。
- ConnectionResetByPeer UnendingError
- DeviceBusy OpenError
- FileBusy OpenError
以下三种情况之一:
- pathname 指向正在执行的可执行映像, 且请求写访问。
- pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
- pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
- FileLocksUnsupported OpenError
- FileNotFound OpenError
以下任一情况:
- 某个路径分量不存在。
- 使用了当前工作目录,但该目录已被删除。
- 已打开目录句柄所关联的路径已被删除。
- macOS 上,多个进程或线程将
O.EXCL设为false,并发争相创建同一文件。
- FileSystemFailure AddDiscoveredPathError
返回此值时会填充诊断信息。 如果同时提供了 contents 和 stat,则此分支不可达。
- FileTooBig OpenError
文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。
- InputOutput UnendingError
- InvalidDepFile
- IsDir OpenError
以下任一情况:
- 路径指向目录,但请求了写权限。
- 路径指向目录,但
allow_directory被设为 false。
- LockViolation UnendingError
由于锁定而无法读取文件。根据
Io实现的不同,读取已锁定文件可能返回此错误,也可能忽略锁。- NameTooLong PathNameError
提供的缓冲区过小, 无法容纳路径名时返回。
- NetworkNotFound OpenError
在 Windows 上,未找到
\\server或\\server\share。- NoDevice OpenError
- NoSpaceLeft OpenError
设备没有空间容纳新文件,无法创建新路径。 仅在提供
CREAT标志时才可能出现此错误。- NotDir OpenError
路径中用作目录的某个部分实际上不是目录, 或者指定了
DIRECTORY,但路径不是目录。- NotOpenForReading UnendingError
打开文件时未授予读取能力。
- OutOfMemory Error
- PathAlreadyExists OpenError
路径已存在,且提供了
CREAT和EXCL标志。- PermissionDenied OpenError
- PipeBusy OpenError
- ProcessFdQuotaExceeded OpenError
- ReadOnlyFileSystem OpenError
- SocketUnconnected UnendingError
- SymLinkLoop OpenError
- SystemFdQuotaExceeded OpenError
- SystemResources OpenError
路径超过
max_path_bytes字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- WouldBlock OpenError
已请求非阻塞模式,但该操作无法立即返回。
std.Build.Cache.Manifest.AddDiscoveredDepFileDiagnostic
容器
字段
add_discovered_path: AddDiscoveredPathDiagnostic
dep_tokenizer: DepTokenizer.Token
std.Build.Cache.Manifest.AddDiscoveredDepFileError
错误集合
错误
- AccessDenied OpenError
在 WASI 中,若文件描述符不具有相对于它 打开新资源所需的权限,可能发生此错误。
- AntivirusInterference OpenError
Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。
- BadPathName PathNameError
文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。
- Canceled Cancelable
调用方请求停止异步操作。
- ConnectionResetByPeer UnendingError
- DeviceBusy OpenError
- FileBusy OpenError
以下三种情况之一:
- pathname 指向正在执行的可执行映像, 且请求写访问。
- pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
- pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
- FileLocksUnsupported OpenError
- FileNotFound OpenError
以下任一情况:
- 某个路径分量不存在。
- 使用了当前工作目录,但该目录已被删除。
- 已打开目录句柄所关联的路径已被删除。
- macOS 上,多个进程或线程将
O.EXCL设为false,并发争相创建同一文件。
- FileSystemFailure AddDiscoveredPathError
返回此值时会填充诊断信息。 如果同时提供了 contents 和 stat,则此分支不可达。
- FileTooBig OpenError
文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。
- InputOutput UnendingError
- InvalidDepFile
- IsDir OpenError
以下任一情况:
- 路径指向目录,但请求了写权限。
- 路径指向目录,但
allow_directory被设为 false。
- LockViolation UnendingError
由于锁定而无法读取文件。根据
Io实现的不同,读取已锁定文件可能返回此错误,也可能忽略锁。- NameTooLong PathNameError
提供的缓冲区过小, 无法容纳路径名时返回。
- NetworkNotFound OpenError
在 Windows 上,未找到
\\server或\\server\share。- NoDevice OpenError
- NoSpaceLeft OpenError
设备没有空间容纳新文件,无法创建新路径。 仅在提供
CREAT标志时才可能出现此错误。- NotDir OpenError
路径中用作目录的某个部分实际上不是目录, 或者指定了
DIRECTORY,但路径不是目录。- NotOpenForReading UnendingError
打开文件时未授予读取能力。
- OutOfMemory Error
- PathAlreadyExists OpenError
路径已存在,且提供了
CREAT和EXCL标志。- PermissionDenied OpenError
- PipeBusy OpenError
- ProcessFdQuotaExceeded OpenError
- ReadOnlyFileSystem OpenError
- SocketUnconnected UnendingError
- SymLinkLoop OpenError
- SystemFdQuotaExceeded OpenError
- SystemResources OpenError
路径超过
max_path_bytes字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- WouldBlock OpenError
已请求非阻塞模式,但该操作无法立即返回。
std.Build.Cache.Manifest.addDiscoveredManifest
函数
缓存未命中后,将另一 Manifest 中的全部路径
添加为被缓存进程的依赖项。
另见:
addDiscoveredPathaddDiscoveredDepFile
pub fn addDiscoveredManifest(m: *Manifest, discovered: *const Manifest, prefix_map: [5]u8) Allocator.Error!void
参数
错误
- OutOfMemory
std.Build.Cache.Manifest.addDiscoveredPath
函数
缓存未命中后,将文件或目录添加为被缓存进程的依赖。
另见:
addInputPathaddDiscoveredDepFileaddDiscoveredManifest
pub fn addDiscoveredPath(m: *Manifest, options: AddDiscoveredPathOptions) AddDiscoveredPathError!void
参数
m: *Manifest
options: AddDiscoveredPathOptions
错误
- Canceled Cancelable
调用方请求停止异步操作。
- FileSystemFailure
返回此值时会填充诊断信息。 如果同时提供了 contents 和 stat,则此分支不可达。
- OutOfMemory Error
std.Build.Cache.Manifest.AddDiscoveredPathDiagnostic
容器
字段
std.Build.Cache.Manifest.AddDiscoveredPathDiagnostic.format
函数
pub fn format(this: @This(), w: *Io.Writer) Io.Writer.Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Build.Cache.Manifest.AddDiscoveredPathError
错误集合
错误
- Canceled Cancelable
调用方请求停止异步操作。
- FileSystemFailure
返回此值时会填充诊断信息。 如果同时提供了 contents 和 stat,则此分支不可达。
- OutOfMemory Error
std.Build.Cache.Manifest.AddDiscoveredPathOptions
容器
字段
discovered_path: DiscoveredPath
handle: PathHandle = .{ .file = null }
stat: ?Stat = null
contents: ?[]const u8 = null若它是目录,则目录内容需要特殊编码:以空字符分隔并排序的条目,每个条目前带 File.Kind。
metadata_only: bool = false
diagnostic: ?*AddDiscoveredPathDiagnostic = null仅当 addDiscoveredPath 返回 error.FileSystemFailure 时填充。
std.Build.Cache.Manifest.addInputDepFile
函数
pub fn addInputDepFile(m: *Manifest, path: Path, diagnostic: ?*DepTokenizer.Token) AddInputDepFileError!void
参数
错误
- AccessDenied OpenError
在 WASI 中,若文件描述符不具有相对于它 打开新资源所需的权限,可能发生此错误。
- AntivirusInterference OpenError
Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。
- BadPathName PathNameError
文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。
- Canceled Cancelable
调用方请求停止异步操作。
- ConnectionResetByPeer UnendingError
- DeviceBusy OpenError
- FileBusy OpenError
以下三种情况之一:
- pathname 指向正在执行的可执行映像, 且请求写访问。
- pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
- pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
- FileLocksUnsupported OpenError
- FileNotFound OpenError
以下任一情况:
- 某个路径分量不存在。
- 使用了当前工作目录,但该目录已被删除。
- 已打开目录句柄所关联的路径已被删除。
- macOS 上,多个进程或线程将
O.EXCL设为false,并发争相创建同一文件。
- FileTooBig OpenError
文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。
- InputOutput UnendingError
- InvalidDepFile
- IsDir OpenError
以下任一情况:
- 路径指向目录,但请求了写权限。
- 路径指向目录,但
allow_directory被设为 false。
- LockViolation UnendingError
由于锁定而无法读取文件。根据
Io实现的不同,读取已锁定文件可能返回此错误,也可能忽略锁。- NameTooLong PathNameError
提供的缓冲区过小, 无法容纳路径名时返回。
- NetworkNotFound OpenError
在 Windows 上,未找到
\\server或\\server\share。- NoDevice OpenError
- NoSpaceLeft OpenError
设备没有空间容纳新文件,无法创建新路径。 仅在提供
CREAT标志时才可能出现此错误。- NotDir OpenError
路径中用作目录的某个部分实际上不是目录, 或者指定了
DIRECTORY,但路径不是目录。- NotOpenForReading UnendingError
打开文件时未授予读取能力。
- OutOfMemory Error
- PathAlreadyExists OpenError
路径已存在,且提供了
CREAT和EXCL标志。- PermissionDenied OpenError
- PipeBusy OpenError
- ProcessFdQuotaExceeded OpenError
- ReadOnlyFileSystem OpenError
- SocketUnconnected UnendingError
- SymLinkLoop OpenError
- SystemFdQuotaExceeded OpenError
- SystemResources OpenError
路径超过
max_path_bytes字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- WouldBlock OpenError
已请求非阻塞模式,但该操作无法立即返回。
std.Build.Cache.Manifest.AddInputDepFileError
错误集合
错误
- AccessDenied OpenError
在 WASI 中,若文件描述符不具有相对于它 打开新资源所需的权限,可能发生此错误。
- AntivirusInterference OpenError
Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。
- BadPathName PathNameError
文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。
- Canceled Cancelable
调用方请求停止异步操作。
- ConnectionResetByPeer UnendingError
- DeviceBusy OpenError
- FileBusy OpenError
以下三种情况之一:
- pathname 指向正在执行的可执行映像, 且请求写访问。
- pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
- pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
- FileLocksUnsupported OpenError
- FileNotFound OpenError
以下任一情况:
- 某个路径分量不存在。
- 使用了当前工作目录,但该目录已被删除。
- 已打开目录句柄所关联的路径已被删除。
- macOS 上,多个进程或线程将
O.EXCL设为false,并发争相创建同一文件。
- FileTooBig OpenError
文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。
- InputOutput UnendingError
- InvalidDepFile
- IsDir OpenError
以下任一情况:
- 路径指向目录,但请求了写权限。
- 路径指向目录,但
allow_directory被设为 false。
- LockViolation UnendingError
由于锁定而无法读取文件。根据
Io实现的不同,读取已锁定文件可能返回此错误,也可能忽略锁。- NameTooLong PathNameError
提供的缓冲区过小, 无法容纳路径名时返回。
- NetworkNotFound OpenError
在 Windows 上,未找到
\\server或\\server\share。- NoDevice OpenError
- NoSpaceLeft OpenError
设备没有空间容纳新文件,无法创建新路径。 仅在提供
CREAT标志时才可能出现此错误。- NotDir OpenError
路径中用作目录的某个部分实际上不是目录, 或者指定了
DIRECTORY,但路径不是目录。- NotOpenForReading UnendingError
打开文件时未授予读取能力。
- OutOfMemory Error
- PathAlreadyExists OpenError
路径已存在,且提供了
CREAT和EXCL标志。- PermissionDenied OpenError
- PipeBusy OpenError
- ProcessFdQuotaExceeded OpenError
- ReadOnlyFileSystem OpenError
- SocketUnconnected UnendingError
- SymLinkLoop OpenError
- SystemFdQuotaExceeded OpenError
- SystemResources OpenError
路径超过
max_path_bytes字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- WouldBlock OpenError
已请求非阻塞模式,但该操作无法立即返回。
std.Build.Cache.Manifest.addInputPath
函数
将文件或目录路径添加为被缓存进程的依赖。
调用 hit 时会检查内容,确保它与此前的内容匹配。
可以请求输入文件内容,随后通过返回的 InputPath.Index 的方法获取,但须先调用 hit。
目录内容视为按顺序排列的直属条目文件名列表,以空字节分隔。每个文件名前都有一个 Io.File.Kind 字节,其值加 1,避免零标签与条目分隔符混淆。
另见:
addDiscoveredPath
pub fn addInputPath(m: *Manifest, path: Path, options: AddInputPathOptions) Allocator.Error!InputPath.Index
参数
错误
- OutOfMemory
std.Build.Cache.Manifest.addInputPathOptional
函数
pub fn addInputPathOptional(m: *Manifest, opt_path: ?Path, options: AddInputPathOptions) Allocator.Error!void
参数
错误
- OutOfMemory
std.Build.Cache.Manifest.AddInputPathOptions
容器
字段
handle: PathHandle = .{ .file = null }若提供此句柄,调用 check 时将关闭它,除非同时设置了 request_handle。
stat: ?Stat = null
request_handle: bool = false若设置此项,则调用 check 后文件句柄仍保持打开。
request_contents: bool = false可根据 handle 请求文件或目录内容。
metadata_only: bool = false跳过内容哈希;元数据中的任何差异 均意味着缓存未命中。
std.Build.Cache.Manifest.borrowFiles
函数
pub fn borrowFiles(m: *const Manifest) SelfContainedFiles
参数
m: *const Manifest
std.Build.Cache.Manifest.check
函数
检查缓存中是否存在该输入。
可调用 final 获取其哈希的十六进制编码。
此函数还会获取清单文件的排他锁。因此,持有 Manifest 的进程会阻塞任何其他尝试获取该锁的进程。若 want_shared_lock 为 true,则缓存命中保证清单文件以共享模式锁定,缓存未命中保证以排他模式锁定。
调用 deinit 时释放清单文件锁。也可调用 toOwnedLock,取得能表示该锁的较小对象。调用 deinit 始终安全,无论此前是否调用过 toOwnedLock。
pub fn check( man: *Manifest, diag: *CheckDiagnostic, parent_progress_node: std.Progress.Node, ) CheckError!CheckResult
参数
错误
- CacheCheckFailed
无法检查缓存, 原因已记录到
diagnostic字段。- Canceled Cancelable
调用方请求停止异步操作。
- OutOfMemory Error
std.Build.Cache.Manifest.CheckDiagnostic
容器
字段
std.Build.Cache.Manifest.CheckDiagnostic.FileOp
容器
字段
std.Build.Cache.Manifest.CheckDiagnostic.FileOp.path
函数
返回的 Path 引用 Manifest.contents。
pub fn path(fo: FileOp, manifest: *const Manifest) Path
参数
std.Build.Cache.Manifest.CheckDiagnostic.fmt
函数
pub fn fmt(diagnostic: CheckDiagnostic, manifest: *const Manifest) Format
参数
diagnostic: CheckDiagnostic
manifest: *const Manifest
std.Build.Cache.Manifest.CheckDiagnostic.Format
容器
字段
diagnostic: CheckDiagnostic
manifest: *const Manifest
std.Build.Cache.Manifest.CheckDiagnostic.Format.format
函数
pub fn format(this: @This(), w: *Io.Writer) Io.Writer.Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Build.Cache.Manifest.checkDiscoveredPath
函数
fn checkDiscoveredPath( m: *Manifest, diag: *CheckDiagnostic, file_off: File.Offset, contents: []u8, ) CheckError!CheckResult
参数
错误
- CacheCheckFailed
无法检查缓存, 原因已记录到
diagnostic字段。- Canceled Cancelable
调用方请求停止异步操作。
- OutOfMemory Error
std.Build.Cache.Manifest.CheckError
错误集合
错误
- CacheCheckFailed
无法检查缓存, 原因已记录到
diagnostic字段。- Canceled Cancelable
调用方请求停止异步操作。
- OutOfMemory Error
std.Build.Cache.Manifest.checkInputPath
函数
返回时,无论命中还是未命中,都会填充 disk_contents 摘要及 stat。
fn checkInputPath( m: *Manifest, diag: *CheckDiagnostic, file_off: File.Offset, input_path: *InputPath, disk_contents: []u8, input_contents: []u8, ) CheckError!CheckResult
参数
m: *Manifest
diag: *CheckDiagnostic
file_off: File.Offset
input_path: *InputPath
disk_contents: []u8
input_contents: []u8
错误
- CacheCheckFailed
无法检查缓存, 原因已记录到
diagnostic字段。- Canceled Cancelable
调用方请求停止异步操作。
- OutOfMemory Error
std.Build.Cache.Manifest.checkLocked
函数
不读取或修改 self.hash.hasher。断言 self.files 仅包含原始输入文件。
fn checkLocked(m: *Manifest, diag: *CheckDiagnostic) CheckError!CheckResult
参数
m: *Manifest
diag: *CheckDiagnostic
错误
- CacheCheckFailed
无法检查缓存, 原因已记录到
diagnostic字段。- Canceled Cancelable
调用方请求停止异步操作。
- OutOfMemory Error
std.Build.Cache.Manifest.checkProgressless
函数
pub fn checkProgressless(man: *Manifest, diag: *CheckDiagnostic) CheckError!CheckResult
参数
man: *Manifest
diag: *CheckDiagnostic
错误
- CacheCheckFailed
无法检查缓存, 原因已记录到
diagnostic字段。- Canceled Cancelable
调用方请求停止异步操作。
- OutOfMemory Error
std.Build.Cache.Manifest.CheckResult
容器
字段
std.Build.Cache.Manifest.CheckResult.fmt
函数
pub fn fmt(check_result: CheckResult, manifest: *const Manifest) Format
参数
check_result: CheckResult
manifest: *const Manifest
std.Build.Cache.Manifest.CheckResult.Format
容器
字段
check_result: CheckResult
manifest: *const Manifest
std.Build.Cache.Manifest.CheckResult.Format.format
函数
pub fn format(this: @This(), w: *Io.Writer) Io.Writer.Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Build.Cache.Manifest.deinit
函数
释放清单文件及 Manifest 使用的全部内存。
必须先调用 Manifest.hit。
不要忘记在此之前调用 finalize!
pub fn deinit(m: *Manifest) void
参数
m: *Manifest
std.Build.Cache.Manifest.DiscoveredPath
容器
字段
unresolved: Path
prefixed: PrefixedPath
std.Build.Cache.Manifest.fail
类型函数
fn fail(ptr: *CheckDiagnostic, d: CheckDiagnostic) error{CacheCheckFailed}
参数
ptr: *CheckDiagnostic
d: CheckDiagnostic
错误
- CacheCheckFailed
std.Build.Cache.Manifest.File
容器
清单文件中为每个被跟踪输入文件存储的数据。
字段
std.Build.Cache.Manifest.File.Flags
容器
字段
std.Build.Cache.Manifest.File.HashContext
容器
有意让仅在 prefix 以外的标志上存在差异的文件匹配。
字段
contents: []const u8
std.Build.Cache.Manifest.File.HashContext.eql
函数
pub fn eql(this: @This(), a_off: Offset, b_off: Offset, b_index: usize) bool
参数
std.Build.Cache.Manifest.File.HashContext.hash
函数
pub fn hash(this: @This(), off: Offset) u32
参数
this: @This()
off: Offset
std.Build.Cache.Manifest.File.hashFromMetadata
函数
fn hashFromMetadata(file: *File) void
参数
file: *File
std.Build.Cache.Manifest.File.Kind
容器
编码后的目录内容中路径名的前缀编号。
从 1 开始编号,使空字节可无歧义地用作
条目分隔符。
字段
file = 1
directory = 2
other = 3
std.Build.Cache.Manifest.File.Kind.fromStat
函数
pub fn fromStat(kind: Io.File.Kind) @This()
参数
std.Build.Cache.Manifest.File.Offset
容器
条目起点在 Manifest.contents 中的字节索引。
字段
_
std.Build.Cache.Manifest.File.Offset.flagsAndPath
函数
pub fn flagsAndPath(off: File.Offset, contents: []const u8) [:0]const u8
参数
std.Build.Cache.Manifest.File.Offset.get
函数
pub fn get(offset: Offset, contents: []u8) *File
参数
offset: Offset
contents: []u8
std.Build.Cache.Manifest.File.Offset.getConst
函数
pub fn getConst(offset: Offset, contents: []const u8) *const File
参数
offset: Offset
contents: []const u8
std.Build.Cache.Manifest.File.Offset.getFallible
函数
pub fn getFallible(offset: Offset, contents: []u8) error{InvalidFormat}!*File
参数
offset: Offset
contents: []u8
错误
- InvalidFormat
std.Build.Cache.Manifest.File.Offset.getFallibleConst
函数
pub fn getFallibleConst(offset: Offset, contents: []const u8) error{InvalidFormat}!*const File
参数
offset: Offset
contents: []const u8
错误
- InvalidFormat
std.Build.Cache.Manifest.File.Offset.path
函数
pub fn path(off: File.Offset, contents: []const u8) [:0]const u8
参数
std.Build.Cache.Manifest.File.Offset.pathFallible
函数
pub fn pathFallible(off: File.Offset, contents: []const u8) error{InvalidFormat}![:0]const u8
参数
错误
- InvalidFormat
std.Build.Cache.Manifest.File.Offset.pathOrDot
函数
pub fn pathOrDot(off: File.Offset, contents: []const u8) [:0]const u8
参数
std.Build.Cache.Manifest.File.setStat
函数
fn setStat(file: *File, m: *Manifest, s: Stat) Io.Cancelable!void
参数
错误
- Canceled
调用方请求停止异步操作。
std.Build.Cache.Manifest.File.setStatChanged
函数
若统计信息已更改则返回 true,并用新的 stat 值更新 file。
fn setStatChanged(file: *File, m: *Manifest, s: Stat) Io.Cancelable!bool
参数
错误
- Canceled
调用方请求停止异步操作。
std.Build.Cache.Manifest.File.setStatUnchecked
函数
fn setStatUnchecked(file: *File, s: Stat) void
参数
std.Build.Cache.Manifest.File.sizeOf
函数
path_len 不包含空字节。
pub fn sizeOf(path_len: usize) usize
参数
path_len: usize
std.Build.Cache.Manifest.File.stat
函数
fn stat(file: *const File) Stat
参数
file: *const File
std.Build.Cache.Manifest.Files
类型
std.Build.Cache.Manifest.finalDigest
函数
fn finalDigest(m: *Manifest) BinDigest
参数
m: *Manifest
std.Build.Cache.Manifest.finalize
函数
若 want_shared_lock 为 true,此函数自动将
独占锁降级为共享锁。
pub fn finalize(m: *Manifest) !void
参数
m: *Manifest
std.Build.Cache.Manifest.hashDir
函数
将已排序、已编码的目录条目追加到 contents。
fn hashDir( gpa: Allocator, io: Io, dir: Io.Dir, bin_digest: *[Hasher.mac_length]u8, contents: *std.ArrayList(u8), ) HashDirError!void
参数
错误
- AccessDenied Error
- Canceled Cancelable
调用方请求停止异步操作。
- OutOfMemory Error
- PermissionDenied Error
- SystemResources Error
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.Build.Cache.Manifest.hashDir.lessThan
函数
pub fn lessThan(this: @This(), lhs: u32, rhs: u32) bool
参数
this: @This()
lhs: u32
rhs: u32
std.Build.Cache.Manifest.HashDirError
错误集合
错误
- AccessDenied Error
- Canceled Cancelable
调用方请求停止异步操作。
- OutOfMemory Error
- PermissionDenied Error
- SystemResources Error
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.Build.Cache.Manifest.hashFile
函数
fn hashFile(io: Io, file: Io.File, bin_digest: *[Hasher.mac_length]u8) Io.File.ReadPositionalError!void
参数
错误
- AccessDenied
在 WASI 中,当文件描述符不具有读取 所需的权限时发生此错误。
- Canceled Cancelable
调用方请求停止异步操作。
- InputOutput
- IsDir
尝试将目录文件描述符当作普通文件读取。
- LockViolation
由于锁定而无法读取文件。根据
Io实现的不同,读取已锁定文件可能返回此错误,也可能忽略锁。- NotOpenForReading
打开文件时未授予读取能力。
- SystemResources
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- Unseekable
此文件不支持按位置读取。
- WouldBlock
已启用非阻塞模式,且从该文件描述符读取会阻塞。
std.Build.Cache.Manifest.hashFileAppend
函数
fn hashFileAppend( io: Io, file: Io.File, bin_digest: *[Hasher.mac_length]u8, al: *std.ArrayList(u8), gpa: Allocator, ) (Io.File.ReadPositionalError || Allocator.Error)!void
参数
std.Build.Cache.Manifest.hitDigest
函数
另请参阅 hitDigestHex。
pub fn hitDigest(m: *Manifest) BinDigest
参数
m: *Manifest
std.Build.Cache.Manifest.hitDigestHex
函数
pub fn hitDigestHex(m: *Manifest) HexDigest
参数
m: *Manifest
std.Build.Cache.Manifest.InputPath
容器
源文件和目录,其前缀与相对路径参与缓存清单摘要计算。这些信息用于仅在缓存未命中时才惰性计算输入文件的哈希。
File.prefix、File.path 和 File.mode 始终填充;但 File 的其他字段是否填充,取决于 InputPath 中的字段。
字段
request_handle: bool决定 check 将保持句柄打开还是关闭句柄。
have_handle: bool决定是否填充 handle。
have_stat: bool确定是否填充 File.size、File.inode 和 File.mtime。
have_digest: bool确定是否填充了 File.digest。
contents: struct {
pop_off: enum(u32) { unpopulated = std.math.maxInt(u32), _ },
req_len: enum(u32) { unrequested = std.math.maxInt(u32) - 1, requested = std.math.maxInt(u32), _ },
pub const requested: @This() = .{
.pop_off = .unpopulated,
.req_len = .requested,
};
pub const unrequested: @This() = .{
.pop_off = .unpopulated,
.req_len = .unrequested,
};
pub fn populated(p: Populated) @This() {
return .{
.pop_off = @fromBackingInt(p.off),
.req_len = @fromBackingInt(p.len),
};
}
pub const Unwrapped = union(enum) {
unrequested,
requested,
populated: Populated,
};
pub const Populated = struct {
off: u32,
len: u32,
};
pub fn unwrap(this: @This()) Unwrapped {
return switch (this.pop_off) {
.unpopulated => switch (this.req_len) {
.unrequested => .unrequested,
.requested => .requested,
_ => unreachable,
},
_ => .{ .populated = .{
.off = @backingInt(this.pop_off),
.len = @backingInt(this.req_len),
} },
};
}
pub fn get(this: @This(), all_contents: []const u8) ?[]const u8 {
return switch (this.unwrap()) {
.unrequested, .requested => null,
.populated => |p| all_contents[p.off..][0..p.len],
};
}
}
handle: union {
file: Io.File,
dir: Io.Dir,
}have_handle 决定是否填充此值。
std.Build.Cache.Manifest.InputPath.get
函数
pub fn get(this: @This(), all_contents: []const u8) ?[]const u8
参数
this: @This()
all_contents: []const u8
std.Build.Cache.Manifest.InputPath.getHandle
函数
pub fn getHandle(this: @This(), file: *const File) Handle
参数
this: @This()
file: *const File
std.Build.Cache.Manifest.InputPath.Handle
容器
字段
std.Build.Cache.Manifest.InputPath.Index
容器
Manifest.input_paths 中的索引。
字段
_
std.Build.Cache.Manifest.InputPath.Index.contents
函数
pub fn contents(i: @This(), manifest: *const Manifest) []const u8
参数
i: @This()
manifest: *const Manifest
std.Build.Cache.Manifest.InputPath.Index.get
函数
pub fn get(i: @This(), manifest: *const Manifest) InputPath
参数
i: @This()
manifest: *const Manifest
std.Build.Cache.Manifest.InputPath.Index.offset
函数
pub fn offset(i: @This(), manifest: *const Manifest) File.Offset
参数
i: @This()
manifest: *const Manifest
std.Build.Cache.Manifest.InputPath.populated
函数
pub fn populated(p: Populated) @This()
参数
p: Populated
std.Build.Cache.Manifest.InputPath.Populated
容器
字段
off: u32
len: u32
std.Build.Cache.Manifest.InputPath.requested
常量
@This()
std.Build.Cache.Manifest.InputPath.unrequested
常量
@This()
std.Build.Cache.Manifest.InputPath.unwrap
函数
pub fn unwrap(this: @This()) Unwrapped
参数
this: @This()
std.Build.Cache.Manifest.InputPath.Unwrapped
容器
字段
std.Build.Cache.Manifest.isProblematicTimestamp
函数
fn isProblematicTimestamp(man: *Manifest, timestamp: Io.Timestamp) error{Canceled}!bool
参数
错误
- Canceled
std.Build.Cache.Manifest.missDigest
函数
另见 missDigestHex。
pub fn missDigest(m: *Manifest) BinDigest
参数
m: *Manifest
std.Build.Cache.Manifest.missDigestHex
函数
pub fn missDigestHex(m: *Manifest) HexDigest
参数
m: *Manifest
std.Build.Cache.Manifest.missInput
函数
恢复输入文件内容,为缓存未命中的流程做准备。
保留 off 之前的全部内容,避免重复计算摘要和文件状态。
此外,此函数负责填充未命中文件之后其余输入文件的摘要与元数据。
fn missInput( m: *Manifest, diag: *CheckDiagnostic, next_file_index: usize, input_contents_len: usize, manifest_size: usize, result: CheckResult, ) CheckError!CheckResult
参数
m: *Manifest
diag: *CheckDiagnostic
next_file_index: usize
input_contents_len: usize
manifest_size: usize
result: CheckResult
错误
- CacheCheckFailed
无法检查缓存, 原因已记录到
diagnostic字段。- Canceled Cancelable
调用方请求停止异步操作。
- OutOfMemory Error
std.Build.Cache.Manifest.PathHandle
容器
字段
std.Build.Cache.Manifest.PathHandle.have
函数
pub fn have(this: @This()) bool
参数
this: @This()
std.Build.Cache.Manifest.PathHandle.isDirectory
函数
pub fn isDirectory(this: @This()) bool
参数
this: @This()
std.Build.Cache.Manifest.populateDirectory
函数
fn populateDirectory( m: *Manifest, file: *File, need_stat: bool, handle: Io.Dir, contents: ?[]const u8, metadata_only: bool, diagnostic: ?*AddDiscoveredPathDiagnostic, ) AddDiscoveredPathError!void
参数
m: *Manifest
file: *File
need_stat: bool
handle: Io.Dir
contents: ?[]const u8
metadata_only: bool
diagnostic: ?*AddDiscoveredPathDiagnostic
错误
- Canceled Cancelable
调用方请求停止异步操作。
- FileSystemFailure
返回此值时会填充诊断信息。 如果同时提供了 contents 和 stat,则此分支不可达。
- OutOfMemory Error
std.Build.Cache.Manifest.populateFile
函数
fn populateFile( m: *Manifest, file: *File, need_stat: bool, handle: Io.File, contents: ?[]const u8, metadata_only: bool, diagnostic: ?*AddDiscoveredPathDiagnostic, ) AddDiscoveredPathError!void
参数
m: *Manifest
file: *File
need_stat: bool
handle: Io.File
contents: ?[]const u8
metadata_only: bool
diagnostic: ?*AddDiscoveredPathDiagnostic
错误
- Canceled Cancelable
调用方请求停止异步操作。
- FileSystemFailure
返回此值时会填充诊断信息。 如果同时提供了 contents 和 stat,则此分支不可达。
- OutOfMemory Error
std.Build.Cache.Manifest.populateFileSystemInputs
函数
pub fn populateFileSystemInputs(man: *const Manifest, buf: *std.ArrayList(u8)) Allocator.Error!void
参数
错误
- OutOfMemory
std.Build.Cache.Manifest.populateInputPath
函数
类似 checkInputPath 和 checkDiscoveredPath,但不与文件系统比较元数据或摘要。
仅确保元数据与摘要可用。
fn populateInputPath( m: *Manifest, diag: *CheckDiagnostic, file_off: File.Offset, input_path: *InputPath, contents: []u8, ) CheckError!void
参数
错误
- CacheCheckFailed
无法检查缓存, 原因已记录到
diagnostic字段。- Canceled Cancelable
调用方请求停止异步操作。
- OutOfMemory Error
std.Build.Cache.Manifest.populateMissingInputFileHashes
函数
fn populateMissingInputFileHashes( m: *Manifest, diag: *CheckDiagnostic, next_file_index: usize, result: CheckResult, ) CheckError!CheckResult
参数
错误
- CacheCheckFailed
无法检查缓存, 原因已记录到
diagnostic字段。- Canceled Cancelable
调用方请求停止异步操作。
- OutOfMemory Error
std.Build.Cache.Manifest.SelfContainedFiles
容器
字段
std.Build.Cache.Manifest.SelfContainedFiles.deinit
函数
pub fn deinit(scf: *SelfContainedFiles, gpa: Allocator) void
参数
scf: *SelfContainedFiles
gpa: Allocator
std.Build.Cache.Manifest.SelfContainedFiles.empty
常量
@This()
std.Build.Cache.Manifest.SelfContainedFiles.path
函数
pub fn path(scf: *const SelfContainedFiles, file_offset: File.Offset) [:0]const u8
参数
scf: *const SelfContainedFiles
file_offset: File.Offset
std.Build.Cache.Manifest.shrinkFilesToInput
函数
fn shrinkFilesToInput(m: *Manifest) void
参数
m: *Manifest
std.Build.Cache.Manifest.Stat
容器
字段
std.Build.Cache.Manifest.Stat.init
函数
pub fn init(other: Io.File.Stat) Stat
参数
std.Build.Cache.Manifest.State
容器
字段
input调用 addInputPath、addInputPathOptional 及 Manifest.hash 的方法。所有输入文件和状态添加完毕后,调用 check。
hit
hit_digested已调用 hitDigest。不允许再执行任何操作。
miss已调用 check,且发生缓存未命中。尚未调用 missDigest。仍可访问未命中诊断
数据。调用 addDiscoveredPath 可添加新发现的文件和目录。
miss_discovered发生了缓存未命中,尚未调用 missDigest。调用 addDiscoveredPath 可添加更多发现的文件
和目录。此后不得再访问未命中诊断数据。
miss_digested已调用 missDigest,但尚未调用 finalize。
miss_finalized缓存清单已写入磁盘,下次使用相同输入检查时将命中。 不允许再执行其他操作。
std.Build.Cache.Manifest.takeFiles
函数
pub fn takeFiles(m: *Manifest) SelfContainedFiles
参数
m: *Manifest
std.Build.Cache.Manifest.toOwnedLock
函数
仅取得维持清单文件锁所需的数据。
仍可安全地对 Manifest 执行 deinit。
不要忘记在此之前调用 finalize!
pub fn toOwnedLock(self: *Manifest) Lock
参数
self: *Manifest
std.Build.Cache.Manifest.transitionToMissDiscovered
函数
fn transitionToMissDiscovered(m: *Manifest) void
参数
m: *Manifest
std.Build.Cache.Manifest.upgradeToExclusiveLock
函数
fn upgradeToExclusiveLock(m: *Manifest, diag: *CheckDiagnostic) error{CacheCheckFailed}!bool
参数
m: *Manifest
diag: *CheckDiagnostic
错误
- CacheCheckFailed
std.Build.Cache.mem
别名
别名目标 std.mem
std.Build.Cache.obtain
函数
初始化成功后,务必调用 Manifest.deinit。
pub fn obtain(cache: *Cache) Manifest
参数
cache: *Cache
std.Build.Cache.Path
别名
别名目标 std.Build.Cache.Path
std.Build.Cache.PrefixedPath
容器
字段
prefix: PrefixIndex
sub_path: []const u8
std.Build.Cache.prefixes
函数
pub fn prefixes(cache: *const Cache) []const Directory
参数
cache: *const Cache
std.Build.Cache.PrefixIndex
类型
std.Build.Cache.resolveAppendPath
函数
fn resolveAppendPath(cache: *const Cache, contents: *std.ArrayList(u8), path: Path) !PrefixIndex
参数
std.Build.Cache.std
别名
别名目标 std
std.Build.Cache.testGetCurrentFileTimestamp
函数
创建并写入文件,关闭它,然后获取其 stat.mtime 时间戳。
fn testGetCurrentFileTimestamp(io: Io, dir: Io.Dir) !Io.Timestamp
参数
std.Build.Cache.testing
别名
别名目标 std.testing
源码
std/Build/Cache.zig
//! 跟踪与 Zig 编译器和构建系统产物相关的文件输入元数据,
//! 据此确定是否必须重新生成这些产物,
//! 或者可以从文件系统中的缓存目录中取回。
//!
const Cache = @This();
const builtin = @import("builtin");
const std = @import("std");
const Io = std.Io;
const crypto = std.crypto;
const assert = std.debug.assert;
const testing = std.testing;
const mem = std.mem;
const fmt = std.fmt;
const Allocator = std.mem.Allocator;
const log = std.log.scoped(.cache);
gpa: Allocator,
io: Io,
manifest_dir: Io.Dir,
hash: HashHelper = .{},
/// 多个线程会访问此值,由互斥锁保护。
recent_problematic_timestamp: Io.Timestamp = .zero,
mutex: Io.Mutex = .init,
/// 一组字符串,例如 Zig 库目录或项目源码根目录,在将文件路径放入缓存之前会从路径中移除,并替换为单字符标记。
/// 目的不是节省空间,而是消除绝对文件路径,从而提高缓存的可移植性,以及在高级用例中的实用性。
///
///
///
prefixes_buffer: [5]Directory = undefined,
prefixes_len: usize = 0,
/// 用于识别前缀。引用外部内存。
cwd: []const u8,
pub const Path = @import("Cache/Path.zig");
pub const Directory = @import("Cache/Directory.zig");
pub const DepTokenizer = @import("Cache/DepTokenizer.zig");
pub fn addPrefix(cache: *Cache, directory: Directory) void {
cache.prefixes_buffer[cache.prefixes_len] = directory;
cache.prefixes_len += 1;
}
/// 初始化成功后,务必调用 `Manifest.deinit`。
pub fn obtain(cache: *Cache) Manifest {
return .{
.cache = cache,
.hash = cache.hash,
.manifest_file = null,
.state = .input,
};
}
pub fn prefixes(cache: *const Cache) []const Directory {
return cache.prefixes_buffer[0..cache.prefixes_len];
}
const PrefixIndex = u6;
const PrefixedPath = struct {
prefix: PrefixIndex,
sub_path: []const u8,
};
fn appendPrefixedPath(cache: *const Cache, contents: *std.ArrayList(u8), prefixed_path: PrefixedPath) !PrefixIndex {
const end = contents.items.len + prefixed_path.sub_path.len;
const needed_alignment = @alignOf(Manifest.File) - (end % @alignOf(Manifest.File));
assert(needed_alignment >= 1); // 至少总需要一个空字节。
// 此处额外的 +1 是因为 `Manifest.contents` 必须始终保留至少一个未使用容量。
try contents.ensureTotalCapacity(cache.gpa, end + needed_alignment + 1);
contents.appendSliceAssumeCapacity(prefixed_path.sub_path);
contents.appendNTimesAssumeCapacity(0, needed_alignment);
return prefixed_path.prefix;
}
fn resolveAppendPath(cache: *const Cache, contents: *std.ArrayList(u8), path: Path) !PrefixIndex {
const gpa = cache.gpa;
const cwd = cache.cwd;
const path_start = contents.items.len;
const resolved_path = try std.fs.path.resolveAlloc(gpa, &.{
path.root_dir.path orelse cwd,
path.subPathOrDot(),
});
defer gpa.free(resolved_path);
for (cache.prefixes(), 0..) |prefix, i| {
const pp = prefix.path orelse continue;
contents.shrinkRetainingCapacity(path_start);
try std.fs.path.relativeAppend(gpa, contents, cwd, null, pp, resolved_path);
const relative = contents.items[path_start..];
var component_iterator: std.fs.path.NativeComponentIterator = .init(relative);
if (component_iterator.root() != null) continue;
const first_component = component_iterator.first();
if (first_component != null and mem.eql(u8, first_component.?.name, "..")) continue;
const needed_alignment = @alignOf(Manifest.File) - (contents.items.len % @alignOf(Manifest.File));
assert(needed_alignment >= 1); // 始终至少需要一个空字节。
// 此处额外加 1,是因为要求 `Manifest.contents`
// 始终保留至少 1 个未使用容量。
try contents.ensureUnusedCapacity(gpa, needed_alignment + 1);
contents.appendNTimesAssumeCapacity(0, needed_alignment);
return @intCast(i);
}
contents.shrinkRetainingCapacity(path_start);
try contents.appendSlice(gpa, resolved_path);
const needed_alignment = @alignOf(Manifest.File) - (contents.items.len % @alignOf(Manifest.File));
assert(needed_alignment >= 1); // 至少总需要一个空字节。
// 此处额外的 +1 是因为 `Manifest.contents` 必须始终保留至少一个未使用容量。
try contents.ensureUnusedCapacity(gpa, needed_alignment + 1);
contents.appendNTimesAssumeCapacity(0, needed_alignment);
return 0;
}
/// 这是 128 位值;即使有 2^54 个缓存条目,冲突概率仍低于 10^-6。
pub const bin_digest_len = 16;
pub const hex_digest_len = bin_digest_len * 2;
pub const BinDigest = [bin_digest_len]u8;
pub const HexDigest = [hex_digest_len]u8;
/// 用于对文件内容进行哈希的类型。目前是 SipHash128(1, 3),
/// 因为它为 Manifest 的用例提供了足够的抗碰撞性,
/// 同时也是当前最快的选项之一。
pub const Hasher = crypto.auth.siphash.SipHash128(1, 3);
/// 包含随机字节、可以复制的初始状态。
/// 当清单格式以不向后兼容的方式修改时,使用新的随机字节更新它。
///
pub const hasher_init: Hasher = Hasher.init(&.{
0x02, 0xe9, 0xfa, 0xfe,
0xe0, 0x95, 0x81, 0x55,
0xf5, 0x5a, 0x15, 0xcb,
0x4a, 0xf4, 0x00, 0x09,
});
pub const HashHelper = struct {
hasher: Hasher = hasher_init,
pub fn addBytes(hh: *HashHelper, bytes: []const u8) void {
hh.hasher.update(mem.asBytes(&bytes.len));
hh.hasher.update(bytes);
}
pub fn addBytesZ(hh: *HashHelper, bytes: [:0]const u8) void {
hh.hasher.update(mem.absorbSentinel(bytes));
}
pub fn addOptionalBytes(hh: *HashHelper, optional_bytes: ?[]const u8) void {
hh.add(optional_bytes != null);
hh.addBytes(optional_bytes orelse return);
}
pub fn addListOfBytes(hh: *HashHelper, list_of_bytes: []const []const u8) void {
hh.add(list_of_bytes.len);
for (list_of_bytes) |bytes| hh.addBytes(bytes);
}
pub fn addOptionalListOfBytes(hh: *HashHelper, optional_list_of_bytes: ?[]const []const u8) void {
hh.add(optional_list_of_bytes != null);
hh.addListOfBytes(optional_list_of_bytes orelse return);
}
/// 将输入值转换为字节,并记录为被缓存进程的依赖项。
pub fn add(hh: *HashHelper, x: anytype) void {
switch (@TypeOf(x)) {
std.SemanticVersion => {
hh.add(x.major);
hh.add(x.minor);
hh.add(x.patch);
},
std.Target.Os.TaggedVersionRange => {
switch (x) {
.hurd => |hurd| {
hh.add(hurd.range.min);
hh.add(hurd.range.max);
hh.add(hurd.glibc);
},
.linux => |linux| {
hh.add(linux.range.min);
hh.add(linux.range.max);
hh.add(linux.glibc);
hh.add(linux.android);
},
.windows => |windows| {
hh.add(windows.min);
hh.add(windows.max);
},
.semver => |semver| {
hh.add(semver.min);
hh.add(semver.max);
},
.none => {},
}
},
std.zig.BuildId => switch (x) {
.none, .fast, .uuid, .sha1, .md5 => hh.add(std.meta.activeTag(x)),
.hexstring => |hex_string| hh.addBytes(hex_string.toSlice()),
},
else => switch (@typeInfo(@TypeOf(x))) {
.bool, .int, .@"enum", .array => hh.addBytes(mem.asBytes(&x)),
else => @compileError("unable to hash type " ++ @typeName(@TypeOf(x))),
},
}
}
pub fn addOptional(hh: *HashHelper, optional: anytype) void {
hh.add(optional != null);
hh.add(optional orelse return);
}
/// 返回输入的十六进制编码哈希,不修改状态。
pub fn peek(hh: HashHelper) [hex_digest_len]u8 {
var copy = hh;
return copy.final();
}
pub fn peekBin(hh: HashHelper) BinDigest {
var copy = hh;
var bin_digest: BinDigest = undefined;
copy.hasher.final(&bin_digest);
return bin_digest;
}
/// 返回输入的十六进制编码哈希,并修改哈希器状态。
pub fn final(hh: *HashHelper) HexDigest {
var bin_digest: BinDigest = undefined;
hh.hasher.final(&bin_digest);
return binToHex(bin_digest);
}
pub fn oneShot(bytes: []const u8) [hex_digest_len]u8 {
var hasher: Hasher = hasher_init;
hasher.update(bytes);
var bin_digest: BinDigest = undefined;
hasher.final(&bin_digest);
return binToHex(bin_digest);
}
};
pub fn binToHex(bin_digest: BinDigest) HexDigest {
var out_digest: HexDigest = undefined;
var w: Io.Writer = .fixed(&out_digest);
w.printHex(&bin_digest, .lower) catch unreachable;
return out_digest;
}
pub const Lock = struct {
manifest_file: Io.File,
pub fn release(lock: *Lock, io: Io) void {
if (builtin.os.tag == .windows) {
// Windows 不保证关闭文件句柄时立即释放锁。
// 参见 LockFileEx 文档。
lock.manifest_file.unlock(io);
}
lock.manifest_file.close(io);
lock.* = undefined;
}
};
/// 格式:连续的 `Manifest.File` 序列,后跟最终的零终止字节,以区分空清单文件和包含零个文件的清单。
///
///
pub const Manifest = struct {
cache: *Cache,
/// 用于增量哈希的当前状态。
hash: HashHelper,
/// 此值为 null 时,`Manifest` 处于“检查前”阶段,否则处于“检查后”阶段。
manifest_file: ?Io.File,
state: State,
/// 调用 `check` 前将此标志设为 true,表示缓存命中后,使用缓存的代码
/// 不会修改缓存目录中的文件。这样多个进程
/// 就可以同时使用同一缓存目录。
want_shared_lock: bool = true,
have_exclusive_lock: bool = false,
// 指示 isProblematicTimestamp 执行一次文件系统写入,
// 以获取供下次调用使用的有问题时间戳。之后的调用
// 复用同一时间戳,避免不必要的文件系统写入。
want_refresh_timestamp: bool = true,
/// 使用 `Cache.gpa`。
files: Files = .empty,
/// 索引与 `files` 对齐,但仅在调用 `hit` 之前如此。使用 `Cache.gpa`。
///
input_paths: std.ArrayList(InputPath) = .empty,
/// 记录上次写入文件系统的时间,以观察文件系统按自身时间粒度认定的当前时间。
///
recent_problematic_timestamp: Io.Timestamp = .zero,
/// 完整的清单文件内容,但不包括末尾的
/// 零字节。不过,始终保留至少 1 字节未使用容量,以便
/// 无需分配即可追加末尾终止字节。使用
/// `Cache.gpa`。
contents: std.ArrayList(u8) = .empty,
/// 所有已请求内容的 `input_paths` 中的全部内容,
/// 拼接而成。总字节大小必须小于 `max_input_content_len`,
/// 否则返回错误。
///
/// 调用 `addDiscoveredPath` 后,此数据失效。
all_input_content: std.ArrayList(u8) = .empty,
max_input_content_len: usize = std.math.maxInt(u32),
pub const Files = std.array_hash_map.Custom(File.Offset, void, File.HashContext, false);
pub const State = enum {
/// 调用 `addInputPath`、`addInputPathOptional` 及 `Manifest.hash` 的方法。所有输入文件和状态添加完毕后,调用 `check`。
///
input,
/// 已调用 `check` 且命中缓存。调用 `hitDigest` 查找缓存产物目录。
hit,
/// 已调用 `hitDigest`。不允许再执行任何操作。
hit_digested,
/// 已调用 `check`,且发生缓存未命中。尚未调用 `missDigest`。仍可访问未命中诊断
/// 数据。调用 `addDiscoveredPath` 可添加新发现的文件和目录。
miss,
/// 发生了缓存未命中,尚未调用 `missDigest`。调用 `addDiscoveredPath` 可添加更多发现的文件
/// 和目录。此后不得再访问未命中诊断数据。
miss_discovered,
/// 已调用 `missDigest`,但尚未调用 `finalize`。
miss_digested,
/// 缓存清单已写入磁盘,下次使用相同输入检查时将命中。
/// 不允许再执行其他操作。
miss_finalized,
};
/// 源文件和目录,其前缀与相对路径参与缓存清单摘要计算。这些信息用于仅在缓存未命中时才惰性计算输入文件的哈希。
///
/// `File.prefix`、`File.path` 和 `File.mode` 始终填充;但 `File` 的其他字段是否填充,取决于 `InputPath` 中的字段。
///
///
///
///
pub const InputPath = struct {
/// 决定 `check` 将保持句柄打开还是关闭句柄。
request_handle: bool,
/// 决定是否填充 `handle`。
have_handle: bool,
/// 确定是否填充 `File.size`、`File.inode` 和 `File.mtime`。
have_stat: bool,
/// 确定是否填充了 `File.digest`。
have_digest: bool,
contents: struct {
pop_off: enum(u32) { unpopulated = std.math.maxInt(u32), _ },
req_len: enum(u32) { unrequested = std.math.maxInt(u32) - 1, requested = std.math.maxInt(u32), _ },
pub const requested: @This() = .{
.pop_off = .unpopulated,
.req_len = .requested,
};
pub const unrequested: @This() = .{
.pop_off = .unpopulated,
.req_len = .unrequested,
};
pub fn populated(p: Populated) @This() {
return .{
.pop_off = @fromBackingInt(p.off),
.req_len = @fromBackingInt(p.len),
};
}
pub const Unwrapped = union(enum) {
unrequested,
requested,
populated: Populated,
};
pub const Populated = struct {
off: u32,
len: u32,
};
pub fn unwrap(this: @This()) Unwrapped {
return switch (this.pop_off) {
.unpopulated => switch (this.req_len) {
.unrequested => .unrequested,
.requested => .requested,
_ => unreachable,
},
_ => .{ .populated = .{
.off = @backingInt(this.pop_off),
.len = @backingInt(this.req_len),
} },
};
}
pub fn get(this: @This(), all_contents: []const u8) ?[]const u8 {
return switch (this.unwrap()) {
.unrequested, .requested => null,
.populated => |p| all_contents[p.off..][0..p.len],
};
}
},
/// `have_handle` 决定是否填充此值。
handle: union {
file: Io.File,
dir: Io.Dir,
},
pub const Handle = union(enum) {
none,
file: Io.File,
dir: Io.Dir,
};
/// `Manifest.input_paths` 中的索引。
pub const Index = enum(u32) {
_,
pub fn get(i: @This(), manifest: *const Manifest) InputPath {
return manifest.input_paths.items[@backingInt(i)];
}
pub fn offset(i: @This(), manifest: *const Manifest) File.Offset {
return manifest.files.keys()[@backingInt(i)];
}
pub fn contents(i: @This(), manifest: *const Manifest) []const u8 {
const input_path = get(i, manifest);
return input_path.contents.get(manifest.all_input_content.items).?;
}
};
pub fn getHandle(this: @This(), file: *const File) Handle {
return if (!this.have_handle) .none else switch (file.flags.is_directory) {
false => .{ .file = this.handle.file },
true => .{ .dir = this.handle.dir },
};
}
};
/// 清单文件中为每个被跟踪输入文件存储的数据。
pub const File = extern struct {
size: u64 align(1),
inode: Io.File.INode align(1),
/// 纳秒。
mtime: i64 align(1),
/// 为简化哈希逻辑,当 `Flags.metadata_only` 为 `true` 时,
/// 在 `hashFromMetadata` 中由大小、inode 和 mtime 计算此值。
digest: BinDigest align(1),
/// 从此字段开始延伸到路径末尾(不包含空字节)的字符串,用于计算清单摘要。
///
flags: Flags align(1),
/// 以零字节终止,再填充至 8 字节对齐。
path_start: [0]u8 align(1),
pub const Flags = packed struct(u8) {
is_directory: bool,
metadata_only: bool,
prefix: PrefixIndex,
};
/// 编码后的目录内容中路径名的前缀编号。
/// 从 `1` 开始编号,使空字节可无歧义地用作
/// 条目分隔符。
pub const Kind = enum(u8) {
file = 1,
directory = 2,
other = 3,
pub fn fromStat(kind: Io.File.Kind) @This() {
return switch (kind) {
.file => .file,
.directory => .directory,
else => .other,
};
}
};
/// 条目起点在 `Manifest.contents` 中的字节索引。
pub const Offset = enum(u32) {
_,
pub fn get(offset: Offset, contents: []u8) *File {
return @constCast(getConst(offset, contents));
}
pub fn getConst(offset: Offset, contents: []const u8) *const File {
return @ptrCast(@alignCast(contents[@backingInt(offset)..][0..@sizeOf(File)]));
}
pub fn getFallible(offset: Offset, contents: []u8) error{InvalidFormat}!*File {
// TODO: 使 @constCast 支持跨错误联合及可选类型的内存内强制转换。
return @constCast(try getFallibleConst(offset, contents));
}
pub fn getFallibleConst(offset: Offset, contents: []const u8) error{InvalidFormat}!*const File {
if (@backingInt(offset) + @sizeOf(File) >= contents.len) return error.InvalidFormat;
if (!mem.isAligned(@backingInt(offset), @alignOf(File))) return error.InvalidFormat;
return getConst(offset, contents);
}
pub fn flagsAndPath(off: File.Offset, contents: []const u8) [:0]const u8 {
const flags_off = @offsetOf(File, "flags");
comptime assert(@offsetOf(File, "path_start") - flags_off == 1);
const start = @backingInt(off) + flags_off;
// 从 path_start 偏移处开始扫描哨兵,因为 flags 可能为零。
const end = mem.findScalarPos(u8, contents, start + 1, 0).?;
return contents[start..end :0];
}
pub fn pathFallible(off: File.Offset, contents: []const u8) error{InvalidFormat}![:0]const u8 {
const path_start = @backingInt(off) + @offsetOf(File, "path_start");
const path_end = mem.findScalarPos(u8, contents, path_start, 0) orelse return error.InvalidFormat;
return contents[path_start..path_end :0];
}
pub fn path(off: File.Offset, contents: []const u8) [:0]const u8 {
return pathFallible(off, contents) catch unreachable;
}
pub fn pathOrDot(off: File.Offset, contents: []const u8) [:0]const u8 {
const p = pathFallible(off, contents) catch unreachable;
return if (p.len == 0) "." else p;
}
};
/// 有意让仅在 prefix 以外的标志上存在差异的文件匹配。
pub const HashContext = struct {
contents: []const u8,
pub fn hash(this: @This(), off: Offset) u32 {
const file_prefix = off.getConst(this.contents).flags.prefix;
const file_path = off.path(this.contents);
return @truncate(std.hash.Wyhash.hash(file_prefix, file_path));
}
pub fn eql(this: @This(), a_off: Offset, b_off: Offset, b_index: usize) bool {
_ = b_index;
const a_prefix = a_off.getConst(this.contents).flags.prefix;
const b_prefix = b_off.getConst(this.contents).flags.prefix;
if (a_prefix != b_prefix) return false;
const a_path = a_off.path(this.contents);
const b_path = b_off.path(this.contents);
return mem.eql(u8, a_path, b_path);
}
};
fn hashFromMetadata(file: *File) void {
var hasher = hasher_init;
hasher.update(mem.asBytes(&file.size));
hasher.update(mem.asBytes(&file.inode));
hasher.update(mem.asBytes(&file.mtime));
hasher.final(&file.digest);
}
fn stat(file: *const File) Stat {
return .{
.size = file.size,
.inode = file.inode,
.mtime = .fromNanoseconds(file.mtime),
};
}
fn setStatUnchecked(file: *File, s: Stat) void {
file.size = s.size;
file.inode = s.inode;
file.mtime = @intCast(s.mtime.toNanoseconds());
}
fn setStat(file: *File, m: *Manifest, s: Stat) Io.Cancelable!void {
setStatUnchecked(file, s);
if (try m.isProblematicTimestamp(s.mtime)) {
// 实际文件的时间戳不可靠;强制对其进行哈希。
file.mtime = 0;
file.inode = 0;
}
}
/// 若统计信息已更改则返回 true,并用新的 stat 值更新 `file`。
fn setStatChanged(file: *File, m: *Manifest, s: Stat) Io.Cancelable!bool {
if (s.size == file.size and
s.mtime.nanoseconds == file.mtime and
s.inode == file.inode)
{
return false;
} else {
try setStat(file, m, s);
return true;
}
}
/// `path_len` 不包含空字节。
pub fn sizeOf(path_len: usize) usize {
const end = @offsetOf(File, "path_start") + path_len;
const needed_alignment = @alignOf(File) - (end % @alignOf(File));
assert(needed_alignment >= 1); // 始终至少需要一个空字节。
return end + needed_alignment;
}
};
pub const CheckDiagnostic = union(enum) {
manifest_create: Io.File.OpenError,
manifest_stat: Io.File.StatError,
manifest_oversize,
manifest_read: Io.File.ReadPositionalError,
manifest_lock: Io.File.LockError,
file_open: FileOp,
file_stat: FileOp,
file_read: FileOp,
file_hash: FileOp,
pub const FileOp = struct {
file_offset: File.Offset,
err: anyerror,
/// 返回的 `Path` 引用 `Manifest.contents`。
pub fn path(fo: FileOp, manifest: *const Manifest) Path {
const contents = manifest.contents.items;
const prefix = fo.file_offset.get(contents).flags.prefix;
return .{
.root_dir = manifest.cache.prefixes()[prefix],
.sub_path = fo.file_offset.path(contents),
};
}
};
pub const Format = struct {
diagnostic: CheckDiagnostic,
manifest: *const Manifest,
pub fn format(this: @This(), w: *Io.Writer) Io.Writer.Error!void {
switch (this.diagnostic) {
.manifest_oversize => return w.writeAll(@tagName(this.diagnostic)),
.manifest_create, .manifest_stat, .manifest_read, .manifest_lock => |e| {
return w.print("{t} {t}", .{ this.diagnostic, e });
},
.file_open, .file_stat, .file_read, .file_hash => |op| {
const path = op.path(this.manifest);
return w.print("{t} {t} {f}", .{ this.diagnostic, op.err, path });
},
}
}
};
pub fn fmt(diagnostic: CheckDiagnostic, manifest: *const Manifest) Format {
return .{
.diagnostic = diagnostic,
.manifest = manifest,
};
}
};
pub const Stat = struct {
size: u64,
inode: Io.File.INode,
mtime: Io.Timestamp,
pub fn init(other: Io.File.Stat) Stat {
return .{
.size = other.size,
.inode = other.inode,
.mtime = other.mtime,
};
}
};
pub const PathHandle = union(enum) {
file: ?Io.File,
/// 若提供,此句柄必须以支持迭代的方式打开。
dir: ?Io.Dir,
pub fn isDirectory(this: @This()) bool {
return this == .dir;
}
pub fn have(this: @This()) bool {
return switch (this) {
.file => |opt_file| opt_file != null,
.dir => |opt_dir| opt_dir != null,
};
}
};
pub const AddInputPathOptions = struct {
/// 若提供此句柄,调用 `check` 时将关闭它,除非同时设置了 `request_handle`。
handle: PathHandle = .{ .file = null },
stat: ?Stat = null,
/// 若设置此项,则调用 `check` 后文件句柄仍保持打开。
request_handle: bool = false,
/// 可根据 `handle` 请求文件或目录内容。
request_contents: bool = false,
/// 跳过内容哈希;元数据中的任何差异
/// 均意味着缓存未命中。
metadata_only: bool = false,
};
/// 将文件或目录路径添加为被缓存进程的依赖。
/// 调用 `hit` 时会检查内容,确保它与此前的内容匹配。
///
/// 可以请求输入文件内容,随后通过返回的 `InputPath.Index` 的方法获取,但须先调用 `hit`。
///
/// 目录内容视为按顺序排列的直属条目文件名列表,以空字节分隔。每个文件名前都有一个 `Io.File.Kind` 字节,其值加 1,避免零标签与条目分隔符混淆。
///
/// 另见:
/// * `addDiscoveredPath`
///
///
///
///
///
///
pub fn addInputPath(m: *Manifest, path: Path, options: AddInputPathOptions) Allocator.Error!InputPath.Index {
assert(m.state == .input);
const cache = m.cache;
const gpa = cache.gpa;
const is_directory = options.handle.isDirectory();
try m.files.ensureUnusedCapacityContext(gpa, 1, .{ .contents = m.contents.items });
try m.input_paths.ensureUnusedCapacity(gpa, 1);
const new_file_offset: File.Offset = @fromBackingInt(@intCast(m.contents.items.len));
try m.contents.appendNTimes(gpa, 0, @offsetOf(File, "path_start"));
errdefer m.contents.shrinkRetainingCapacity(@backingInt(new_file_offset));
const new_prefix = try cache.resolveAppendPath(&m.contents, path);
assert(mem.isAligned(m.contents.items.len, @alignOf(File)));
new_file_offset.get(m.contents.items).flags = .{
.prefix = new_prefix,
.is_directory = is_directory,
.metadata_only = options.metadata_only,
};
const gop = m.files.getOrPutAssumeCapacityContext(new_file_offset, .{ .contents = m.contents.items });
m.files.lockPointers();
defer m.files.unlockPointers();
if (gop.found_existing) {
m.contents.shrinkRetainingCapacity(@backingInt(new_file_offset));
const existing_input_file = &m.input_paths.items[gop.index];
switch (options.handle) {
.file => |opt_file| if (opt_file) |file| {
existing_input_file.handle = .{ .file = file };
existing_input_file.have_handle = true;
},
.dir => |opt_dir| if (opt_dir) |dir| {
existing_input_file.handle = .{ .dir = dir };
existing_input_file.have_handle = true;
},
}
if (options.request_contents) switch (existing_input_file.contents.unwrap()) {
.requested, .unrequested => existing_input_file.contents = .requested,
.populated => {},
};
const existing_header = m.files.keys()[gop.index].get(m.contents.items);
if (options.stat) |stat| {
existing_input_file.have_stat = true;
existing_header.size = stat.size;
existing_header.inode = stat.inode;
existing_header.mtime = @intCast(stat.mtime.toNanoseconds());
}
// 若触发,则表示同一文件路径既以目录又以普通文件形式添加到缓存清单,使预期缓存行为存在歧义。
//
//
assert(existing_header.flags.is_directory == is_directory);
if (!options.metadata_only)
existing_header.flags.metadata_only = false;
} else {
m.input_paths.appendAssumeCapacity(.{
.request_handle = options.request_handle,
.have_handle = options.handle.have(),
.handle = switch (options.handle) {
.file => |opt_file| if (opt_file) |file| .{ .file = file } else undefined,
.dir => |opt_dir| if (opt_dir) |dir| .{ .dir = dir } else undefined,
},
.contents = if (options.request_contents) .requested else .unrequested,
.have_digest = false,
.have_stat = options.stat != null,
});
assert(m.input_paths.items.len - 1 == gop.index);
if (options.stat) |stat| {
const header = new_file_offset.get(m.contents.items);
header.size = stat.size;
header.inode = stat.inode;
header.mtime = @intCast(stat.mtime.toNanoseconds());
}
}
return @fromBackingInt(@intCast(gop.index));
}
pub fn addInputPathOptional(m: *Manifest, opt_path: ?Path, options: AddInputPathOptions) Allocator.Error!void {
assert(m.state == .input);
m.hash.add(opt_path != null);
_ = try addInputPath(m, opt_path orelse return, options);
}
pub const AddInputDepFileError = error{
InvalidDepFile,
} || Allocator.Error || Io.File.OpenError || Io.File.Reader.Error;
pub fn addInputDepFile(m: *Manifest, path: Path, diagnostic: ?*DepTokenizer.Token) AddInputDepFileError!void {
assert(m.manifest_file == null);
assert(m.state == .input);
const cache = m.cache;
const gpa = cache.gpa;
const io = cache.io;
// TODO: 将 DepTokenizer 改为流式处理,而不是处理字节切片。
const prev_len = m.all_input_content.items.len;
defer m.all_input_content.items.len = prev_len;
const file = try path.root_dir.handle.openFile(io, path.sub_path, .{});
defer file.close(io);
var file_reader: Io.File.Reader = .init(file, io, &.{});
file_reader.interface.appendRemainingUnlimited(gpa, &m.all_input_content) catch |err| switch (err) {
error.OutOfMemory => |e| return e,
error.ReadFailed => return file_reader.err.?,
};
var aux: std.ArrayList(u8) = .empty;
defer aux.deinit(gpa);
var it: DepTokenizer = .{ .bytes = m.all_input_content.items[prev_len..] };
while (it.next()) |token| switch (token) {
.target, .target_must_resolve => {},
.prereq => |file_path| {
_ = try m.addInputPath(.initCwd(file_path), .{});
},
.prereq_must_resolve => {
aux.clearRetainingCapacity();
try token.resolve(gpa, &aux);
_ = try m.addInputPath(.initCwd(aux.items), .{});
},
else => |err| {
if (diagnostic) |d| d.* = err;
return error.InvalidDepFile;
},
};
}
pub const CheckResult = union(enum) {
hit,
incomplete_manifest,
invalid_manifest,
path_deleted: File.Offset,
directory_status_changed: File.Offset,
metadata_changed: File.Offset,
contents_changed: File.Offset,
pub const Format = struct {
check_result: CheckResult,
manifest: *const Manifest,
pub fn format(this: @This(), w: *Io.Writer) Io.Writer.Error!void {
switch (this.check_result) {
.hit, .incomplete_manifest, .invalid_manifest => return w.writeAll(@tagName(this.check_result)),
.path_deleted, .directory_status_changed, .metadata_changed, .contents_changed => |off| {
const path = off.path(this.manifest.contents.items);
return w.print("{t} {s}", .{ this.check_result, path });
},
}
}
};
pub fn fmt(check_result: CheckResult, manifest: *const Manifest) Format {
return .{
.check_result = check_result,
.manifest = manifest,
};
}
};
pub const CheckError = error{
/// 无法检查缓存,
/// 原因已记录到 `diagnostic` 字段。
CacheCheckFailed,
} || Allocator.Error || Io.Cancelable;
/// 检查缓存中是否存在该输入。
/// 可调用 `final` 获取其哈希的十六进制编码。
///
/// 此函数还会获取清单文件的排他锁。因此,持有 Manifest 的进程会阻塞任何其他尝试获取该锁的进程。若 `want_shared_lock` 为 `true`,则缓存命中保证清单文件以共享模式锁定,缓存未命中保证以排他模式锁定。
///
/// 调用 `deinit` 时释放清单文件锁。也可调用 `toOwnedLock`,取得能表示该锁的较小对象。调用 `deinit` 始终安全,无论此前是否调用过 `toOwnedLock`。
///
///
///
///
///
///
pub fn check(
man: *Manifest,
diag: *CheckDiagnostic,
parent_progress_node: std.Progress.Node,
) CheckError!CheckResult {
const node = parent_progress_node.start("Reusing Cache Artifacts", 0);
defer node.end();
return checkProgressless(man, diag);
}
pub fn checkProgressless(man: *Manifest, diag: *CheckDiagnostic) CheckError!CheckResult {
assert(man.state == .input);
assert(man.manifest_file == null);
// 这里*不*对输入文件的内容进行哈希。
// 仅对标志(包括前缀)及路径进行哈希。
for (man.files.keys()[0..man.input_paths.items.len]) |file_off| {
const flags_and_path = file_off.flagsAndPath(man.contents.items);
man.hash.hasher.update(mem.absorbSentinel(flags_and_path));
}
var input_digest: BinDigest = undefined;
man.hash.hasher.final(&input_digest);
const input_hex_digest = binToHex(input_digest);
const manifest_file_path = &input_hex_digest;
const io = man.cache.io;
// 先尝试以独占锁打开缓存,但若此操作会阻塞,
// 且设置了 `want_shared_lock`,则共享锁可能已经足够,
// 因此改用共享锁打开。
while (true) {
if (man.cache.manifest_dir.createFile(io, manifest_file_path, .{
.read = true,
.truncate = false,
.lock = .exclusive,
.lock_nonblocking = man.want_shared_lock,
})) |manifest_file| {
man.manifest_file = manifest_file;
man.have_exclusive_lock = true;
break;
} else |err| switch (err) {
error.WouldBlock => {
man.manifest_file = man.cache.manifest_dir.openFile(io, manifest_file_path, .{
.mode = .read_write,
.lock = .shared,
}) catch |e| return fail(diag, .{ .manifest_create = e });
break;
},
error.FileNotFound => {
// 没有目录分量,因此唯一可能的情况
// 应是句柄对应的目录已被
// 删除。不过,在 macOS 上我们观察到两个进程
// 竞态执行带 O_CREAT 的 openat(),结果返回 ENOENT。
//
// 作为变通方案,以 exclusive=true 重试,
// 通过返回值消除歧义:EEXIST 表示原先
// 失败是竞态导致;ENOENT 表示打开句柄
// 所指的目录已被删除。
if (!builtin.os.tag.isDarwin()) return fail(diag, .{ .manifest_create = error.FileNotFound });
if (man.cache.manifest_dir.createFile(io, manifest_file_path, .{
.read = true,
.truncate = false,
.lock = .exclusive,
.lock_nonblocking = man.want_shared_lock,
.exclusive = true,
})) |manifest_file| {
man.manifest_file = manifest_file;
man.have_exclusive_lock = true;
break;
} else |excl_err| switch (excl_err) {
error.WouldBlock, error.PathAlreadyExists => continue,
error.FileNotFound => return fail(diag, .{ .manifest_create = error.FileNotFound }),
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .manifest_create = e }),
}
},
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .manifest_create = e }),
}
}
man.want_refresh_timestamp = true;
// 接下来构造第二个哈希。其输入首先是已经计算出的摘要(`input_digest`),然后是每个输入文件的摘要,包括发现的文件(参见 `addDiscoveredPath`)。若缓存命中,则从磁盘清单中得知已发现文件集合;若未命中,则通过后续调用 `addDiscoveredPath` 等函数得知这些文件。因此,此函数执行后 `man.hash.hasher` 的状态取决于是否命中缓存。
//
// 若返回 `CacheStatus.hit`,则 `man.hash.hasher` 必须已包含所有已发现文件的摘要,以便调用者调用 `final`。否则,即缓存未命中时,`man.hash.hasher` 将包含所有非发现文件的摘要,也就是此前已告知的文件。其余文件通过调用 `addDiscoveredPath` 等函数发现,同时更新哈希器。添加完所有文件后,用户可以调用 `final`,并在适当时机调用 `finalize` 将文件列表写入磁盘。
//
//
//
//
//
//
//
//
man.hash.hasher = hasher_init;
man.hash.hasher.update(&input_digest);
hit: {
const miss_result = miss: {
const result = try man.checkLocked(diag);
if (result == .hit) {
break :hit;
} else if (!try man.upgradeToExclusiveLock(diag)) {
break :miss result;
}
// 持有共享锁时未命中,随后升级为独占锁。但其他进程可能已
// 修改缓存目录,因此在判定未命中之前需要再次检查。
man.shrinkFilesToInput();
const refreshed_result = try man.checkLocked(diag);
if (refreshed_result == .hit) break :hit;
break :miss refreshed_result;
};
// 缓存未命中,但 `checkLocked` 保证即便未命中,也已计算所有输入文件的摘要;
// 因为后续清单摘要需要使用这些摘要。
man.state = .miss;
return miss_result;
}
if (man.want_shared_lock) {
man.downgradeToSharedLock() catch |err| return fail(diag, .{ .manifest_lock = err });
}
man.state = .hit;
return .hit;
}
fn transitionToMissDiscovered(m: *Manifest) void {
switch (m.state) {
.input => unreachable,
.hit => unreachable,
.hit_digested => unreachable,
.miss => {
m.shrinkFilesToInput();
m.state = .miss_discovered;
},
.miss_discovered => {},
.miss_digested => unreachable,
.miss_finalized => unreachable,
}
}
fn shrinkFilesToInput(m: *Manifest) void {
if (m.files.count() <= m.input_paths.items.len) return;
// 从文件哈希映射读取数据,而其数据将在下一行被销毁。
const off = m.files.keys()[m.input_paths.items.len];
// 从尚未缩减的内容中读取;其数据将在下一行被破坏。
m.files.shrinkRetainingCapacityContext(m.input_paths.items.len, .{ .contents = m.contents.items });
m.contents.shrinkRetainingCapacity(@backingInt(off));
assert(mem.isAligned(m.contents.items.len, @alignOf(File)));
}
/// 不读取或修改 `self.hash.hasher`。断言 `self.files` 仅包含原始输入文件。
fn checkLocked(m: *Manifest, diag: *CheckDiagnostic) CheckError!CheckResult {
assert(m.files.count() == m.input_paths.items.len);
const gpa = m.cache.gpa;
const io = m.cache.io;
const manifest_file = m.manifest_file.?;
const manifest_stat = manifest_file.stat(io) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .manifest_stat = e }),
};
const manifest_size = std.math.cast(u32, manifest_stat.size) orelse
return fail(diag, .manifest_oversize);
if (manifest_size == 0 or manifest_size < m.contents.items.len) {
// 清单文件从未完成写入。
try m.contents.ensureUnusedCapacity(gpa, 1);
return populateMissingInputFileHashes(m, diag, 0, .incomplete_manifest);
}
// 不得覆盖现有的 `Manifest.contents`,因为其中可能预先填充了文件状态与摘要信息,必须将这些信息与文件系统比较。非输入文件通常比输入文件多,因此这里先移动现有内容,为磁盘上完整清单内容腾出空间,再截断内容数组。
//
// 磁盘文件按约定已经包含必须保留的额外空字节。
//
//
//
const input_contents_len = m.contents.items.len;
// 此次调整大小后,每个 return 语句都需要修改 m.contents 的长度。
try m.contents.resize(gpa, input_contents_len + manifest_size);
errdefer m.contents.shrinkRetainingCapacity(input_contents_len);
@memcpy(m.contents.items[manifest_size..][0..input_contents_len], m.contents.items[0..input_contents_len]);
{
const n = manifest_file.readPositionalAll(io, m.contents.items, 0) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .manifest_read = e }),
};
if (n != manifest_size) return missInput(m, diag, 0, input_contents_len, manifest_size, .incomplete_manifest);
}
const disk_contents = m.contents.items[0..manifest_size];
const input_contents = m.contents.items[manifest_size..][0..input_contents_len];
// 首先是输入文件段;它必须与我们的输入文件匹配,否则即为无效或不完整。
var off: usize = 0;
for (m.input_paths.items, m.files.keys()[0..m.input_paths.items.len], 0..) |*input_path, file_off, i| {
if (@backingInt(file_off) + 1 >= disk_contents.len)
return missInput(m, diag, i, input_contents_len, manifest_size, .incomplete_manifest);
if (!mem.eql(u8, file_off.flagsAndPath(disk_contents), file_off.flagsAndPath(input_contents)))
return missInput(m, diag, i, input_contents_len, manifest_size, .invalid_manifest);
const result = try checkInputPath(m, diag, file_off, input_path, disk_contents, input_contents);
if (result != .hit) return missInput(m, diag, i + 1, input_contents_len, manifest_size, result);
off = @backingInt(file_off);
}
// 根据清单内容长度估计文件数,以减少分配。
// 这不是上界;后续插入仍可能分配内存。
try m.files.ensureUnusedCapacityContext(gpa, disk_contents.len / (@sizeOf(File) + 32), .{
.contents = disk_contents,
});
// 验证并检查发现的文件。
while (off + 1 < disk_contents.len) {
const file_off: File.Offset = @fromBackingInt(@intCast(off));
const file = file_off.getFallible(disk_contents) catch return .invalid_manifest;
if (file.flags.prefix >= m.cache.prefixes_len) return .invalid_manifest;
const path = file_off.pathFallible(disk_contents) catch return .invalid_manifest;
if (path.len == 0) return .invalid_manifest;
try m.files.putContext(gpa, file_off, {}, .{ .contents = disk_contents });
const result = try checkDiscoveredPath(m, diag, file_off, disk_contents);
if (result != .hit) return result;
off += File.sizeOf(path.len);
}
// 末尾的终止零字节,用于区分空清单文件与
// 包含零个文件的清单。
const file_valid = off + 1 == disk_contents.len and disk_contents[off] == 0;
if (!file_valid) return .incomplete_manifest;
// 由于缓存命中,接受磁盘上的输入文件内容,并丢弃另一个副本。
// 此外,不在内容中跟踪末尾的零字节。
m.contents.shrinkRetainingCapacity(manifest_size - 1);
return .hit;
}
/// 恢复输入文件内容,为缓存未命中的流程做准备。
/// 保留 `off` 之前的全部内容,避免重复计算摘要和文件状态。
///
/// 此外,此函数负责填充未命中文件之后其余输入文件的摘要与元数据。
///
fn missInput(
m: *Manifest,
diag: *CheckDiagnostic,
next_file_index: usize,
input_contents_len: usize,
manifest_size: usize,
result: CheckResult,
) CheckError!CheckResult {
const file_offs = m.files.keys();
const off = if (file_offs.len - next_file_index == 0)
input_contents_len
else
@backingInt(file_offs[next_file_index]);
const copy_len = input_contents_len - off;
if (manifest_size > 0) @memcpy(
m.contents.items[off..][0..copy_len],
m.contents.items[manifest_size + off ..][0..copy_len],
);
m.contents.shrinkRetainingCapacity(input_contents_len);
return populateMissingInputFileHashes(m, diag, next_file_index, result);
}
fn populateMissingInputFileHashes(
m: *Manifest,
diag: *CheckDiagnostic,
next_file_index: usize,
result: CheckResult,
) CheckError!CheckResult {
const file_offs = m.files.keys();
const contents = m.contents.items;
for (file_offs[next_file_index..], m.input_paths.items[next_file_index..]) |input_file_off, *input_path| {
try populateInputPath(m, diag, input_file_off, input_path, contents);
}
return result;
}
/// 类似 `checkInputPath` 和 `checkDiscoveredPath`,但不与文件系统比较元数据或摘要。
/// 仅确保元数据与摘要可用。
fn populateInputPath(
m: *Manifest,
diag: *CheckDiagnostic,
file_off: File.Offset,
input_path: *InputPath,
contents: []u8,
) CheckError!void {
const cache = m.cache;
const io = cache.io;
const input_file = file_off.get(contents);
const parent_dir = cache.prefixes()[input_file.flags.prefix].handle;
const file_path = file_off.pathOrDot(contents);
const gpa = cache.gpa;
if (input_path.have_digest) return;
const stat_path_ok = switch (input_path.contents.unwrap()) {
.populated => true,
.unrequested, .requested => input_file.flags.metadata_only,
};
if (!input_path.have_stat and stat_path_ok) {
// 由于这是输入文件,FileNotFound 属于失败,而非缓存未命中。
const actual_stat = switch (input_path.getHandle(input_file)) {
.none => parent_dir.statFile(io, file_path, .{}) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_stat = .{
.file_offset = file_off,
.err = e,
} }),
},
.file => |opened_file| opened_file.stat(io) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_stat = .{
.file_offset = file_off,
.err = e,
} }),
},
.dir => |opened_dir| opened_dir.stat(io) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_stat = .{
.file_offset = file_off,
.err = e,
} }),
},
};
const actual_is_directory = actual_stat.kind == .directory;
if (actual_is_directory != input_file.flags.is_directory) {
// 由于这是输入文件,这属于失败,而非缓存未命中。
return fail(diag, .{ .file_stat = .{
.file_offset = file_off,
.err = if (actual_is_directory) error.IsDir else error.NotDir,
} });
}
try input_file.setStat(m, .init(actual_stat));
}
if (input_file.flags.metadata_only) {
assert(stat_path_ok);
input_file.hashFromMetadata();
return;
}
if (input_path.contents.get(m.all_input_content.items)) |file_or_dir_contents| {
assert(stat_path_ok);
var hasher = hasher_init;
hasher.update(file_or_dir_contents);
hasher.final(&input_file.digest);
return;
}
if (input_file.flags.is_directory) {
const opened_dir = if (input_path.have_handle)
input_path.handle.dir
else
parent_dir.openDir(io, file_path, .{
.iterate = true,
.access_sub_paths = false,
}) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_open = .{
.file_offset = file_off,
.err = e,
} }),
};
defer if (!input_path.request_handle) opened_dir.close(io) else {
input_path.handle = .{ .dir = opened_dir };
input_path.have_handle = true;
};
if (!input_path.have_stat) {
assert(!stat_path_ok);
const actual_stat = opened_dir.stat(io) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_stat = .{
.file_offset = file_off,
.err = e,
} }),
};
try input_file.setStat(m, .init(actual_stat));
}
const dir_contents_start = m.all_input_content.items.len;
hashDir(gpa, io, opened_dir, &input_file.digest, &m.all_input_content) catch |err| switch (err) {
error.Canceled, error.OutOfMemory => |e| return e,
else => |e| return fail(diag, .{ .file_read = .{
.file_offset = file_off,
.err = e,
} }),
};
defer switch (input_path.contents.unwrap()) {
.requested => input_path.contents = .populated(.{
.off = @intCast(dir_contents_start),
.len = @intCast(m.all_input_content.items.len - dir_contents_start),
}),
.unrequested => m.all_input_content.shrinkRetainingCapacity(dir_contents_start),
.populated => unreachable,
};
} else {
const opened_file = if (input_path.have_handle)
input_path.handle.file
else
parent_dir.openFile(io, file_path, .{ .mode = .read_only }) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_open = .{
.file_offset = file_off,
.err = e,
} }),
};
defer if (!input_path.request_handle) opened_file.close(io) else {
input_path.handle = .{ .file = opened_file };
input_path.have_handle = true;
};
if (!input_path.have_stat) {
assert(!stat_path_ok);
const actual_stat = opened_file.stat(io) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_stat = .{
.file_offset = file_off,
.err = e,
} }),
};
try input_file.setStat(m, .init(actual_stat));
}
switch (input_path.contents.unwrap()) {
.requested => {
const start = m.all_input_content.items.len;
hashFileAppend(io, opened_file, &input_file.digest, &m.all_input_content, gpa) catch |err| switch (err) {
error.Canceled, error.OutOfMemory => |e| return e,
else => |e| return fail(diag, .{ .file_read = .{
.file_offset = file_off,
.err = e,
} }),
};
input_path.contents = .populated(.{
.off = @intCast(start),
.len = @intCast(m.all_input_content.items.len - start),
});
},
.unrequested => hashFile(io, opened_file, &input_file.digest) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_read = .{
.file_offset = file_off,
.err = e,
} }),
},
.populated => unreachable,
}
}
}
/// 返回时,无论命中还是未命中,都会填充 disk_contents 摘要及 stat。
fn checkInputPath(
m: *Manifest,
diag: *CheckDiagnostic,
file_off: File.Offset,
input_path: *InputPath,
disk_contents: []u8,
input_contents: []u8,
) CheckError!CheckResult {
const cache = m.cache;
const io = cache.io;
const gpa = cache.gpa;
const disk_file = file_off.get(disk_contents);
const input_file = file_off.get(input_contents);
const parent_dir = cache.prefixes()[disk_file.flags.prefix].handle;
const file_path = file_off.pathOrDot(disk_contents);
assert(disk_file.flags == input_file.flags);
if (input_path.have_digest) {
if (mem.eql(u8, &disk_file.digest, &input_file.digest))
return .hit;
}
if (input_path.have_stat) {
const changed = try disk_file.setStatChanged(m, input_file.stat());
if (!changed) return .hit;
}
if (disk_file.flags.metadata_only) {
if (!input_path.have_stat) {
// 由于这是输入文件,FileNotFound 属于失败,而非缓存未命中。
const actual_stat = switch (input_path.getHandle(input_file)) {
.none => parent_dir.statFile(io, file_path, .{}) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_stat = .{
.file_offset = file_off,
.err = e,
} }),
},
.file => |opened_file| opened_file.stat(io) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_stat = .{
.file_offset = file_off,
.err = e,
} }),
},
.dir => |opened_dir| opened_dir.stat(io) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_stat = .{
.file_offset = file_off,
.err = e,
} }),
},
};
// 另一种情况(have_stat=true)中,此检查是冗余的,
// 因为已经断言包含该前缀的标志完全相同。
const actual_is_directory = actual_stat.kind == .directory;
if (actual_is_directory != disk_file.flags.is_directory) {
// 由于这是输入文件,这属于失败,而非缓存未命中。
return fail(diag, .{ .file_stat = .{
.file_offset = file_off,
.err = if (actual_is_directory) error.IsDir else error.NotDir,
} });
}
const stat: Stat = .init(actual_stat);
const changed = try disk_file.setStatChanged(m, stat);
disk_file.hashFromMetadata();
if (!changed) return .hit;
}
return .{ .metadata_changed = file_off };
}
if (input_path.contents.get(m.all_input_content.items)) |file_or_dir_contents| {
var hasher = hasher_init;
hasher.update(file_or_dir_contents);
hasher.final(&disk_file.digest);
if (mem.eql(u8, &disk_file.digest, &input_file.digest)) return .hit;
return .{ .contents_changed = file_off };
}
if (disk_file.flags.is_directory) {
const opened_dir = if (input_path.have_handle)
input_path.handle.dir
else
parent_dir.openDir(io, file_path, .{
.iterate = true,
.access_sub_paths = false,
}) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_open = .{
.file_offset = file_off,
.err = e,
} }),
};
defer if (!input_path.request_handle) opened_dir.close(io) else {
input_path.handle = .{ .dir = opened_dir };
input_path.have_handle = true;
};
if (!input_path.have_stat) {
const actual_stat = opened_dir.stat(io) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_stat = .{
.file_offset = file_off,
.err = e,
} }),
};
if (!try disk_file.setStatChanged(m, .init(actual_stat))) return .hit;
}
const dir_contents_start = m.all_input_content.items.len;
hashDir(gpa, io, opened_dir, &disk_file.digest, &m.all_input_content) catch |err| switch (err) {
error.Canceled, error.OutOfMemory => |e| return e,
else => |e| return fail(diag, .{ .file_read = .{
.file_offset = file_off,
.err = e,
} }),
};
defer switch (input_path.contents.unwrap()) {
.requested => input_path.contents = .populated(.{
.off = @intCast(dir_contents_start),
.len = @intCast(m.all_input_content.items.len - dir_contents_start),
}),
.unrequested => m.all_input_content.shrinkRetainingCapacity(dir_contents_start),
.populated => unreachable,
};
if (mem.eql(u8, &disk_file.digest, &input_file.digest)) return .hit;
return .{ .contents_changed = file_off };
} else {
const opened_file = if (input_path.have_handle)
input_path.handle.file
else
parent_dir.openFile(io, file_path, .{ .mode = .read_only }) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_open = .{
.file_offset = file_off,
.err = e,
} }),
};
defer if (!input_path.request_handle) opened_file.close(io) else {
input_path.handle = .{ .file = opened_file };
input_path.have_handle = true;
};
if (!input_path.have_stat) {
const actual_stat = opened_file.stat(io) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_stat = .{
.file_offset = file_off,
.err = e,
} }),
};
if (!try disk_file.setStatChanged(m, .init(actual_stat))) return .hit;
}
switch (input_path.contents.unwrap()) {
.requested => {
const start = m.all_input_content.items.len;
hashFileAppend(io, opened_file, &disk_file.digest, &m.all_input_content, gpa) catch |err| switch (err) {
error.Canceled, error.OutOfMemory => |e| return e,
else => |e| return fail(diag, .{ .file_read = .{
.file_offset = file_off,
.err = e,
} }),
};
input_path.contents = .populated(.{
.off = @intCast(start),
.len = @intCast(m.all_input_content.items.len - start),
});
},
.unrequested => hashFile(io, opened_file, &disk_file.digest) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_read = .{
.file_offset = file_off,
.err = e,
} }),
},
.populated => unreachable,
}
if (mem.eql(u8, &disk_file.digest, &input_file.digest)) return .hit;
return .{ .contents_changed = file_off };
}
}
fn checkDiscoveredPath(
m: *Manifest,
diag: *CheckDiagnostic,
file_off: File.Offset,
contents: []u8,
) CheckError!CheckResult {
const file = file_off.get(contents);
const cache = m.cache;
const gpa = cache.gpa;
const io = cache.io;
const parent_dir = cache.prefixes()[file.flags.prefix].handle;
const file_path = file_off.pathOrDot(contents);
if (file.flags.metadata_only) {
const actual_stat = parent_dir.statFile(io, file_path, .{}) catch |err| switch (err) {
error.FileNotFound => return .{ .path_deleted = file_off },
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_stat = .{
.file_offset = file_off,
.err = e,
} }),
};
const actual_is_directory = actual_stat.kind == .directory;
if (actual_is_directory != file.flags.is_directory) return .{ .directory_status_changed = file_off };
const changed = try file.setStatChanged(m, .init(actual_stat));
file.hashFromMetadata();
if (changed) return .{ .metadata_changed = file_off };
return .hit;
}
if (file.flags.is_directory) {
const opened_dir = parent_dir.openDir(io, file_path, .{
.iterate = true,
.access_sub_paths = false,
}) catch |err| switch (err) {
error.FileNotFound => return .{ .path_deleted = file_off },
error.NotDir => return .{ .directory_status_changed = file_off },
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_open = .{
.file_offset = file_off,
.err = e,
} }),
};
defer opened_dir.close(io);
const actual_stat = opened_dir.stat(io) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_stat = .{
.file_offset = file_off,
.err = e,
} }),
};
if (try file.setStatChanged(m, .init(actual_stat))) {
const prev_digest: BinDigest = file.digest;
const dir_contents_start = m.all_input_content.items.len;
defer m.all_input_content.shrinkRetainingCapacity(dir_contents_start);
hashDir(gpa, io, opened_dir, &file.digest, &m.all_input_content) catch |err| switch (err) {
error.Canceled, error.OutOfMemory => |e| return e,
else => |e| return fail(diag, .{ .file_read = .{
.file_offset = file_off,
.err = e,
} }),
};
if (!mem.eql(u8, &file.digest, &prev_digest)) return .{ .contents_changed = file_off };
}
return .hit;
}
const opened_file = parent_dir.openFile(io, file_path, .{ .mode = .read_only }) catch |err| switch (err) {
error.FileNotFound => return .{ .path_deleted = file_off },
error.IsDir => return .{ .directory_status_changed = file_off },
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_open = .{
.file_offset = file_off,
.err = e,
} }),
};
defer opened_file.close(io);
const actual_stat = opened_file.stat(io) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_stat = .{
.file_offset = file_off,
.err = e,
} }),
};
if (try file.setStatChanged(m, .init(actual_stat))) {
const prev_digest: BinDigest = file.digest;
hashFile(io, opened_file, &file.digest) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| return fail(diag, .{ .file_read = .{
.file_offset = file_off,
.err = e,
} }),
};
if (!mem.eql(u8, &file.digest, &prev_digest)) return .{ .contents_changed = file_off };
}
return .hit;
}
fn fail(ptr: *CheckDiagnostic, d: CheckDiagnostic) error{CacheCheckFailed} {
ptr.* = d;
return error.CacheCheckFailed;
}
fn isProblematicTimestamp(man: *Manifest, timestamp: Io.Timestamp) error{Canceled}!bool {
const io = man.cache.io;
// 若 file_time 早于最近的问题时间戳,
// 则无需访问文件系统。
if (timestamp.nanoseconds < man.recent_problematic_timestamp.nanoseconds)
return false;
// 接下来检查全局共享的 Cache 时间戳,
// 多个线程都会访问它。
try man.cache.mutex.lock(io);
defer man.cache.mutex.unlock(io);
// 将全局值保存到局部值,以避免下次加锁。
man.recent_problematic_timestamp = man.cache.recent_problematic_timestamp;
if (timestamp.nanoseconds < man.recent_problematic_timestamp.nanoseconds)
return false;
// 此标志防止同一次 hit() 调用多次写入文件系统。
if (man.want_refresh_timestamp) {
man.want_refresh_timestamp = false;
var file = man.cache.manifest_dir.createFile(io, "timestamp", .{
.read = true,
.truncate = true,
}) catch |err| switch (err) {
error.Canceled => |e| return e,
else => return true,
};
defer file.close(io);
// 同时在本地和全局保存(此时仍持有全局锁)。
const stat = file.stat(io) catch |err| switch (err) {
error.Canceled => |e| return e,
else => return true,
};
man.recent_problematic_timestamp = stat.mtime;
man.cache.recent_problematic_timestamp = man.recent_problematic_timestamp;
}
return timestamp.nanoseconds >= man.recent_problematic_timestamp.nanoseconds;
}
pub const AddDiscoveredPathOptions = struct {
discovered_path: DiscoveredPath,
handle: PathHandle = .{ .file = null },
stat: ?Stat = null,
/// 若它是目录,则目录内容需要特殊编码:以空字符分隔并排序的条目,每个条目前带 `File.Kind`。
///
contents: ?[]const u8 = null,
metadata_only: bool = false,
/// 仅当 `addDiscoveredPath` 返回 `error.FileSystemFailure` 时填充。
diagnostic: ?*AddDiscoveredPathDiagnostic = null,
};
pub const DiscoveredPath = union(enum) {
unresolved: Path,
prefixed: PrefixedPath,
};
pub const AddDiscoveredPathDiagnostic = union(enum) {
none,
open_file: Io.File.OpenError,
open_dir: Io.Dir.OpenError,
stat_file: Io.File.StatError,
stat_dir: Io.Dir.StatError,
read_file: Io.File.ReadPositionalError,
read_dir: Io.Dir.Reader.Error,
pub fn format(this: @This(), w: *Io.Writer) Io.Writer.Error!void {
switch (this) {
.none => return w.writeAll("none"),
else => |err, tag| return w.print("{t}: {t}", .{ tag, err }),
}
}
};
pub const AddDiscoveredPathError = error{
/// 返回此值时会填充诊断信息。
/// 如果同时提供了 contents 和 stat,则此分支不可达。
FileSystemFailure,
} || Allocator.Error || Io.Cancelable;
/// 缓存未命中后,将文件或目录添加为被缓存进程的依赖。
///
/// 另见:
/// * `addInputPath`
/// * `addDiscoveredDepFile`
/// * `addDiscoveredManifest`
pub fn addDiscoveredPath(m: *Manifest, options: AddDiscoveredPathOptions) AddDiscoveredPathError!void {
assert(m.manifest_file != null);
transitionToMissDiscovered(m);
const cache = m.cache;
const gpa = cache.gpa;
const io = cache.io;
const is_directory = options.handle == .dir;
try m.files.ensureUnusedCapacityContext(gpa, 1, .{ .contents = m.contents.items });
const new_file_offset: File.Offset = @fromBackingInt(@intCast(m.contents.items.len));
try m.contents.appendNTimes(gpa, 0, @offsetOf(File, "path_start"));
errdefer m.contents.shrinkRetainingCapacity(@backingInt(new_file_offset));
const new_prefix = switch (options.discovered_path) {
.unresolved => |unresolved| try cache.resolveAppendPath(&m.contents, unresolved),
.prefixed => |prefixed| try cache.appendPrefixedPath(&m.contents, prefixed),
};
assert(mem.isAligned(m.contents.items.len, @alignOf(File)));
new_file_offset.get(m.contents.items).flags = .{
.prefix = new_prefix,
.is_directory = is_directory,
.metadata_only = options.metadata_only,
};
const gop = m.files.getOrPutAssumeCapacityContext(new_file_offset, .{ .contents = m.contents.items });
m.files.lockPointers();
defer m.files.unlockPointers();
const file_offset = if (gop.found_existing) h: {
m.contents.shrinkRetainingCapacity(@backingInt(new_file_offset));
const existing_off = gop.key_ptr.*;
const header = existing_off.get(m.contents.items);
// 若触发,则表示同一文件路径既以目录又以普通文件形式添加到缓存清单,使预期缓存行为存在歧义。
//
//
assert(header.flags.is_directory == is_directory);
if (!options.metadata_only)
header.flags.metadata_only = false;
break :h existing_off;
} else new_file_offset;
const header = file_offset.get(m.contents.items);
if (options.stat) |stat| {
try header.setStat(m, stat);
if (header.flags.metadata_only) {
header.hashFromMetadata();
} else if (options.contents) |contents| {
var hasher = hasher_init;
hasher.update(contents);
hasher.final(&header.digest);
}
return;
}
const need_stat = options.stat == null;
const metadata_only = header.flags.metadata_only;
const prefix = header.flags.prefix;
switch (options.handle) {
.dir => |opt_handle| if (opt_handle) |handle| {
try populateDirectory(m, header, need_stat, handle, options.contents, metadata_only, options.diagnostic);
} else {
const dir = cache.prefixes()[prefix].handle;
const sub_path = file_offset.path(m.contents.items);
const handle = dir.openDir(io, sub_path, .{
.access_sub_paths = false,
.iterate = true,
}) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| {
if (options.diagnostic) |d| d.* = .{ .open_dir = e };
return error.FileSystemFailure;
},
};
defer handle.close(io);
try populateDirectory(m, header, need_stat, handle, options.contents, metadata_only, options.diagnostic);
},
.file => |opt_handle| if (opt_handle) |handle| {
try populateFile(m, header, need_stat, handle, options.contents, metadata_only, options.diagnostic);
} else {
const dir = cache.prefixes()[prefix].handle;
const sub_path = file_offset.path(m.contents.items);
const handle = dir.openFile(io, sub_path, .{ .mode = .read_only }) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| {
if (options.diagnostic) |d| d.* = .{ .open_file = e };
return error.FileSystemFailure;
},
};
defer handle.close(io);
try populateFile(m, header, need_stat, handle, options.contents, metadata_only, options.diagnostic);
},
}
}
pub const AddDiscoveredDepFileError = error{
InvalidDepFile,
} || AddDiscoveredPathError || Io.File.OpenError || Io.File.Reader.Error;
pub const AddDiscoveredDepFileDiagnostic = union(enum) {
add_discovered_path: AddDiscoveredPathDiagnostic,
dep_tokenizer: DepTokenizer.Token,
};
/// 缓存未命中后,将 GNU make 风格的依赖文件添加为被缓存进程的依赖。
///
/// 另见:
/// * `addDiscoveredPath
/// * `addDiscoveredManifest`
pub fn addDiscoveredDepFile(
m: *Manifest,
path: Path,
diagnostic: ?*AddDiscoveredDepFileDiagnostic,
) AddDiscoveredDepFileError!void {
assert(m.manifest_file != null);
transitionToMissDiscovered(m);
const cache = m.cache;
const gpa = cache.gpa;
const io = cache.io;
// TODO: 将 DepTokenizer 改为流式处理,而不是处理字节切片。
const prev_len = m.all_input_content.items.len;
defer m.all_input_content.items.len = prev_len;
const file = try path.root_dir.handle.openFile(io, path.sub_path, .{});
defer file.close(io);
var file_reader: Io.File.Reader = .init(file, io, &.{});
file_reader.interface.appendRemainingUnlimited(gpa, &m.all_input_content) catch |err| switch (err) {
error.OutOfMemory => |e| return e,
error.ReadFailed => return file_reader.err.?,
};
var aux: std.ArrayList(u8) = .empty;
defer aux.deinit(gpa);
var it: DepTokenizer = .{ .bytes = m.all_input_content.items[prev_len..] };
while (it.next()) |token| switch (token) {
.target, .target_must_resolve => {},
.prereq => |p| try m.addDiscoveredPath(.{ .discovered_path = .{ .unresolved = .initCwd(p) } }),
.prereq_must_resolve => {
aux.clearRetainingCapacity();
try token.resolve(gpa, &aux);
try m.addDiscoveredPath(.{ .discovered_path = .{ .unresolved = .initCwd(aux.items) } });
},
else => |err| {
if (diagnostic) |d| d.* = .{ .dep_tokenizer = err };
return error.InvalidDepFile;
},
};
}
fn populateFile(
m: *Manifest,
file: *File,
need_stat: bool,
handle: Io.File,
contents: ?[]const u8,
metadata_only: bool,
diagnostic: ?*AddDiscoveredPathDiagnostic,
) AddDiscoveredPathError!void {
const io = m.cache.io;
if (need_stat) {
const stat = handle.stat(io) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| {
if (diagnostic) |d| d.* = .{ .stat_file = e };
return error.FileSystemFailure;
},
};
try file.setStat(m, .init(stat));
}
if (metadata_only) {
file.hashFromMetadata();
return;
}
if (contents) |bytes| {
var hasher = hasher_init;
hasher.update(bytes);
hasher.final(&file.digest);
} else {
hashFile(io, handle, &file.digest) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| {
if (diagnostic) |d| d.* = .{ .read_file = e };
return error.FileSystemFailure;
},
};
}
}
fn populateDirectory(
m: *Manifest,
file: *File,
need_stat: bool,
handle: Io.Dir,
contents: ?[]const u8,
metadata_only: bool,
diagnostic: ?*AddDiscoveredPathDiagnostic,
) AddDiscoveredPathError!void {
const cache = m.cache;
const io = cache.io;
const gpa = cache.gpa;
if (need_stat) {
const stat = handle.stat(io) catch |err| switch (err) {
error.Canceled => |e| return e,
else => |e| {
if (diagnostic) |d| d.* = .{ .stat_dir = e };
return error.FileSystemFailure;
},
};
try file.setStat(m, .init(stat));
}
if (metadata_only) {
file.hashFromMetadata();
return;
}
if (contents) |bytes| {
var hasher = hasher_init;
hasher.update(bytes);
hasher.final(&file.digest);
} else {
const prev_contents_len = m.all_input_content.items.len;
defer m.all_input_content.shrinkRetainingCapacity(prev_contents_len);
hashDir(gpa, io, handle, &file.digest, &m.all_input_content) catch |err| switch (err) {
error.OutOfMemory, error.Canceled => |e| return e,
else => |e| {
if (diagnostic) |d| d.* = .{ .read_dir = e };
return error.FileSystemFailure;
},
};
}
}
/// 另请参阅 `hitDigestHex`。
pub fn hitDigest(m: *Manifest) BinDigest {
assert(m.manifest_file != null);
assert(m.state == .hit);
m.state = .hit_digested;
return finalDigest(m);
}
pub fn hitDigestHex(m: *Manifest) HexDigest {
return binToHex(m.hitDigest());
}
/// 另见 `missDigestHex`。
pub fn missDigest(m: *Manifest) BinDigest {
assert(m.manifest_file != null);
transitionToMissDiscovered(m);
m.state = .miss_digested;
return finalDigest(m);
}
pub fn missDigestHex(m: *Manifest) HexDigest {
return binToHex(m.missDigest());
}
fn finalDigest(m: *Manifest) BinDigest {
const contents = m.contents.items;
const hasher = &m.hash.hasher;
for (m.files.keys()) |off| {
const file = off.get(contents);
hasher.update(&file.digest);
}
// 暂不关闭清单文件,因为希望在 API 用户使用完之前始终保持锁定。
// 也暂不写出清单,因为在调用 `finalize` 前,可能仍在
// 创建待缓存的产物。
var bin_digest: BinDigest = undefined;
hasher.final(&bin_digest);
return bin_digest;
}
/// 若 `want_shared_lock` 为 true,此函数自动将
/// 独占锁降级为共享锁。
pub fn finalize(m: *Manifest) !void {
const io = m.cache.io;
const manifest_file = m.manifest_file.?;
assert(m.state == .miss_digested);
assert(m.have_exclusive_lock);
{
m.contents.appendAssumeCapacity(0);
defer _ = m.contents.pop().?;
try manifest_file.setLength(io, m.contents.items.len);
try manifest_file.writePositionalAll(io, m.contents.items, 0);
m.state = .miss_finalized;
}
if (m.want_shared_lock) {
try m.downgradeToSharedLock();
}
}
fn downgradeToSharedLock(self: *Manifest) !void {
if (!self.have_exclusive_lock) return;
const io = self.cache.io;
if (std.process.can_spawn or !builtin.single_threaded) {
const manifest_file = self.manifest_file.?;
try manifest_file.downgradeLock(io);
}
self.have_exclusive_lock = false;
}
fn upgradeToExclusiveLock(m: *Manifest, diag: *CheckDiagnostic) error{CacheCheckFailed}!bool {
if (m.have_exclusive_lock) return false;
assert(m.manifest_file != null);
const io = m.cache.io;
if (std.process.can_spawn or !builtin.single_threaded) {
const manifest_file = m.manifest_file.?;
// 此处有意留出锁已释放的一段时间,以应对其他进程持有共享锁的情况。
//
manifest_file.unlock(io);
manifest_file.lock(io, .exclusive) catch |err| return fail(diag, .{ .manifest_lock = err });
}
m.have_exclusive_lock = true;
return true;
}
/// 仅取得维持清单文件锁所需的数据。
/// 仍可安全地对 `Manifest` 执行 deinit。
///
/// 不要忘记在此之前调用 `finalize`!
pub fn toOwnedLock(self: *Manifest) Lock {
defer self.manifest_file = null;
return .{ .manifest_file = self.manifest_file.? };
}
pub const SelfContainedFiles = struct {
/// 引用 `contents` 内部的内存。
files: Files,
contents: std.ArrayList(u8),
pub const empty: @This() = .{
.files = .empty,
.contents = .empty,
};
pub fn deinit(scf: *SelfContainedFiles, gpa: Allocator) void {
scf.files.deinit(gpa);
scf.contents.deinit(gpa);
scf.* = undefined;
}
pub fn path(scf: *const SelfContainedFiles, file_offset: File.Offset) [:0]const u8 {
return file_offset.path(scf.contents.items);
}
};
pub fn takeFiles(m: *Manifest) SelfContainedFiles {
defer m.files = .empty;
defer m.contents = .empty;
return borrowFiles(m);
}
pub fn borrowFiles(m: *const Manifest) SelfContainedFiles {
return .{
.files = m.files,
.contents = m.contents,
};
}
/// 释放清单文件及 Manifest 使用的全部内存。
/// 必须先调用 `Manifest.hit`。
///
/// 不要忘记在此之前调用 `finalize`!
pub fn deinit(m: *Manifest) void {
const io = m.cache.io;
const gpa = m.cache.gpa;
if (m.manifest_file) |file| {
if (builtin.os.tag == .windows) {
// Windows 上需要此操作的原因见 Lock.release。
file.unlock(io);
}
file.close(io);
}
m.files.deinit(gpa);
m.contents.deinit(gpa);
m.input_paths.deinit(gpa);
m.all_input_content.deinit(gpa);
m.* = undefined;
}
pub fn populateFileSystemInputs(man: *const Manifest, buf: *std.ArrayList(u8)) Allocator.Error!void {
assert(@typeInfo(std.zig.Server.Message.PathPrefix).@"enum".field_names.len == man.cache.prefixes_len);
buf.clearRetainingCapacity();
const gpa = man.cache.gpa;
const files = man.files.keys();
if (files.len > 0) {
const contents = man.contents.items;
for (files) |file| {
const file_path = file.path(contents);
try buf.ensureUnusedCapacity(gpa, file_path.len + 2);
buf.appendAssumeCapacity(@as(u8, file.get(contents).flags.prefix) + 1);
buf.appendSliceAssumeCapacity(file_path);
buf.appendAssumeCapacity(0);
}
// 空字节是分隔符,而非终止符。
buf.items.len -= 1;
}
}
/// 缓存未命中后,将另一 `Manifest` 中的全部路径
/// 添加为被缓存进程的依赖项。
///
/// 另见:
/// * `addDiscoveredPath`
/// * `addDiscoveredDepFile`
pub fn addDiscoveredManifest(m: *Manifest, discovered: *const Manifest, prefix_map: [5]u8) Allocator.Error!void {
const gpa = m.cache.gpa;
assert(m.manifest_file != null);
transitionToMissDiscovered(m);
assert(@typeInfo(std.zig.Server.Message.PathPrefix).@"enum".field_names.len == discovered.cache.prefixes_len);
assert(discovered.cache.prefixes_len == 5);
const discovered_files = discovered.files.keys();
const orig_files_len = m.files.count();
const orig_contents_len = m.contents.items.len;
errdefer {
m.files.shrinkRetainingCapacityContext(orig_files_len, .{ .contents = m.contents.items });
m.contents.shrinkRetainingCapacity(orig_contents_len);
}
for (discovered_files, 0..) |off, file_index| {
try m.files.ensureUnusedCapacityContext(gpa, 1, .{ .contents = m.contents.items });
const next_index = file_index + 1;
const next_off = if (discovered_files.len - next_index == 0)
discovered.contents.items.len
else
@backingInt(discovered_files[next_index]);
const copy_bytes = discovered.contents.items[@backingInt(off)..next_off];
const prev_contents_len: File.Offset = @fromBackingInt(@intCast(m.contents.items.len));
try m.contents.appendSlice(gpa, copy_bytes);
const gop = m.files.getOrPutAssumeCapacityContext(prev_contents_len, .{
.contents = m.contents.items,
});
if (gop.found_existing) {
m.contents.shrinkRetainingCapacity(@backingInt(prev_contents_len));
continue;
}
// 标志已复制,但应由 `prefix_map` 筛选前缀。
const other_file = prev_contents_len.get(m.contents.items);
other_file.flags.prefix = @intCast(prefix_map[other_file.flags.prefix]);
}
}
fn hashFile(io: Io, file: Io.File, bin_digest: *[Hasher.mac_length]u8) Io.File.ReadPositionalError!void {
var buffer: [2048]u8 = undefined;
var hasher = hasher_init;
var offset: u64 = 0;
while (true) {
const n = try file.readPositional(io, &.{&buffer}, offset);
if (n == 0) break;
hasher.update(buffer[0..n]);
offset += n;
}
hasher.final(bin_digest);
}
fn hashFileAppend(
io: Io,
file: Io.File,
bin_digest: *[Hasher.mac_length]u8,
al: *std.ArrayList(u8),
gpa: Allocator,
) (Io.File.ReadPositionalError || Allocator.Error)!void {
var hasher = hasher_init;
var offset: u64 = 0;
while (true) {
try al.ensureUnusedCapacity(gpa, 2048);
const buffer = al.unusedCapacitySlice();
const n = try file.readPositional(io, &.{buffer}, offset);
if (n == 0) break;
hasher.update(buffer[0..n]);
offset += n;
al.items.len += n;
}
hasher.final(bin_digest);
}
const HashDirError = Io.Dir.Reader.Error || Allocator.Error;
/// 将已排序、已编码的目录条目追加到 `contents`。
fn hashDir(
gpa: Allocator,
io: Io,
dir: Io.Dir,
bin_digest: *[Hasher.mac_length]u8,
contents: *std.ArrayList(u8),
) HashDirError!void {
var buffer: [@max(2048, Io.Dir.Reader.min_buffer_len)]u8 align(@alignOf(usize)) = undefined;
var reader: Io.Dir.Reader = .init(dir, &buffer);
var entry_buffer: [16]Io.Dir.Entry = undefined;
const contents_start = contents.items.len;
errdefer contents.shrinkRetainingCapacity(contents_start);
// 每个索引都指向 `contents` 内部。
var entries_list: std.ArrayList(u32) = .empty;
defer entries_list.deinit(gpa);
while (reader.state != .finished) {
const entries = entry_buffer[0..try reader.read(io, &entry_buffer)];
for (try entries_list.addManyAsSlice(gpa, entries.len), entries) |*off, entry| {
off.* = @intCast(contents.items.len);
// 作为优化,预留空间时也计入排序后必须复制 contents 缓冲区所需的空间。
//
try contents.ensureUnusedCapacity(gpa, (contents.items.len + entry.name.len + 2 - contents_start) * 2);
contents.appendAssumeCapacity(@backingInt(Manifest.File.Kind.fromStat(entry.kind)));
contents.appendSliceAssumeCapacity(entry.name);
contents.appendAssumeCapacity(0);
}
}
const Sort = struct {
contents: [*:0]const u8,
pub fn lessThan(this: @This(), lhs: u32, rhs: u32) bool {
// 此比较包含 kind 字节。
return mem.lessThanZ(u8, this.contents + lhs, this.contents + rhs);
}
};
mem.sortUnstable(u32, entries_list.items, @as(Sort, .{
.contents = @ptrCast(contents.items.ptr),
}), Sort.lessThan);
// 复制内容,以便在原位置(contents_start)创建排序副本时仍可引用该内容。
// 随后从未排序副本读取时,将 entries_list 中所有条目的偏移量
// 加上 contents 长度。
const contents_len = contents.items.len - contents_start;
@memcpy(contents.addManyAsSliceAssumeCapacity(contents_len), contents.items[contents_start..][0..contents_len]);
var new_offset: usize = contents_start;
for (entries_list.items) |wrong_offset| {
const offset = wrong_offset + contents_len;
// 包含同样需要复制的种类前缀。
const entry: [*:0]const u8 = @ptrCast(contents.items[offset..]);
new_offset += mem.copySentinelInclusive(u8, 0, contents.items[new_offset..], entry);
}
assert(new_offset == contents_start + contents_len);
contents.shrinkRetainingCapacity(contents_start + contents_len);
var hasher = hasher_init;
hasher.update(contents.items[contents_start..][0..contents_len]);
hasher.final(bin_digest);
}
};
/// 创建并写入文件,关闭它,然后获取其 stat.mtime 时间戳。
fn testGetCurrentFileTimestamp(io: Io, dir: Io.Dir) !Io.Timestamp {
const test_out_file = "test-filetimestamp.tmp";
var file = try dir.createFile(io, test_out_file, .{
.read = true,
.truncate = true,
});
defer {
file.close(io);
dir.deleteFile(io, test_out_file) catch {};
}
return (try file.stat(io)).mtime;
}
test "cache file and then recall it" {
const io = testing.io;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
const cwd = try std.process.currentPathAlloc(io, testing.allocator);
defer testing.allocator.free(cwd);
const temp_file = "test.txt";
const temp_manifest_dir = "temp_manifest_dir";
try tmp.dir.writeFile(io, .{ .sub_path = temp_file, .data = "Hello, world!\n" });
const tmp_directory: Directory = .{
.path = try std.fs.path.join(testing.allocator, &.{std.testing.TmpDir.parent_dir_path}),
.handle = tmp.dir,
};
defer testing.allocator.free(tmp_directory.path.?);
// 等待文件时间戳变化
const initial_time = try testGetCurrentFileTimestamp(io, tmp.dir);
while ((try testGetCurrentFileTimestamp(io, tmp.dir)).nanoseconds == initial_time.nanoseconds) {
try Io.Clock.Duration.sleep(.{ .clock = .boot, .raw = .fromNanoseconds(1) }, io);
}
var digest1: HexDigest = undefined;
var digest2: HexDigest = undefined;
{
var cache: Cache = .{
.io = io,
.gpa = testing.allocator,
.manifest_dir = try tmp.dir.createDirPathOpen(io, temp_manifest_dir, .{}),
.cwd = cwd,
};
cache.addPrefix(.{ .path = null, .handle = Io.Dir.cwd() });
cache.addPrefix(tmp_directory);
defer cache.manifest_dir.close(io);
{
var man = cache.obtain();
defer man.deinit();
man.hash.add(true);
man.hash.add(@as(u16, 1234));
man.hash.addBytes("1234");
_ = try man.addInputPath(.{
.root_dir = tmp_directory,
.sub_path = temp_file,
}, .{});
var diag: Manifest.CheckDiagnostic = undefined;
try testing.expectEqual(.incomplete_manifest, try man.check(&diag, .none));
digest1 = man.missDigestHex();
try man.finalize();
}
{
var man = cache.obtain();
defer man.deinit();
man.hash.add(true);
man.hash.add(@as(u16, 1234));
man.hash.addBytes("1234");
_ = try man.addInputPath(.{
.root_dir = tmp_directory,
.sub_path = temp_file,
}, .{});
// 缓存命中!刚刚“构建”过相同文件
var diag: Manifest.CheckDiagnostic = undefined;
try testing.expectEqual(.hit, try man.check(&diag, .none));
digest2 = man.hitDigestHex();
try testing.expectEqual(false, man.have_exclusive_lock);
}
try testing.expectEqual(digest1, digest2);
}
}
test "check that changing a file causes cache miss" {
const io = testing.io;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
const cwd = try std.process.currentPathAlloc(io, testing.allocator);
defer testing.allocator.free(cwd);
const temp_file = "cache_hash_change_file_test.txt";
const temp_manifest_dir = "cache_hash_change_file_manifest_dir";
const original_temp_file_contents = "Hello, world!\n";
const updated_temp_file_contents = "Hello, world; but updated!\n";
try tmp.dir.writeFile(io, .{ .sub_path = temp_file, .data = original_temp_file_contents });
const tmp_directory: Directory = .{
.path = try std.fs.path.join(testing.allocator, &.{std.testing.TmpDir.parent_dir_path}),
.handle = tmp.dir,
};
defer testing.allocator.free(tmp_directory.path.?);
// 等待文件时间戳变化
const initial_time = try testGetCurrentFileTimestamp(io, tmp.dir);
while ((try testGetCurrentFileTimestamp(io, tmp.dir)).nanoseconds == initial_time.nanoseconds) {
try Io.Clock.Duration.sleep(.{ .clock = .boot, .raw = .fromNanoseconds(1) }, io);
}
var digest1: HexDigest = undefined;
var digest2: HexDigest = undefined;
{
var cache: Cache = .{
.io = io,
.gpa = testing.allocator,
.manifest_dir = try tmp.dir.createDirPathOpen(io, temp_manifest_dir, .{}),
.cwd = cwd,
};
cache.addPrefix(.{ .path = null, .handle = Io.Dir.cwd() });
cache.addPrefix(tmp_directory);
defer cache.manifest_dir.close(io);
{
var man = cache.obtain();
defer man.deinit();
man.hash.addBytes("1234");
const temp_file_idx = try man.addInputPath(.{
.root_dir = tmp_directory,
.sub_path = temp_file,
}, .{ .request_contents = true });
var diag: Manifest.CheckDiagnostic = undefined;
try testing.expectEqual(.incomplete_manifest, try man.check(&diag, .none));
try testing.expectEqualStrings(original_temp_file_contents, temp_file_idx.contents(&man));
digest1 = man.missDigestHex();
try man.finalize();
}
try tmp.dir.writeFile(io, .{ .sub_path = temp_file, .data = updated_temp_file_contents });
{
var man = cache.obtain();
defer man.deinit();
man.hash.addBytes("1234");
const temp_file_idx = try man.addInputPath(.{
.root_dir = tmp_directory,
.sub_path = temp_file,
}, .{ .request_contents = true });
// 唯一的输入文件发生了更改。
var diag: Manifest.CheckDiagnostic = undefined;
try testing.expectEqual(
@as(Manifest.CheckResult, .{ .contents_changed = temp_file_idx.offset(&man) }),
try man.check(&diag, .none),
);
try testing.expectEqualStrings(updated_temp_file_contents, temp_file_idx.contents(&man));
digest2 = man.missDigestHex();
try man.finalize();
}
try testing.expect(!mem.eql(u8, &digest1, &digest2));
}
}
test "no file inputs" {
const io = testing.io;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
const cwd = try std.process.currentPathAlloc(io, testing.allocator);
defer testing.allocator.free(cwd);
const temp_manifest_dir = "no_file_inputs_manifest_dir";
var digest1: HexDigest = undefined;
var digest2: HexDigest = undefined;
var cache: Cache = .{
.io = io,
.gpa = testing.allocator,
.manifest_dir = try tmp.dir.createDirPathOpen(io, temp_manifest_dir, .{}),
.cwd = cwd,
};
cache.addPrefix(.{ .path = null, .handle = tmp.dir });
defer cache.manifest_dir.close(io);
{
var man = cache.obtain();
defer man.deinit();
man.hash.addBytes("1234");
var diag: Manifest.CheckDiagnostic = undefined;
try testing.expectEqual(.incomplete_manifest, try man.check(&diag, .none));
digest1 = man.missDigestHex();
try man.finalize();
}
{
var man = cache.obtain();
defer man.deinit();
man.hash.addBytes("1234");
var diag: Manifest.CheckDiagnostic = undefined;
try testing.expectEqual(.hit, try man.check(&diag, .none));
digest2 = man.hitDigestHex();
try testing.expectEqual(false, man.have_exclusive_lock);
}
try testing.expectEqual(digest1, digest2);
}
test "Manifest with files added after initial hash" {
const io = testing.io;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
const cwd = try std.process.currentPathAlloc(io, testing.allocator);
defer testing.allocator.free(cwd);
const temp_file1 = "cache_hash_post_file_test1.txt";
const temp_file2 = "cache_hash_post_file_test2.txt";
const temp_manifest_dir = "cache_hash_post_file_manifest_dir";
try tmp.dir.writeFile(io, .{ .sub_path = temp_file1, .data = "Hello, world!\n" });
try tmp.dir.writeFile(io, .{ .sub_path = temp_file2, .data = "Hello world the second!\n" });
const tmp_directory: Directory = .{
.path = try std.fs.path.join(testing.allocator, &.{std.testing.TmpDir.parent_dir_path}),
.handle = tmp.dir,
};
defer testing.allocator.free(tmp_directory.path.?);
// 等待文件时间戳变化
const initial_time = try testGetCurrentFileTimestamp(io, tmp.dir);
while ((try testGetCurrentFileTimestamp(io, tmp.dir)).nanoseconds == initial_time.nanoseconds) {
try Io.Clock.Duration.sleep(.{ .clock = .boot, .raw = .fromNanoseconds(1) }, io);
}
var digest1: HexDigest = undefined;
var digest2: HexDigest = undefined;
var digest3: HexDigest = undefined;
{
var cache: Cache = .{
.io = io,
.gpa = testing.allocator,
.manifest_dir = try tmp.dir.createDirPathOpen(io, temp_manifest_dir, .{}),
.cwd = cwd,
};
cache.addPrefix(.{ .path = null, .handle = Io.Dir.cwd() });
cache.addPrefix(tmp_directory);
defer cache.manifest_dir.close(io);
{
var man = cache.obtain();
defer man.deinit();
man.hash.addBytes("1234");
_ = try man.addInputPath(.{
.root_dir = tmp_directory,
.sub_path = temp_file1,
}, .{});
var diag: Manifest.CheckDiagnostic = undefined;
try testing.expectEqual(.incomplete_manifest, try man.check(&diag, .none));
try man.addDiscoveredPath(.{ .discovered_path = .{ .unresolved = .{
.root_dir = tmp_directory,
.sub_path = temp_file2,
} } });
digest1 = man.missDigestHex();
try man.finalize();
}
{
var man = cache.obtain();
defer man.deinit();
man.hash.addBytes("1234");
_ = try man.addInputPath(.{
.root_dir = tmp_directory,
.sub_path = temp_file1,
}, .{});
var diag: Manifest.CheckDiagnostic = undefined;
try testing.expect(.hit == try man.check(&diag, .none));
digest2 = man.hitDigestHex();
try testing.expectEqual(false, man.have_exclusive_lock);
}
try testing.expect(mem.eql(u8, &digest1, &digest2));
// 修改初始哈希后添加的文件
try tmp.dir.writeFile(io, .{ .sub_path = temp_file2, .data = "Hello world the second, updated\n" });
// 等待文件时间戳变化
const initial_time2 = try testGetCurrentFileTimestamp(io, tmp.dir);
while ((try testGetCurrentFileTimestamp(io, tmp.dir)).nanoseconds == initial_time2.nanoseconds) {
try Io.Clock.Duration.sleep(.{ .clock = .boot, .raw = .fromNanoseconds(1) }, io);
}
{
var man = cache.obtain();
defer man.deinit();
man.hash.addBytes("1234");
_ = try man.addInputPath(.{
.root_dir = tmp_directory,
.sub_path = temp_file1,
}, .{});
var diag: Manifest.CheckDiagnostic = undefined;
switch (try man.check(&diag, .none)) {
.contents_changed => |off| {
try testing.expectEqualStrings(temp_file2, off.path(man.contents.items));
},
else => return error.TestFailed,
}
try man.addDiscoveredPath(.{ .discovered_path = .{ .unresolved = .{
.root_dir = tmp_directory,
.sub_path = temp_file2,
} } });
digest3 = man.missDigestHex();
try man.finalize();
}
try testing.expect(!mem.eql(u8, &digest1, &digest3));
}
}
test {
_ = Path;
_ = Directory;
_ = DepTokenizer;
}