diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index cbbcd10e..e3936c21 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -34,3 +34,37 @@ jobs: - name: Test run: cargo test --workspace + + # release.yaml builds for Windows only on a signed tag, and the release + # rehearsal runs only when a release input changes. A pull request that + # changes Rust code alone reached a tag with a Windows build that did + # not compile. This job compiles every target of the workspace for + # Windows on every pull request, and a warning fails it. It then runs + # the release build command, which compiles code that only the release + # profile enables and links rune.exe, and the rune-docs tests. + windows: + runs-on: windows-latest + env: + RUSTFLAGS: -D warnings + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6 + with: + persist-credentials: false + + - uses: dtolnay/rust-toolchain@4be7066ada62dd38de10e7b70166bc74ed198c30 # stable + with: + toolchain: 1.100.0 + + - name: Check + run: cargo check --locked --workspace --all-features --all-targets + + # The same command as the Windows row of the release matrix. + - name: Build the release binary + run: cargo build --release --locked --target x86_64-pc-windows-msvc + + # Spec transactions open, link, rename, and flush files through + # Windows calls, and file identity comes from an open handle. + # Only a Windows runner can prove that a transaction completes + # there and that a hard link equals its target. + - name: Test rune-docs + run: cargo test --locked -p rune-docs --all-features diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e65e844..4aab13e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/). +[0.7.1]: https://github.com/runedeck/rune/compare/v0.7.0...v0.7.1 [0.7.0]: https://github.com/runedeck/rune/compare/v0.6.0...v0.7.0 [0.6.0]: https://github.com/runedeck/rune/compare/v0.5.0...v0.6.0 [0.5.0]: https://github.com/runedeck/rune/compare/v0.4.0...v0.5.0 @@ -14,6 +15,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). [0.2.0]: https://github.com/runedeck/rune/compare/v0.1.0...v0.2.0 [0.1.0]: https://github.com/runedeck/rune/releases/tag/v0.1.0 +## [0.7.1] - 2026-11-17 + +### Fixed + +- Build for Windows again. The 0.7.0 release build for `x86_64-pc-windows-msvc` did not compile. +- Read a file's identity on Windows from an open handle, as the volume serial number and the file index, so the spec transaction can tell a replaced file from the one it hashed. +- Skip the directory flush on Windows, where a directory does not open as a file. Spec transactions no longer fail there when they sync a directory. +- Compile `gix`, `jsonschema`, and the dashboard and terminal UI dependencies on every platform. They sat in the Unix-only dependency table with `nix`. + ## [0.7.0] - 2026-11-16 ### Added diff --git a/Cargo.lock b/Cargo.lock index 4532a8f7..2d567cb0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3599,7 +3599,7 @@ dependencies = [ [[package]] name = "rune-cli" -version = "0.7.0" +version = "0.7.1" dependencies = [ "ansi-to-tui", "askama", @@ -3656,6 +3656,7 @@ dependencies = [ "serde_yaml", "sha2 0.10.9", "tempfile", + "winapi-util", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 9e872b82..b3710944 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rune-cli" -version = "0.7.0" +version = "0.7.1" edition = "2024" license = "EUPL-1.2" repository = "https://github.com/runedeck/cli" @@ -84,9 +84,6 @@ ureq = { version = "3", default-features = false, features = ["rustls", "platfor webpki-root-certs = "1" signal-hook = "=0.3.18" -[target.'cfg(unix)'.dependencies] -nix = { version = "0.30", features = ["fs", "process", "resource", "signal"] } - # git gix = { version = "0.66", default-features = false, features = ["blocking-network-client", "blocking-http-transport-reqwest-rust-tls", "worktree-mutation"] } @@ -109,6 +106,11 @@ ansi-to-tui = { version = "8.0.1", optional = true } unicode-width = { version = "0.2", optional = true } edtui = { version = "0.11", default-features = false, optional = true } +# Only nix is Unix-only. This table stays after every other dependency: +# a dependency written below a target table header belongs to that target. +[target.'cfg(unix)'.dependencies] +nix = { version = "0.30", features = ["fs", "process", "resource", "signal"] } + [build-dependencies] sha2 = "0.10" diff --git a/rune-docs/Cargo.toml b/rune-docs/Cargo.toml index 60f5b273..3a201b3a 100644 --- a/rune-docs/Cargo.toml +++ b/rune-docs/Cargo.toml @@ -15,7 +15,7 @@ default = [] # The whole spec module: lifecycle commands, the read-only scans, tree # validation, and OpenSpec interop. links, adr, and the support helpers are # always compiled. -lifecycle = ["dep:clap", "dep:sha2"] +lifecycle = ["dep:clap", "dep:sha2", "dep:winapi-util"] [dependencies] clap = { version = "4", features = ["derive"], optional = true } @@ -27,6 +27,11 @@ serde_json = "1" serde_yaml = "0.9" sha2 = { version = "0.10", optional = true } +# File identity on Windows comes from an open handle: std has no stable +# accessor for the volume serial number or the file index. +[target.'cfg(windows)'.dependencies] +winapi-util = { version = "0.1.11", optional = true } + [dev-dependencies] tempfile = "3" diff --git a/rune-docs/src/spec/transaction/confine.rs b/rune-docs/src/spec/transaction/confine.rs index 2cec207f..bacb373d 100644 --- a/rune-docs/src/spec/transaction/confine.rs +++ b/rune-docs/src/spec/transaction/confine.rs @@ -15,62 +15,178 @@ pub(super) struct FileIdentity { inode: u64, } +/// The volume serial number and the file index, read from an open handle. +/// Stable Rust gives neither from `fs::Metadata` on Windows, and an +/// identity with no value in it would make every file equal every other. +/// +/// The index is the 64-bit one. NTFS keeps it unique on a volume. `ReFS` +/// names a file with a 128-bit identifier and gives the 64-bit index only +/// where it can map the long identifier to it without loss. Everywhere +/// else it reports all bits set, and a file system with no index reports +/// zero. Neither value names a file, so `windows_identity` refuses both +/// instead of letting two files compare equal. #[cfg(windows)] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct FileIdentity { - volume: Option, - index: Option, + volume: u64, + index: u64, } #[cfg(not(any(unix, windows)))] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct FileIdentity; +/// `FILE_FLAG_BACKUP_SEMANTICS`: lets a directory open, so a directory is +/// reported as not a regular file instead of as an access error. +#[cfg(windows)] +const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000; +/// `FILE_FLAG_OPEN_REPARSE_POINT`: opens a symlink itself, not its target. +#[cfg(windows)] +const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + #[cfg(any(unix, windows))] -pub(super) fn metadata_identity(metadata: &fs::Metadata) -> FileIdentity { +fn not_a_regular_file(path: &Path) -> Error { + Error::new( + ErrorKind::Io, + format!("transaction path is not a regular file: {}", path.display()), + ) +} + +/// The identity of an open regular file. The caller keeps the handle, so +/// the identity names the file the caller reads, not whatever the path +/// names a moment later. +#[cfg(any(unix, windows))] +pub(super) fn open_file_identity(file: &fs::File, path: &Path) -> Result { + let metadata = file + .metadata() + .map_err(|error| io_error("inspect", path, error))?; + if !metadata.is_file() { + return Err(not_a_regular_file(path)); + } #[cfg(unix)] { - use std::os::unix::fs::MetadataExt as _; - FileIdentity { - device: metadata.dev(), - inode: metadata.ino(), - } + Ok(unix_identity(&metadata)) } #[cfg(windows)] { - use std::os::windows::fs::MetadataExt as _; - FileIdentity { - volume: metadata.volume_serial_number(), - index: metadata.file_index(), - } + windows_identity(file, path) } } -pub(super) fn file_identity(path: &Path) -> Result { - #[cfg(not(any(unix, windows)))] - { - let _ = path; +#[cfg(unix)] +fn unix_identity(metadata: &fs::Metadata) -> FileIdentity { + use std::os::unix::fs::MetadataExt as _; + FileIdentity { + device: metadata.dev(), + inode: metadata.ino(), + } +} + +/// Whether a 64-bit file index names one file. Zero means the file system +/// keeps no index. All bits set means it could not give this file a +/// unique one, which `ReFS` does for a file whose 128-bit identifier does +/// not fit. +#[cfg(windows)] +pub(super) const fn index_names_one_file(index: u64) -> bool { + index != 0 && index != u64::MAX +} + +/// The identity behind an open handle to a regular file. Every Windows +/// identity comes through here, so a path and an open file are held to +/// the same rules: the handle is not a console, a pipe, or another +/// device, and its index names one file. +#[cfg(windows)] +fn windows_identity(file: &fs::File, path: &Path) -> Result { + let kind = winapi_util::file::typ(file).map_err(|error| io_error("inspect", path, error))?; + if kind.is_char() || kind.is_pipe() || kind.is_unknown() { + return Err(not_a_regular_file(path)); + } + let information = + winapi_util::file::information(file).map_err(|error| io_error("inspect", path, error))?; + let index = information.file_index(); + if !index_names_one_file(index) { return Err(Error::new( ErrorKind::Io, - "cannot verify file identity on this platform", + format!( + "cannot prove file identity because the file system gives no unique file index: {}", + path.display() + ), )); } - #[cfg(any(unix, windows))] + Ok(FileIdentity { + volume: information.volume_serial_number(), + index, + }) +} + +/// Opens `path` without following a symlink and without any access right: +/// reading the file information needs none. This is the handle form of +/// `fs::symlink_metadata`. +#[cfg(windows)] +fn open_without_following(path: &Path) -> Result { + use std::os::windows::fs::OpenOptionsExt as _; + fs::OpenOptions::new() + .access_mode(0) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS) + .open(path) + .map_err(|error| io_error("inspect", path, error)) +} + +/// The identity behind a handle from `open_without_following`. The +/// metadata of that handle classifies the path as `fs::symlink_metadata` +/// does: a symlink or a junction is refused, and so is a directory. A +/// deduplicated file or a cloud file also carries a reparse point, but it +/// is a regular file with its own index, and a followed open of the same +/// path reads that same index. +#[cfg(windows)] +fn unfollowed_identity(file: &fs::File, path: &Path) -> Result { + let metadata = file + .metadata() + .map_err(|error| io_error("inspect", path, error))?; + if metadata.file_type().is_symlink() || !metadata.is_file() { + return Err(not_a_regular_file(path)); + } + windows_identity(file, path) +} + +pub(super) fn file_identity(path: &Path) -> Result { + #[cfg(unix)] { let metadata = fs::symlink_metadata(path).map_err(|error| io_error("inspect", path, error))?; if metadata.file_type().is_symlink() || !metadata.is_file() { - return Err(Error::new( - ErrorKind::Io, - format!("transaction path is not a regular file: {}", path.display()), - )); + return Err(not_a_regular_file(path)); } - Ok(metadata_identity(&metadata)) + Ok(unix_identity(&metadata)) + } + #[cfg(windows)] + { + unfollowed_identity(&open_without_following(path)?, path) + } + #[cfg(not(any(unix, windows)))] + { + let _ = path; + Err(Error::new( + ErrorKind::Io, + "cannot verify file identity on this platform", + )) } } pub(super) fn is_same_file(left: &Path, right: &Path) -> Result { - Ok(file_identity(left)? == file_identity(right)?) + #[cfg(windows)] + { + // Both handles stay open until the comparison. A file index is + // unique only while the file exists, and an open handle keeps it + // from being given to another file. + let left_file = open_without_following(left)?; + let right_file = open_without_following(right)?; + Ok(unfollowed_identity(&left_file, left)? == unfollowed_identity(&right_file, right)?) + } + #[cfg(not(windows))] + { + Ok(file_identity(left)? == file_identity(right)?) + } } pub(super) fn path_exists_without_following(path: &Path) -> Result { diff --git a/rune-docs/src/spec/transaction/conversion.rs b/rune-docs/src/spec/transaction/conversion.rs index f3e0a83e..1b11362b 100644 --- a/rune-docs/src/spec/transaction/conversion.rs +++ b/rune-docs/src/spec/transaction/conversion.rs @@ -256,10 +256,7 @@ impl Transaction { fs::hard_link(&install, &destination) .map_err(|error| io_error("install create-only destination", &destination, error))?; verify_file_hash(&destination, &write.intended_sha256)?; - let directory = File::open(parent).map_err(|error| io_error("open", parent, error))?; - directory - .sync_all() - .map_err(|error| io_error("sync", parent, error)) + sync_directory(parent) } fn create_conversion_destination_directories( diff --git a/rune-docs/src/spec/transaction/identity_tests.rs b/rune-docs/src/spec/transaction/identity_tests.rs new file mode 100644 index 00000000..1f43bb43 --- /dev/null +++ b/rune-docs/src/spec/transaction/identity_tests.rs @@ -0,0 +1,145 @@ +//! File identity on every platform the transaction supports. These tests +//! run on Windows too, where the identity comes from an open handle: an +//! identity that compared equal for any two files would pass every +//! replacement check in the transaction. + +use super::confine::{file_identity, is_same_file}; +use super::verify::hash_file_with_identity; +use std::fs; +use tempfile::TempDir; + +#[test] +fn two_files_have_different_identities() { + let directory = TempDir::new().unwrap(); + let first = directory.path().join("first.md"); + let second = directory.path().join("second.md"); + fs::write(&first, "same bytes\n").unwrap(); + fs::write(&second, "same bytes\n").unwrap(); + + assert_ne!( + file_identity(&first).unwrap(), + file_identity(&second).unwrap() + ); + assert!(!is_same_file(&first, &second).unwrap()); +} + +#[test] +fn hard_link_has_the_identity_of_its_target() { + let directory = TempDir::new().unwrap(); + let target = directory.path().join("target.md"); + let link = directory.path().join("link.md"); + fs::write(&target, "content\n").unwrap(); + fs::hard_link(&target, &link).unwrap(); + + assert_eq!( + file_identity(&target).unwrap(), + file_identity(&link).unwrap() + ); + assert!(is_same_file(&target, &link).unwrap()); + assert!(is_same_file(&target, &target).unwrap()); +} + +#[test] +fn open_handle_and_path_agree_on_the_identity() { + let directory = TempDir::new().unwrap(); + let first = directory.path().join("first.md"); + let second = directory.path().join("second.md"); + fs::write(&first, "first\n").unwrap(); + fs::write(&second, "second\n").unwrap(); + + let (_, first_identity) = hash_file_with_identity(&first).unwrap(); + let (_, second_identity) = hash_file_with_identity(&second).unwrap(); + + assert_eq!(first_identity, file_identity(&first).unwrap()); + assert_eq!(second_identity, file_identity(&second).unwrap()); + assert_ne!(first_identity, second_identity); +} + +#[test] +fn replaced_file_has_a_new_identity() { + let directory = TempDir::new().unwrap(); + let path = directory.path().join("source.md"); + let replacement = directory.path().join("replacement.md"); + fs::write(&path, "content\n").unwrap(); + let (_, before) = hash_file_with_identity(&path).unwrap(); + + // The replacement exists beside the original before the rename, so + // the file system cannot give it the original's identity. + fs::write(&replacement, "content\n").unwrap(); + fs::rename(&replacement, &path).unwrap(); + + assert_ne!(before, file_identity(&path).unwrap()); +} + +#[test] +fn directory_has_no_file_identity() { + let directory = TempDir::new().unwrap(); + + let error = file_identity(directory.path()).unwrap_err(); + assert!( + error.to_string().contains("is not a regular file"), + "{error}" + ); + assert!(hash_file_with_identity(directory.path()).is_err()); +} + +#[test] +fn missing_file_has_no_identity() { + let directory = TempDir::new().unwrap(); + let missing = directory.path().join("missing.md"); + + assert!(file_identity(&missing).is_err()); + assert!(is_same_file(&missing, &missing).is_err()); +} + +#[cfg(unix)] +#[test] +fn symlink_has_no_file_identity() { + let directory = TempDir::new().unwrap(); + let target = directory.path().join("target.md"); + let link = directory.path().join("link.md"); + fs::write(&target, "content\n").unwrap(); + std::os::unix::fs::symlink(&target, &link).unwrap(); + + let error = file_identity(&link).unwrap_err(); + assert!( + error.to_string().contains("is not a regular file"), + "{error}" + ); + assert!(hash_file_with_identity(&link).is_err()); +} + +// A file system reports zero when it keeps no index, and all bits set +// when it cannot give a file a unique one. Two such files would compare +// equal, so neither value is an identity. +#[cfg(windows)] +#[test] +fn index_without_a_unique_value_names_no_file() { + use super::confine::index_names_one_file; + + assert!(!index_names_one_file(0)); + assert!(!index_names_one_file(u64::MAX)); + assert!(index_names_one_file(1)); + assert!(index_names_one_file(u64::MAX - 1)); +} + +// A symlink needs a privilege on Windows that a test process may not +// hold, so the test passes without a link when the system refuses one. +#[cfg(windows)] +#[test] +fn symlink_has_no_file_identity() { + let directory = TempDir::new().unwrap(); + let target = directory.path().join("target.md"); + let link = directory.path().join("link.md"); + fs::write(&target, "content\n").unwrap(); + if std::os::windows::fs::symlink_file(&target, &link).is_err() { + return; + } + + let error = file_identity(&link).unwrap_err(); + assert!( + error.to_string().contains("is not a regular file"), + "{error}" + ); + assert!(hash_file_with_identity(&link).is_err()); +} diff --git a/rune-docs/src/spec/transaction/mod.rs b/rune-docs/src/spec/transaction/mod.rs index 51c7a78c..d7881b9d 100644 --- a/rune-docs/src/spec/transaction/mod.rs +++ b/rune-docs/src/spec/transaction/mod.rs @@ -27,7 +27,7 @@ use journal::{ use serde::{Deserialize, Serialize}; use staging::{ archive_staging_path, copy_file_exclusive, copy_tree_exclusive, remove_verified_tree, - replace_file_from_backup, write_file_exclusive, + replace_file_from_backup, sync_directory, write_file_exclusive, }; use std::collections::HashSet; use std::fs::{self, File, OpenOptions}; @@ -724,5 +724,7 @@ fn io_error(action: &str, path: &Path, error: impl std::fmt::Display) -> Error { ) } +#[cfg(test)] +mod identity_tests; #[cfg(test)] mod tests; diff --git a/rune-docs/src/spec/transaction/staging.rs b/rune-docs/src/spec/transaction/staging.rs index 4d2d36bb..7b366668 100644 --- a/rune-docs/src/spec/transaction/staging.rs +++ b/rune-docs/src/spec/transaction/staging.rs @@ -120,10 +120,28 @@ pub(super) fn write_file_atomic(path: &Path, content: &[u8]) -> Result<(), Error io_error("replace", path, error), )); } - let directory = File::open(parent).map_err(|error| io_error("open", parent, error))?; - directory + sync_directory(parent) +} + +/// Flushes a directory, so a rename or a hard link made in it survives a +/// power loss. +/// +/// Windows skips the flush. `File::open` cannot open a directory there: +/// it fails with an access error, because a directory opens only with +/// `FILE_FLAG_BACKUP_SEMANTICS`. The flush behind `sync_all` is +/// `FlushFileBuffers`, and Microsoft documents it for a file, a volume, a +/// pipe, and a communications device, not for a directory. A flush that +/// one file system refuses would fail every transaction on it. The file +/// content is flushed before this call, and the file system keeps the +/// directory entry. +pub(super) fn sync_directory(directory: &Path) -> Result<(), Error> { + if cfg!(windows) { + return Ok(()); + } + File::open(directory) + .map_err(|error| io_error("open", directory, error))? .sync_all() - .map_err(|error| io_error("sync", parent, error)) + .map_err(|error| io_error("sync", directory, error)) } pub(super) fn replace_file_from_backup( diff --git a/rune-docs/src/spec/transaction/verify.rs b/rune-docs/src/spec/transaction/verify.rs index 9c9ae1c6..559deee9 100644 --- a/rune-docs/src/spec/transaction/verify.rs +++ b/rune-docs/src/spec/transaction/verify.rs @@ -2,7 +2,7 @@ //! a deterministic tree digest (sorted entries, kind- and length-prefixed) //! that proves a copied archive matches its source byte for byte. -use super::confine::{FileIdentity, metadata_identity, reject_symlink}; +use super::confine::{FileIdentity, open_file_identity, reject_symlink}; use super::io_error; use crate::error::{Error, ErrorKind}; use sha2::{Digest, Sha256}; @@ -36,16 +36,7 @@ pub(super) fn hash_file_with_identity(path: &Path) -> Result<(String, FileIdenti { reject_symlink(path)?; let mut file = File::open(path).map_err(|error| io_error("open", path, error))?; - let metadata = file - .metadata() - .map_err(|error| io_error("inspect", path, error))?; - if !metadata.is_file() { - return Err(Error::new( - ErrorKind::Io, - format!("transaction path is not a regular file: {}", path.display()), - )); - } - let identity = metadata_identity(&metadata); + let identity = open_file_identity(&file, path)?; Ok((hash_open_file(&mut file, path)?, identity)) } } diff --git a/src/cli/assemble/mod.rs b/src/cli/assemble/mod.rs index 652c24fd..c6211022 100644 --- a/src/cli/assemble/mod.rs +++ b/src/cli/assemble/mod.rs @@ -597,6 +597,24 @@ fn assemble_binary_passthrough( })) } +#[cfg(unix)] +fn create_skill_symlink(target: &Path, output_path: &Path) -> Result<(), Error> { + std::os::unix::fs::symlink(target, output_path).map_err(|error| { + Error::new( + rune::error::ErrorKind::Io, + format!("cannot create link {}: {error}", output_path.display()), + ) + }) +} + +#[cfg(not(unix))] +fn create_skill_symlink(_target: &Path, _output_path: &Path) -> Result<(), Error> { + Err(Error::new( + rune::error::ErrorKind::Validate, + "skill symlink assembly requires a supported Unix filesystem", + )) +} + #[allow(clippy::too_many_arguments)] fn assemble_symlink_passthrough( source: &sources::SourceFile, @@ -642,18 +660,7 @@ fn assemble_symlink_passthrough( std::fs::create_dir_all(parent) .map_err(|error| Error::new(rune::error::ErrorKind::Io, error.to_string()))?; } - #[cfg(unix)] - std::os::unix::fs::symlink(&target, &output_path).map_err(|error| { - Error::new( - rune::error::ErrorKind::Io, - format!("cannot create link {}: {error}", output_path.display()), - ) - })?; - #[cfg(not(unix))] - return Err(Error::new( - rune::error::ErrorKind::Validate, - "skill symlink assembly requires a supported Unix filesystem", - )); + create_skill_symlink(&target, &output_path)?; let statement = provenance::build_statement_bytes( &format!("{provider_name}/{deploy_relative}"), @@ -805,7 +812,11 @@ fn rewrite_command_values(value: &mut serde_json::Value, deployed_root: &str) { } } +#[cfg_attr(not(unix), allow(clippy::unnecessary_wraps))] // the Unix form can fail fn preserve_executable_bit(source: &sources::SourceFile, output_path: &Path) -> Result<(), Error> { + // Only Unix has an executable bit to carry over. + #[cfg(not(unix))] + let _ = (source, output_path); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; diff --git a/src/cli/deploy/mod.rs b/src/cli/deploy/mod.rs index 4a4b66b5..75a99f22 100644 --- a/src/cli/deploy/mod.rs +++ b/src/cli/deploy/mod.rs @@ -1229,6 +1229,20 @@ fn ensure_destination_within(target_path: &Path, base: &Path) -> Result<(), Erro }) } +#[cfg(unix)] +fn create_deployed_symlink(link: &Path, target: &Path) -> Result<(), Error> { + std::os::unix::fs::symlink(link, target) + .map_err(|error| Error::new(ErrorKind::Io, error.to_string())) +} + +#[cfg(not(unix))] +fn create_deployed_symlink(_link: &Path, _target: &Path) -> Result<(), Error> { + Err(Error::new( + ErrorKind::Validate, + "symbolic link deployment is unsupported on this platform", + )) +} + /// Copy a file, creating parent directories as needed. fn copy_file(source: &Path, target: &Path) -> Result<(), Error> { if let Some(parent) = target.parent() { @@ -1246,15 +1260,7 @@ fn copy_file(source: &Path, target: &Path) -> Result<(), Error> { fs::remove_file(target) .map_err(|error| Error::new(ErrorKind::Io, error.to_string()))?; } - #[cfg(unix)] - std::os::unix::fs::symlink(link, target) - .map_err(|error| Error::new(ErrorKind::Io, error.to_string()))?; - #[cfg(not(unix))] - return Err(Error::new( - ErrorKind::Validate, - "symbolic link deployment is unsupported on this platform", - )); - return Ok(()); + return create_deployed_symlink(&link, target); } if fs::symlink_metadata(target).is_ok_and(|meta| meta.file_type().is_symlink()) { fs::remove_file(target).map_err(|error| Error::new(ErrorKind::Io, error.to_string()))?; @@ -1311,19 +1317,18 @@ fn same_entry_semantics(left: &Path, right: &Path) -> bool { let (Ok(left), Ok(right)) = (fs::symlink_metadata(left), fs::symlink_metadata(right)) else { return false; }; - if left.file_type().is_symlink() != right.file_type().is_symlink() { - return false; - } + let same_kind = left.file_type().is_symlink() == right.file_type().is_symlink(); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; - if !left.file_type().is_symlink() + if same_kind + && !left.file_type().is_symlink() && left.permissions().mode() & 0o111 != right.permissions().mode() & 0o111 { return false; } } - true + same_kind } /// Check if a stale manifest entry was installed by the current module. diff --git a/src/cli/deploy/tests.rs b/src/cli/deploy/tests.rs index e385bb30..c2bc566d 100644 --- a/src/cli/deploy/tests.rs +++ b/src/cli/deploy/tests.rs @@ -386,6 +386,7 @@ fn only_matches_keeps_separated_names_distinct() { assert!(only_matches("skills/a-b/SKILL.md", "skills/a-b")); } +#[cfg(unix)] #[test] fn ensure_destination_within_rejects_symlink_escape() { let temp_directory = TempDir::new().unwrap(); diff --git a/src/cli/hook/legacy.rs b/src/cli/hook/legacy.rs index fb1051ca..107eb9cb 100644 --- a/src/cli/hook/legacy.rs +++ b/src/cli/hook/legacy.rs @@ -307,16 +307,14 @@ pub(crate) fn shebang_shell(text: &str) -> Option { /// process runs as, not by the mode bits alone. A file with an /// executable bit for its group only is not executable by its owner. pub(crate) fn executable(path: &Path) -> bool { - if !fs::metadata(path).is_ok_and(|m| m.is_file()) { - return false; - } + let is_file = fs::metadata(path).is_ok_and(|m| m.is_file()); #[cfg(unix)] { - nix::unistd::access(path, nix::unistd::AccessFlags::X_OK).is_ok() + is_file && nix::unistd::access(path, nix::unistd::AccessFlags::X_OK).is_ok() } #[cfg(not(unix))] { - true + is_file } } diff --git a/src/cli/hook/publish.rs b/src/cli/hook/publish.rs index defaafd3..2d2181be 100644 --- a/src/cli/hook/publish.rs +++ b/src/cli/hook/publish.rs @@ -63,6 +63,7 @@ fn set_mode(path: &Path, mode: u32) -> std::io::Result<()> { } #[cfg(not(unix))] +#[allow(clippy::unnecessary_wraps)] // the Unix form can fail fn set_mode(_path: &Path, _mode: u32) -> std::io::Result<()> { Ok(()) } diff --git a/src/cli/hook/record/tests.rs b/src/cli/hook/record/tests.rs index 9a4edff4..06002686 100644 --- a/src/cli/hook/record/tests.rs +++ b/src/cli/hook/record/tests.rs @@ -98,6 +98,7 @@ fn a_read_only_directory_costs_one_line_and_nothing_else() { assert!(errors[0].contains("1 hook record")); } +#[cfg(unix)] fn nix_is_root() -> bool { std::fs::metadata("/").is_ok() && std::env::var("USER").as_deref() == Ok("root") } diff --git a/src/cli/hook/switches.rs b/src/cli/hook/switches.rs index 5850ff42..ff386f67 100644 --- a/src/cli/hook/switches.rs +++ b/src/cli/hook/switches.rs @@ -175,6 +175,7 @@ fn set_mode(path: &Path, mode: u32) -> Result<(), Error> { } #[cfg(not(unix))] +#[allow(clippy::unnecessary_wraps)] // the Unix form can fail fn set_mode(_path: &Path, _mode: u32) -> Result<(), Error> { Ok(()) } diff --git a/src/cli/init/mod.rs b/src/cli/init/mod.rs index d90da3eb..15e40a73 100644 --- a/src/cli/init/mod.rs +++ b/src/cli/init/mod.rs @@ -1397,6 +1397,7 @@ fn is_vcs_internal(name: &std::ffi::OsStr) -> bool { /// enforces in the generated project (EXE001, EXE002), so a hook module /// without a shebang stays 644 and a script with one becomes executable /// wherever it lives. +#[cfg(any(unix, test))] pub(crate) fn wants_executable_bit(contents: &[u8]) -> bool { contents.starts_with(b"#!") } @@ -1421,6 +1422,7 @@ fn make_executable_if_needed(target: &Path, contents: &[u8]) -> Result<(), Error } #[cfg(not(unix))] +#[allow(clippy::unnecessary_wraps)] // the Unix form can fail fn make_executable_if_needed(_target: &Path, _contents: &[u8]) -> Result<(), Error> { Ok(()) } diff --git a/src/cli/process/mod.rs b/src/cli/process/mod.rs index 09895598..1627c0c0 100644 --- a/src/cli/process/mod.rs +++ b/src/cli/process/mod.rs @@ -269,6 +269,7 @@ impl SignalFlags { } #[cfg(not(unix))] + #[allow(clippy::unnecessary_wraps)] // the Unix form can fail fn register() -> Result { Ok(Self { interrupt: Arc::new(AtomicBool::new(false)), @@ -277,6 +278,7 @@ impl SignalFlags { }) } + #[cfg_attr(not(unix), allow(clippy::unused_self))] // only Unix has signals to read fn received(&self) -> Option { #[cfg(unix)] { @@ -330,6 +332,7 @@ impl SignalWatch { /// forwarded it to the harness and reported it), so it is not reported /// twice. A signal of the other kind, or one that arrives later, stays /// pending. + #[cfg_attr(not(unix), allow(clippy::unused_self))] // only Unix has signals to read pub(crate) fn acknowledge(&self, signal: i32) { #[cfg(unix)] { @@ -718,7 +721,10 @@ fn stopping_signal(failure: &ProcessFailure) -> i32 { } } #[cfg(not(unix))] - 0 + { + let _ = failure; + 0 + } } fn wait_for_process( diff --git a/src/cli/run/output.rs b/src/cli/run/output.rs index 418e1dd0..7008da59 100644 --- a/src/cli/run/output.rs +++ b/src/cli/run/output.rs @@ -50,6 +50,7 @@ impl Folder { /// folder the check judged, `checked`, by device and inode, so a folder /// swapped for another folder between the check and the open is refused /// as well. + #[cfg_attr(not(unix), allow(clippy::unnecessary_wraps))] // the Unix form can fail fn open(root: &Path, path: &Path, checked: &std::fs::Metadata) -> std::io::Result { #[cfg(unix)] { diff --git a/src/consumer.rs b/src/consumer.rs index d08f75e2..39f5ce1d 100644 --- a/src/consumer.rs +++ b/src/consumer.rs @@ -61,7 +61,9 @@ pub fn user_directory(home: &Path) -> PathBuf { #[cfg(test)] mod tests { - use super::{MANIFEST_IN_DIRECTORY, is_linked_directory, manifest_exists, manifest_path}; + #[cfg(unix)] + use super::is_linked_directory; + use super::{MANIFEST_IN_DIRECTORY, manifest_exists, manifest_path}; use std::path::Path; #[test] diff --git a/src/services/atomic.rs b/src/services/atomic.rs index 4e51141a..5229f037 100644 --- a/src/services/atomic.rs +++ b/src/services/atomic.rs @@ -118,6 +118,7 @@ mod tests { assert_eq!(fs::read(&path).unwrap(), b"\x00\xff binary"); } + #[cfg(unix)] #[test] fn refuses_a_symlinked_destination() { let root = tempfile::tempdir().unwrap(); diff --git a/src/services/confine.rs b/src/services/confine.rs index 30a84894..f360cbe4 100644 --- a/src/services/confine.rs +++ b/src/services/confine.rs @@ -202,6 +202,7 @@ mod tests { assert!(matches!(future, Violation::Escape { .. }), "{future:?}"); } + #[cfg(unix)] #[test] fn symlink_escape_is_rejected() { let root = tempfile::tempdir().unwrap(); @@ -242,6 +243,7 @@ mod tests { assert!(matches!(error, Violation::Escape { .. }), "{error:?}"); } + #[cfg(unix)] #[test] fn dangling_symlink_destination_is_rejected() { let root = tempfile::tempdir().unwrap(); diff --git a/tests/hook_dispatch.rs b/tests/hook_dispatch.rs index 4756f862..cbf6cdba 100644 --- a/tests/hook_dispatch.rs +++ b/tests/hook_dispatch.rs @@ -336,6 +336,7 @@ fn retired(scene: &Scene) -> Vec { } /// The command of the Claude `PreToolUse` registration. +#[cfg(unix)] fn pre_tool_command(scene: &Scene) -> String { json_at(&claude_settings(scene))["hooks"]["PreToolUse"][0]["hooks"][0]["command"] .as_str() @@ -346,6 +347,7 @@ fn pre_tool_command(scene: &Scene) -> String { /// A scene whose config guards `tool.before` with `dcg` under `deny`, /// installed, and the observer config that gives `dcg`'s id to a handler /// that allows every call. +#[cfg(unix)] fn guarded_scene() -> (Scene, String) { let scene = Scene::new(); std::fs::create_dir_all(scene.home().join(".claude")).unwrap(); @@ -365,6 +367,7 @@ fn guarded_scene() -> (Scene, String) { } /// What the registered `command` answers for `rm -rf /tmp/x`. +#[cfg(unix)] fn registration_answers(scene: &Scene, command: &str) -> String { let mut args = CLAUDE_PRE.to_vec(); let plan = plan_of(command); @@ -1540,6 +1543,7 @@ fn a_switch_rewrites_the_harness_table_at_once() { /// Trust the first rune entry of one Codex event the way `/hooks` records /// it: the sha256 of the hook's identity, keyed by table, event label, /// group, and handler, appended to the Codex config. +#[cfg(unix)] fn trust_codex(scene: &Scene, event: &str, label: &str) { use sha2::Digest as _; let table = scene.home().join(".codex/hooks.json"); diff --git a/tests/plugin.rs b/tests/plugin.rs index 7ea9b637..2446872a 100644 --- a/tests/plugin.rs +++ b/tests/plugin.rs @@ -1,3 +1,6 @@ +// Every plugin here is a shell script with the executable bit set. +#![cfg(unix)] + mod support; use assert_cmd::Command; use std::fs; diff --git a/tests/queue.rs b/tests/queue.rs index d1aad672..536efc19 100644 --- a/tests/queue.rs +++ b/tests/queue.rs @@ -65,6 +65,7 @@ fn json_of(output: &std::process::Output) -> serde_json::Value { }) } +#[cfg(unix)] const RECEIPT: &str = "Queued message msg-41 for thread 019a-ouroboros.\n"; #[cfg(unix)] diff --git a/tests/run.rs b/tests/run.rs index fc23ac4a..16a22ae0 100644 --- a/tests/run.rs +++ b/tests/run.rs @@ -498,6 +498,7 @@ printf '%s\n' '{"type":"turn.failed","error":{"message":null}}' /// The message of a run that failed on a JSON line rune cannot read: the /// tool, the line on stdout, and serde's reason for the truncated object. +#[cfg(unix)] fn assert_unreadable_line(result: &serde_json::Value, tool: &str, line: usize) { let message = result["details"]["message"].as_str().unwrap_or_default(); let prefix = @@ -4285,6 +4286,7 @@ fn the_guard_refuses_rewrites_outside_the_run_and_allows_the_harness_own_commits /// The names of the folders jj keeps under `/.config/jj/workspaces`: /// one for each workspace with its own configuration, such as a run's /// guard. None after a run means the run took its guard with it. +#[cfg(unix)] fn guard_folders(home: &std::path::Path) -> Vec { let config_root = home.join(".config/jj/workspaces"); let mut names: Vec = std::fs::read_dir(config_root).map_or_default(|entries| { @@ -5854,7 +5856,6 @@ fn marking_provider(home: &std::path::Path, name: &str, reply: &str) -> std::pat ) } -#[cfg(unix)] fn confirmation_of(output: &std::process::Output) -> serde_json::Value { serde_json::from_slice(&output.stdout).unwrap_or_else(|error| { panic!(