diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index e3936c21..4760ba17 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -38,10 +38,11 @@ jobs: # 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. + # not compile, and a build that compiles says nothing about whether + # rune works there. This job compiles every target of the workspace for + # Windows on every pull request, and a warning fails it. It runs the + # release build command, which compiles code that only the release + # profile enables and links rune.exe. Then it runs the workspace tests. windows: runs-on: windows-latest env: @@ -62,9 +63,26 @@ jobs: - 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 + # The tests start jj and mdschema, as on Linux, and sh, bash, + # and ssh-keygen from Git for Windows. Its tools go first on + # the PATH: System32 can hold a bash.exe that is the WSL + # launcher, which cannot read a Windows path. + - name: Install jj and mdschema + shell: bash + run: | + bash scripts/install-tools jj mdschema + cygpath -w "$HOME/.local/bin" >> "$GITHUB_PATH" + cygpath -w /usr/bin >> "$GITHUB_PATH" + + - name: Show the mdschema version + run: mdschema version + + # A test that needs a Unix shell script as a program, the + # executable bit, a process group, or python3 is marked + # `#[cfg_attr(windows, ignore = "...")]` with its reason, and + # the run reports it as ignored. Every other test runs here: + # spec transactions, file identity from an open handle, + # install, deploy, drift, doctor, and the isolation of every + # test from the runner's own profile. + - name: Test + run: cargo test --locked --workspace diff --git a/Cargo.lock b/Cargo.lock index 2d567cb0..b6ece472 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3614,6 +3614,7 @@ dependencies = [ "crossterm", "dirs", "edtui", + "getrandom 0.3.4", "gix", "jsonschema", "nix 0.30.1", diff --git a/Cargo.toml b/Cargo.toml index b3710944..32763533 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -106,11 +106,17 @@ 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. +# Only nix is Unix-only. The target tables stay 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"] } +# The seal nonce is 32 random bytes. Unix reads them from /dev/urandom, and +# Windows has no such file. getrandom is already in the dependency tree. +[target.'cfg(windows)'.dependencies] +getrandom = "0.3" + [build-dependencies] sha2 = "0.10" diff --git a/build.rs b/build.rs index 38403071..688a39ef 100644 --- a/build.rs +++ b/build.rs @@ -33,6 +33,19 @@ fn main() { build_commit(&manifest_dir) ); println!("cargo:rustc-env=RUNE_BUILD_TIME={}", build_time()); + + // Windows reserves 1 MB of stack for the main thread, where Linux and + // macOS give it 8 MB. A debug build of rune overflows 1 MB while it + // builds its command tree, before any command runs, so rune.exe asks + // the linker for the 8 MB the other platforms have. + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { + let argument = if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") { + "/STACK:8388608" + } else { + "-Wl,--stack,8388608" + }; + println!("cargo:rustc-link-arg-bins={argument}"); + } } fn build_commit(manifest_dir: &Path) -> String { diff --git a/rune-docs/src/links.rs b/rune-docs/src/links.rs index 22b27e59..ab15eeb4 100644 --- a/rune-docs/src/links.rs +++ b/rune-docs/src/links.rs @@ -1,6 +1,7 @@ //! Broken internal links and orphan pages across a repo's `docs/` tree. //! Pure analysis: the caller renders the report. +use crate::support::Canonical as _; use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; @@ -66,7 +67,7 @@ fn link_report(root: &Path, docs_root: &Path, pages: &[PathBuf]) -> DocsReport { LinkTarget::Relative(relative) => { let resolved = page_dir.join(decode_spaces(relative)); if resolved.exists() { - if let Ok(canonical) = resolved.canonicalize() { + if let Ok(canonical) = resolved.canonical() { linked.insert(canonical); } } else { @@ -78,7 +79,7 @@ fn link_report(root: &Path, docs_root: &Path, pages: &[PathBuf]) -> DocsReport { } LinkTarget::Wikilink(name) => match basenames.get(name.as_str()) { Some(found) => { - if let Ok(canonical) = found.canonicalize() { + if let Ok(canonical) = found.canonical() { linked.insert(canonical); } } @@ -92,7 +93,7 @@ fn link_report(root: &Path, docs_root: &Path, pages: &[PathBuf]) -> DocsReport { } for page in pages { - let Ok(canonical) = page.canonicalize() else { + let Ok(canonical) = page.canonical() else { continue; }; let is_entry = page diff --git a/rune-docs/src/spec/openspec_oracle.rs b/rune-docs/src/spec/openspec_oracle.rs index ca404a63..70fd2a08 100644 --- a/rune-docs/src/spec/openspec_oracle.rs +++ b/rune-docs/src/spec/openspec_oracle.rs @@ -2,6 +2,7 @@ //! `tests/fixtures/openspec/` proving that artifacts the pinned upstream //! release accepts load, apply, and round-trip here without semantic loss. +use crate::support::Canonical as _; use serde::Deserialize; use std::collections::{BTreeMap, BTreeSet}; use std::fs; @@ -90,7 +91,7 @@ fn compatibility_manifest_references_pinned_existing_fixtures() { let manifest: CompatibilityManifest = serde_yaml::from_str(MANIFEST).expect("compatibility manifest must deserialize"); let fixture_root = Path::new(FIXTURE_ROOT) - .canonicalize() + .canonical() .expect("fixture root must exist"); assert_eq!(manifest.version, 1); @@ -306,7 +307,7 @@ fn assert_fixture_path(fixture_root: &Path, relative_path: &str) { ); let canonical_path = fixture_root .join(declared_path) - .canonicalize() + .canonical() .unwrap_or_else(|error| panic!("fixture path is missing: {relative_path}: {error}")); assert!( canonical_path.starts_with(fixture_root), @@ -316,7 +317,7 @@ fn assert_fixture_path(fixture_root: &Path, relative_path: &str) { fn collect_tree(root_path: &Path) -> Result>, String> { let canonical_root = root_path - .canonicalize() + .canonical() .map_err(|error| format!("failed to resolve {}: {error}", root_path.display()))?; let mut files = BTreeMap::new(); collect_tree_files(&canonical_root, &canonical_root, &mut files)?; diff --git a/rune-docs/src/spec/root.rs b/rune-docs/src/spec/root.rs index ece9a056..783cede0 100644 --- a/rune-docs/src/spec/root.rs +++ b/rune-docs/src/spec/root.rs @@ -1,4 +1,5 @@ use crate::error::{Error, ErrorKind}; +use crate::support::Canonical as _; use std::path::{Path, PathBuf}; use std::sync::OnceLock; @@ -92,7 +93,7 @@ pub(super) fn resolve_with_config( configured: Option<&str>, ) -> Result { let repository = root - .canonicalize() + .canonical() .map_err(|error| root_error("resolve repository", root, error))?; let relative = match configured { Some(configured) => shared::validate_configured_root(configured), diff --git a/rune-docs/src/spec/root_shared.rs b/rune-docs/src/spec/root_shared.rs index 2fa9b87f..77a39c7e 100644 --- a/rune-docs/src/spec/root_shared.rs +++ b/rune-docs/src/spec/root_shared.rs @@ -15,6 +15,7 @@ // transaction journal wins so recovery reacquires the same lock. Two // journals, or none, stay ambiguous and require `spec.root`. +use crate::support::Canonical as _; use std::ffi::OsString; use std::path::{Component, Path, PathBuf}; @@ -86,7 +87,7 @@ pub(crate) fn resolve_confined_destination( .ok_or_else(|| format!("cannot resolve spec path: {}", candidate.display()))?; } - let resolved_existing = existing.canonicalize().map_err(|error| { + let resolved_existing = existing.canonical().map_err(|error| { format!("cannot resolve spec path {}: {error}", existing.display()) })?; if !resolved_existing.starts_with(repository) { diff --git a/rune-docs/src/spec/term_links.rs b/rune-docs/src/spec/term_links.rs index 8010d64a..f60bbfb3 100644 --- a/rune-docs/src/spec/term_links.rs +++ b/rune-docs/src/spec/term_links.rs @@ -8,6 +8,7 @@ use super::prose::prose_lines; use super::terms::{Term, Terms, kebab}; use super::{Error, ErrorKind}; +use crate::support::Canonical as _; use regex::Regex; use std::collections::BTreeMap; use std::path::{Component, Path, PathBuf}; @@ -353,7 +354,7 @@ pub(super) fn canonical(path: &Path) -> PathBuf { let mut rest = Vec::new(); let mut ancestor = path.as_path(); loop { - if let Ok(real) = ancestor.canonicalize() { + if let Ok(real) = ancestor.canonical() { let mut result = real; for component in rest.iter().rev() { result.push(component); diff --git a/rune-docs/src/spec/transaction/confine.rs b/rune-docs/src/spec/transaction/confine.rs index bacb373d..0d4ba6a0 100644 --- a/rune-docs/src/spec/transaction/confine.rs +++ b/rune-docs/src/spec/transaction/confine.rs @@ -4,6 +4,7 @@ use super::io_error; use crate::error::{Error, ErrorKind}; +use crate::support::Canonical as _; use std::fs; use std::io; use std::path::{Component, Path}; @@ -231,7 +232,7 @@ pub(super) fn inspect_existing_ancestors(root: &Path, candidate: &Path) -> Resul } Ok(_) => { let resolved = current - .canonicalize() + .canonical() .map_err(|error| io_error("resolve", ¤t, error))?; if !resolved.starts_with(root) { return Err(Error::new( diff --git a/rune-docs/src/spec/transaction/mod.rs b/rune-docs/src/spec/transaction/mod.rs index d7881b9d..eb1cae7a 100644 --- a/rune-docs/src/spec/transaction/mod.rs +++ b/rune-docs/src/spec/transaction/mod.rs @@ -15,6 +15,7 @@ pub(crate) use verify::sha256_file; use super::root::SpecRoot; use crate::error::{Error, ErrorKind}; +use crate::support::Canonical as _; use confine::{ create_confined_directories, file_identity, inspect_existing_ancestors, is_same_file, path_exists_without_following, reject_symlink, @@ -215,11 +216,11 @@ impl Transaction { .map_err(|error| io_error("create", spec_root.base(), error))?; let repository = spec_root .repository() - .canonicalize() + .canonical() .map_err(|error| io_error("resolve", spec_root.repository(), error))?; let root = spec_root .base() - .canonicalize() + .canonical() .map_err(|error| io_error("resolve", spec_root.base(), error))?; let lock_path = root.join(LOCK_FILE); reject_symlink(&lock_path)?; @@ -602,7 +603,7 @@ pub(super) fn health_findings( } let root = spec_root .base() - .canonicalize() + .canonical() .map_err(|error| io_error("resolve", spec_root.base(), error))?; // Diagnosis never writes: the lock is probed only if it already exists // (acquisition creates it), and a created lock is never unlinked here @@ -671,7 +672,7 @@ fn incomplete_transaction_findings( }; let repository = spec_root .repository() - .canonicalize() + .canonical() .map_err(|error| io_error("resolve", spec_root.repository(), error))?; let transaction = Transaction { repository, diff --git a/rune-docs/src/support.rs b/rune-docs/src/support.rs index 2446d906..f43133f2 100644 --- a/rune-docs/src/support.rs +++ b/rune-docs/src/support.rs @@ -114,11 +114,9 @@ pub(crate) fn temporary_sibling(path: &Path) -> PathBuf { /// created is the transaction layer's ancestor inspection; the two forms /// are deliberately separate and must not be collapsed. pub fn confine_existing(base: &Path, candidate: &Path) -> Result { - let resolved_base = base - .canonicalize() + let resolved_base = canonicalize(base) .map_err(|error| format!("cannot resolve {}: {error}", base.display()))?; - let resolved = candidate - .canonicalize() + let resolved = canonicalize(candidate) .map_err(|error| format!("cannot resolve {}: {error}", candidate.display()))?; if resolved.starts_with(&resolved_base) { Ok(resolved) @@ -131,6 +129,87 @@ pub fn confine_existing(base: &Path, candidate: &Path) -> Result) -> std::io::Result { + fs::canonicalize(path).map(plain) +} + +/// [`canonicalize`] as a method, for a path at the end of a chain. +pub trait Canonical { + /// See [`canonicalize`]. + fn canonical(&self) -> std::io::Result; +} + +impl Canonical for Path { + fn canonical(&self) -> std::io::Result { + canonicalize(self) + } +} + +#[cfg(not(windows))] +fn plain(path: PathBuf) -> PathBuf { + path +} + +#[cfg(windows)] +fn plain(path: PathBuf) -> PathBuf { + match path.to_str().and_then(without_verbatim_prefix) { + Some(text) => PathBuf::from(text), + None => path, + } +} + +/// A verbatim path without its prefix, when the shorter text names the +/// same file: `\\?\C:\repo` is `C:\repo`, and `\\?\UNC\server\share` is +/// `\\server\share`. +#[cfg(any(windows, test))] +fn without_verbatim_prefix(text: &str) -> Option { + let plain = if let Some(rest) = text.strip_prefix(r"\\?\UNC\") { + format!(r"\\{rest}") + } else { + let rest = text.strip_prefix(r"\\?\")?; + let mut characters = rest.chars(); + let drive = characters.next()?; + if !drive.is_ascii_alphabetic() || characters.next() != Some(':') { + return None; + } + rest.to_owned() + }; + (plain.len() < 260 && plain.split('\\').all(part_reads_as_written)).then_some(plain) +} + +/// Whether Windows reads this part of a plain path as the name written. +/// It drops a trailing dot or space, and it reads a device name such as +/// `NUL`, with or without an extension, as the device. +#[cfg(any(windows, test))] +fn part_reads_as_written(part: &str) -> bool { + if part.ends_with('.') || part.ends_with(' ') { + return false; + } + let stem = part + .split('.') + .next() + .unwrap_or(part) + .trim_end() + .to_ascii_uppercase(); + let numbered = |device: &str| { + stem.strip_prefix(device).is_some_and(|number| { + matches!(number, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9") + }) + }; + !(matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") || numbered("COM") || numbered("LPT")) +} + /// Split `---`-fenced YAML frontmatter from a markdown body. Returns `None` /// when there is no opening fence at the start, the opening fence is never /// closed, or the content exceeds 256 KB. @@ -157,3 +236,32 @@ pub fn split_frontmatter(content: &str) -> Option<(&str, &str)> { Some((yaml_text, body)) } + +#[cfg(test)] +mod tests { + use super::without_verbatim_prefix; + + #[test] + fn a_verbatim_drive_or_network_path_loses_its_prefix() { + assert_eq!( + without_verbatim_prefix(r"\\?\C:\repo\docs").as_deref(), + Some(r"C:\repo\docs") + ); + assert_eq!( + without_verbatim_prefix(r"\\?\UNC\server\share\repo").as_deref(), + Some(r"\\server\share\repo") + ); + } + + #[test] + fn a_path_only_the_verbatim_form_names_keeps_its_prefix() { + for path in [ + r"\\?\Volume{b75e2c83-0000-0000-0000-602f00000000}\repo", + r"\\?\C:\repo\NUL", + r"\\?\C:\repo\name.", + r"C:\repo", + ] { + assert_eq!(without_verbatim_prefix(path), None, "{path}"); + } + } +} diff --git a/scripts/install-tools b/scripts/install-tools index f30e2ebd..0f273c6e 100755 --- a/scripts/install-tools +++ b/scripts/install-tools @@ -155,17 +155,22 @@ verified_archive() { local binary_name=$4 local scratch_directory scratch_directory=$(mktemp -d "${TMPDIR:-/tmp}/rune-tools.XXXXXX") + # A Windows release holds the tool as an .exe. + local executable=$binary_name + if [ "$(platform)" = "windows" ]; then + executable="$binary_name.exe" + fi if ! ( cd "$scratch_directory" \ && curl -fsSL --connect-timeout 15 --max-time 300 --retry 3 --retry-connrefused "$archive_url" -o "$archive_name" \ && printf '%s %s\n' "$expected_digest" "$archive_name" > selected-checksum \ && digest_matches selected-checksum \ - && tar -xf "$archive_name" \ - && extracted_binary=$(find . -type f -name "$binary_name" -perm -u+x -print -quit) \ + && extract_archive "$archive_name" \ + && extracted_binary=$(find . -type f -name "$executable" -perm -u+x -print -quit) \ && [ -n "$extracted_binary" ] \ && mkdir -p "$INSTALL_DIRECTORY" \ - && install -m 0755 "$extracted_binary" "$INSTALL_DIRECTORY/$binary_name" + && install -m 0755 "$extracted_binary" "$INSTALL_DIRECTORY/$executable" ); then command rm -rf "$scratch_directory" fail "could not install verified archive $archive_name: digest or extraction failed" @@ -201,10 +206,22 @@ verified_binary() { export PATH="$INSTALL_DIRECTORY:$PATH" } +# A release archive is a tarball, or a zip for Windows. +extract_archive() { + case "$1" in + *.zip) unzip -q "$1" ;; + *) tar -xf "$1" ;; + esac +} + +# Windows is Git Bash, which a Windows runner starts this script in. Only +# jj and mdschema have a Windows digest: the Windows job runs the tests, +# and the checks that need the other tools run on Linux. platform() { case "$(uname -s)" in Darwin) printf 'darwin\n' ;; Linux) printf 'linux\n' ;; + MINGW*|MSYS*) printf 'windows\n' ;; *) fail "unsupported operating system: $(uname -s)" ;; esac } @@ -240,10 +257,13 @@ install_gitleaks() { install_mdschema() { tool_matches_version mdschema "$MDSCHEMA_VERSION" && return - local system_name machine_name archive_name digest + local system_name machine_name archive_name digest extension=tar.gz system_name=$(platform) machine_name=$(architecture) - archive_name="mdschema_${MDSCHEMA_VERSION}_${system_name}_${machine_name}.tar.gz" + if [ "$system_name" = "windows" ]; then + extension=zip + fi + archive_name="mdschema_${MDSCHEMA_VERSION}_${system_name}_${machine_name}.${extension}" digest=$(archive_digest mdschema "$system_name" "$machine_name") log "Installing digest-verified mdschema $MDSCHEMA_VERSION" verified_archive \ @@ -259,6 +279,7 @@ rust_target() { darwin:amd64) printf 'x86_64-apple-darwin\n' ;; linux:arm64) printf 'aarch64-unknown-linux-%s\n' "$1" ;; linux:amd64) printf 'x86_64-unknown-linux-%s\n' "$1" ;; + windows:amd64) printf 'x86_64-pc-windows-msvc\n' ;; *) fail "no release archive for $(platform)/$(architecture)" ;; esac } @@ -400,11 +421,15 @@ install_dcg() { "$archive_name" "$digest" dcg } -# jj publishes musl archives for linux and one per Apple target. +# jj publishes musl archives for linux, one per Apple target, and a zip +# for Windows. install_jj() { tool_matches_version jj "$JJ_VERSION" && return - local archive_name digest - archive_name="jj-v${JJ_VERSION}-$(rust_target musl).tar.gz" + local archive_name digest extension=tar.gz + if [ "$(platform)" = "windows" ]; then + extension=zip + fi + archive_name="jj-v${JJ_VERSION}-$(rust_target musl).${extension}" digest=$(archive_digest jj "$(platform)" "$(architecture)") log "Installing digest-verified jj $JJ_VERSION" verified_archive \ diff --git a/scripts/tool-versions b/scripts/tool-versions index 8b0a36d0..817cb9b7 100644 --- a/scripts/tool-versions +++ b/scripts/tool-versions @@ -29,6 +29,9 @@ MDSCHEMA_DARWIN_AMD64_SHA256="3a365906d5335442ebc5a167f016a74ea07f34befe10bffffd MDSCHEMA_DARWIN_ARM64_SHA256="1a150979f42f3d8b0a37388d1d24f85ff9fd7db5c253aa567516fd92a2e805f0" MDSCHEMA_LINUX_AMD64_SHA256="94a150893b0a0852e234f2e349dd19af4ede1b1f43f5e486e2d069e0cc7e605b" MDSCHEMA_LINUX_ARM64_SHA256="939c1d4fd3e5a553e2095fc404a30db980a92ea8db741be93666bb343eb8bd15" +# The Windows test job installs mdschema and jj, and no other tool. The +# mdschema digest is the publisher's, from its checksums file. +MDSCHEMA_WINDOWS_AMD64_SHA256="32c78c855510b5278bd45785745f4b0a70c8d9f9228dd3c750c3c0ce7904c531" # Prose and workflow linters (deck DECK-0010 row). Digests are computed from # the downloaded release archives; the linux amd64 values match the deck's @@ -88,3 +91,5 @@ JJ_DARWIN_AMD64_SHA256="10d941de276c7c5074ef5d395312813b4575f4ce92cb9c0b05738efb JJ_DARWIN_ARM64_SHA256="43daa37ce0f9716cdf6fb65a29cbcae74a3160aef048cf3cb3d166d41cb4ab58" JJ_LINUX_AMD64_SHA256="fce0271158e665ceb82dc66c5eb95b1728649094e9133074f3b5baece345fc08" JJ_LINUX_ARM64_SHA256="80e28f7501c11e50e0ca06cd6a1fa1d982cff9cc59bfe4411a9d36aa501d867e" +# Computed from the downloaded release archive on 2026-11-18. +JJ_WINDOWS_AMD64_SHA256="c42316b10df04611bc65029a18bcb2d92636edddb6871d511f7bb4233e999b83" diff --git a/src/cli/adopt/mod.rs b/src/cli/adopt/mod.rs index bd8d5cef..b25e6cd4 100644 --- a/src/cli/adopt/mod.rs +++ b/src/cli/adopt/mod.rs @@ -91,7 +91,7 @@ pub fn execute( // A local directory without --source-url records its canonical // location as a file URL, the same shape classify_url accepts, so the // upstream field never carries a bare relative path. - let canonical = fs::canonicalize(&directory) + let canonical = rune::folders::canonicalize(&directory) .map_err(|error| format!("cannot resolve {}: {error}", directory.display()))?; let attribution = source_url.map_or_else(|| format!("file://{}", canonical.display()), str::to_string); @@ -492,7 +492,7 @@ fn classify_url(url: &str) -> Result { } if !SCHEME_RE.is_match(url) { - let path = fs::canonicalize(url).map_err(|error| { + let path = rune::folders::canonicalize(url).map_err(|error| { if error.kind() == std::io::ErrorKind::NotFound { format!("local source does not exist: {url}") } else { @@ -563,7 +563,7 @@ fn fetch(source: &ClassifiedUrl) -> Result, String> { } fn canonical_module_root(module: &Path) -> Result { - let root = fs::canonicalize(module).map_err(|error| { + let root = rune::folders::canonicalize(module).map_err(|error| { format!( "cannot canonicalize rune source {}: {error}", module.display() diff --git a/src/cli/adopt/relocate.rs b/src/cli/adopt/relocate.rs index 3528486c..61f2691d 100644 --- a/src/cli/adopt/relocate.rs +++ b/src/cli/adopt/relocate.rs @@ -51,7 +51,7 @@ struct Plan { #[allow(clippy::too_many_lines)] fn plan(from: &Path, to: &Path) -> Result { - let from = fs::canonicalize(from) + let from = rune::folders::canonicalize(from) .map_err(|error| format!("cannot resolve {}: {error}", from.display()))?; if from .parent() @@ -77,7 +77,7 @@ fn plan(from: &Path, to: &Path) -> Result { .ok_or_else(|| format!("{} has no parent directory", to.display()))?; fs::create_dir_all(to_parent) .map_err(|error| format!("cannot create {}: {error}", to_parent.display()))?; - let to_parent = fs::canonicalize(to_parent) + let to_parent = rune::folders::canonicalize(to_parent) .map_err(|error| format!("cannot resolve {}: {error}", to_parent.display()))?; let to = to_parent.join( to.file_name() @@ -305,10 +305,10 @@ fn relative(root: &Path, path: &Path) -> String { /// git store answers only to jj). fn repository_root(directory: &Path) -> Option { if let Some(output) = git(directory, &["rev-parse", "--show-toplevel"]) { - return fs::canonicalize(output.trim()).ok(); + return rune::folders::canonicalize(output.trim()).ok(); } let output = jj(directory, &["workspace", "root"])?; - fs::canonicalize(output.trim()).ok() + rune::folders::canonicalize(output.trim()).ok() } /// The commit the transfer record pins: the last committed state. In a jj diff --git a/src/cli/adopt/review.rs b/src/cli/adopt/review.rs index d795503d..27e28d1a 100644 --- a/src/cli/adopt/review.rs +++ b/src/cli/adopt/review.rs @@ -817,9 +817,9 @@ pub(crate) fn trash_orphaned_sidecar( ) -> Result { // Both sides canonical, so a `/var` versus `/private/var` root never // turns the relative path into an absolute one that renames onto itself. - let module_root = fs::canonicalize(module_root) + let module_root = rune::folders::canonicalize(module_root) .map_err(|error| format!("cannot resolve {}: {error}", module_root.display()))?; - let canonical = fs::canonicalize(sidecar_path) + let canonical = rune::folders::canonicalize(sidecar_path) .map_err(|error| format!("cannot resolve {}: {error}", sidecar_path.display()))?; let relative = canonical.strip_prefix(&module_root).map_err(|_| { format!( @@ -1776,7 +1776,7 @@ pub(super) fn module_root_for(path: &Path) -> Result { }; for directory in start.ancestors() { if directory.join("module.yaml").is_file() { - return fs::canonicalize(directory).map_err(|error| { + return rune::folders::canonicalize(directory).map_err(|error| { format!( "cannot resolve module root {}: {error}", directory.display() @@ -1809,8 +1809,8 @@ fn git_session_root(module_root: &Path) -> Option { } fn fallback_session_root(module_root: &Path) -> Result { - let base = dirs::state_dir() - .or_else(dirs::cache_dir) + let base = rune::folders::state_dir() + .or_else(rune::folders::cache_dir) .ok_or_else(|| "cannot resolve a user state or cache directory".to_string())?; let key = manifest::content_sha256(&path_to_slash(module_root)); Ok(base.join("rune").join(SESSION_DIRECTORY).join(key)) diff --git a/src/cli/adopt/subject.rs b/src/cli/adopt/subject.rs index f3c95ebd..a823750d 100644 --- a/src/cli/adopt/subject.rs +++ b/src/cli/adopt/subject.rs @@ -41,9 +41,9 @@ pub fn holder_relative_name(module_root: &Path, holder: &Path, subject_name: &st .file_name() .unwrap_or_default() .to_os_string(); - let holder = std::fs::canonicalize(holder).unwrap_or_else(|_| holder.to_path_buf()); + let holder = rune::folders::canonicalize(holder).unwrap_or_else(|_| holder.to_path_buf()); let module_root = - std::fs::canonicalize(module_root).unwrap_or_else(|_| module_root.to_path_buf()); + rune::folders::canonicalize(module_root).unwrap_or_else(|_| module_root.to_path_buf()); let file = holder.join(file_name); file.strip_prefix(&module_root) .unwrap_or(&file) diff --git a/src/cli/adopt/tests.rs b/src/cli/adopt/tests.rs index 0db720a9..236a4c4b 100644 --- a/src/cli/adopt/tests.rs +++ b/src/cli/adopt/tests.rs @@ -1,4 +1,5 @@ use super::*; +use rune::folders::Canonical as _; const UPSTREAM: &str = "---\nname: upstream-skill\ndescription: Use when adopting fixtures.\nlicense: MIT\n---\n\n# Upstream\n\nBody.\n"; @@ -204,7 +205,7 @@ fn plain_local_file_path_is_canonicalized() { std::fs::write(&source_path, "Rule body.\n").expect("source file"); let source = classify_url(source_path.to_str().expect("utf8 path")).expect("local source"); - let canonical = source_path.canonicalize().expect("canonical source"); + let canonical = source_path.canonical().expect("canonical source"); assert_eq!( source.original_url, @@ -225,7 +226,7 @@ fn relative_local_file_path_is_canonicalized() { let source = classify_url(relative.to_str().expect("utf8 path")).expect("local source"); assert!( - matches!(source.fetch_url, FetchUrl::File(path) if path == source_path.canonicalize().expect("canonical source")) + matches!(source.fetch_url, FetchUrl::File(path) if path == source_path.canonical().expect("canonical source")) ); } @@ -698,7 +699,7 @@ fn adopt_rule_places_single_file_with_session() { ) .expect("rule adopt succeeds"); let root = adopted.artifact_root.expect("artifact root"); - let canonical_module = dir.path().canonicalize().expect("canonical temp dir"); + let canonical_module = dir.path().canonical().expect("canonical temp dir"); assert_eq!(root, canonical_module.join("rules/NoTabs.md")); review::open_session(&root, &adopted.upstream_uri, &adopted.upstream_digest) .expect("session opens"); @@ -959,7 +960,7 @@ fn modules_in_one_repository_use_distinct_session_directories() { /// directory to a repository under the temp directory. The base is made /// canonical first, since `..` climbs the physical tree. fn relative_path(base: &std::path::Path, target: &std::path::Path) -> std::path::PathBuf { - let base = base.canonicalize().expect("canonical base"); + let base = base.canonical().expect("canonical base"); let mut relative = std::path::PathBuf::new(); for _ in base.components().skip(1) { relative.push(".."); @@ -978,10 +979,7 @@ fn relative_root_selects_an_open_session_by_artifact() { // open on canonical paths, as `rune adopt` hands them over: a session // names its artifact relative to the canonical module root. let repository = tempfile::tempdir().expect("repository"); - let root = repository - .path() - .canonicalize() - .expect("canonical repository"); + let root = repository.path().canonical().expect("canonical repository"); init_git(&root); std::fs::write(root.join("module.yaml"), "name: fixture\n").expect("module"); @@ -1685,7 +1683,7 @@ fn directory_source_records_canonical_file_url() { .unwrap(); let expected = format!( "file://{}", - std::fs::canonicalize(&source_root).unwrap().display() + rune::folders::canonicalize(&source_root).unwrap().display() ); assert_eq!(adopted.upstream_uri, expected); let sidecar = manifest::provenance::read( diff --git a/src/cli/adopt/tree.rs b/src/cli/adopt/tree.rs index e869d9b1..fedf8c60 100644 --- a/src/cli/adopt/tree.rs +++ b/src/cli/adopt/tree.rs @@ -26,7 +26,7 @@ pub(super) fn adopt_tree( source_url: &str, dry_run: bool, ) -> Result { - let skill_root = std::fs::canonicalize(source_dir) + let skill_root = rune::folders::canonicalize(source_dir) .map_err(|error| format!("cannot resolve {}: {error}", source_dir.display()))?; let skill_md = skill_root.join("SKILL.md"); if !skill_md.is_file() { diff --git a/src/cli/assemble/snapshot.rs b/src/cli/assemble/snapshot.rs index 76477eb9..38718ffc 100644 --- a/src/cli/assemble/snapshot.rs +++ b/src/cli/assemble/snapshot.rs @@ -5,7 +5,6 @@ use crate::cli::dotrune::{self, Source}; use rune::error::{Error, ErrorKind}; use rune::manifest::source_snapshot::SourceInput; use std::collections::BTreeMap; -use std::fs; use std::path::{Path, PathBuf}; // The consumer manifest is not in this list: its path depends on the form @@ -56,7 +55,8 @@ fn source_inputs_with_cache( let mut inputs = Vec::new(); append_inputs(&mut inputs, "root", &root); let executable = std::env::current_exe().map_err(|error| incomplete(error.to_string()))?; - let executable = fs::canonicalize(executable).map_err(|error| incomplete(error.to_string()))?; + let executable = + rune::folders::canonicalize(executable).map_err(|error| incomplete(error.to_string()))?; inputs.push(SourceInput::required("builder:executable", executable)); let merged = config::load_merged_config(&root)?; let providers: BTreeMap<_, _> = config::load_providers(&merged)?.into_iter().collect(); @@ -146,7 +146,7 @@ fn append_inputs(inputs: &mut Vec, label: &str, root: &Path) { } fn canonical_directory(path: &Path) -> Result { - let path = fs::canonicalize(path).map_err(|error| { + let path = rune::folders::canonicalize(path).map_err(|error| { incomplete(format!( "source root {} is unavailable: {error}", path.display() diff --git a/src/cli/assemble/snapshot_tests.rs b/src/cli/assemble/snapshot_tests.rs index 20714b51..0fe31e13 100644 --- a/src/cli/assemble/snapshot_tests.rs +++ b/src/cli/assemble/snapshot_tests.rs @@ -1,5 +1,7 @@ use super::*; +use rune::folders::Canonical as _; use rune::manifest::source_snapshot::inspect; +use std::fs; fn module(root: &Path) { fs::create_dir_all(root.join("skills/Alpha")).unwrap(); @@ -113,7 +115,7 @@ fn source_inputs_require_existing_git_cache_without_materializing_it() { assert!( observed .iter() - .any(|input| input.path == cached.canonicalize().unwrap().join("skills")) + .any(|input| input.path == cached.canonical().unwrap().join("skills")) ); } diff --git a/src/cli/assemble/sources.rs b/src/cli/assemble/sources.rs index 78245ae0..917647e4 100644 --- a/src/cli/assemble/sources.rs +++ b/src/cli/assemble/sources.rs @@ -136,6 +136,12 @@ mod skill_symlink_tests { } } +/// The path of a source file under its module root, as the text every +/// record keeps: `/` between the parts on every platform. +fn module_relative(path: &Path, module_root: &Path) -> String { + rune::manifest::slash_lossy(path.strip_prefix(module_root).unwrap_or(path)) +} + /// A source file discovered during directory walking. /// /// ```text @@ -363,12 +369,7 @@ fn collect_pending(dir: &Path, module_root: &Path, pending: &mut Vec) { effective_review_state(&path, module_root), AdoptReviewState::Deployable ) { - pending.push( - path.strip_prefix(module_root) - .unwrap_or(&path) - .to_string_lossy() - .to_string(), - ); + pending.push(module_relative(&path, module_root)); } } } @@ -440,11 +441,7 @@ fn walk_content_dir( base_filenames.insert(filename); - let relative = path - .strip_prefix(module_root) - .unwrap_or(&path) - .to_string_lossy() - .to_string(); + let relative = module_relative(&path, module_root); let Some(content) = read_source_text(&path)? else { continue; @@ -512,11 +509,7 @@ fn walk_hook_dir( let Some(content) = read_source_text(&path)? else { continue; }; - let relative_path = path - .strip_prefix(module_root) - .unwrap_or(&path) - .to_string_lossy() - .to_string(); + let relative_path = module_relative(&path, module_root); sources.push(SourceFile { relative_path, full_path: path.to_string_lossy().to_string(), @@ -655,11 +648,7 @@ fn walk_qualifier_dir( if base_filenames.contains(&filename) { continue; } - let relative = path - .strip_prefix(module_root) - .unwrap_or(&path) - .to_string_lossy() - .to_string(); + let relative = module_relative(&path, module_root); let Some(content) = read_source_text(&path)? else { continue; }; diff --git a/src/cli/bench/mod.rs b/src/cli/bench/mod.rs index 9a7dc000..80bc1e8b 100644 --- a/src/cli/bench/mod.rs +++ b/src/cli/bench/mod.rs @@ -13,6 +13,7 @@ mod tests; use crate::cli::style::Sheet; use clap::Subcommand; use rune::error::{Error, ErrorKind}; +use rune::folders::Canonical as _; use rune::ontology; use std::path::{Path, PathBuf}; @@ -155,12 +156,12 @@ impl Workspace { fn owning_root(&self, suite_path: &Path) -> Option { let canonical_suite = suite_path - .canonicalize() + .canonical() .unwrap_or_else(|_| suite_path.to_path_buf()); self.roots .iter() .find(|root| { - let canonical_root = root.canonicalize().unwrap_or_else(|_| (*root).clone()); + let canonical_root = root.canonical().unwrap_or_else(|_| (*root).clone()); canonical_suite.starts_with(&canonical_root) }) .cloned() @@ -168,12 +169,12 @@ impl Workspace { fn is_private_suite(&self, suite_path: &Path) -> bool { let canonical_suite = suite_path - .canonicalize() + .canonical() .unwrap_or_else(|_| suite_path.to_path_buf()); self.roots.iter().any(|root| { let private_dir = root.join("suites").join("private"); let canonical_private = private_dir - .canonicalize() + .canonical() .unwrap_or_else(|_| private_dir.clone()); canonical_suite.starts_with(&canonical_private) }) @@ -248,7 +249,7 @@ fn resolve_workspace(config: &ontology::ResolvedConfig) -> Result, json: bool) -> Result { } fn home() -> Result { - dirs::home_dir().ok_or_else(|| { + rune::folders::home_dir().ok_or_else(|| { Error::new(ErrorKind::Config, "cannot resolve home directory") .with_code("completion.home_unavailable") .with_fix_command("printenv HOME") @@ -226,18 +226,27 @@ fn install_path(shell: Shell) -> Result { brew_prefix().map(|prefix| prefix.join("share/zsh/site-functions")); match site_functions { Some(directory) if directory.is_dir() => Ok(directory.join("_rune")), - _ => Ok(home.join(".zfunc/_rune")), + _ => Ok(rune::folders::join(&home, ".zfunc/_rune")), } } - Shell::Bash => Ok(home.join(".local/share/bash-completion/completions/rune")), - Shell::Fish => Ok(home.join(".config/fish/completions/rune.fish")), + Shell::Bash => Ok(rune::folders::join( + &home, + ".local/share/bash-completion/completions/rune", + )), + Shell::Fish => Ok(rune::folders::join( + &home, + ".config/fish/completions/rune.fish", + )), Shell::Nushell => { - let data_dir = dirs::data_dir().ok_or_else(|| { + let data_dir = rune::folders::data_dir().ok_or_else(|| { Error::new(ErrorKind::Config, "cannot resolve the user data directory") .with_code("completion.data_directory_unavailable") .with_fix_command("printenv HOME") })?; - Ok(data_dir.join("nushell/vendor/autoload/rune.nu")) + Ok(rune::folders::join( + &data_dir, + "nushell/vendor/autoload/rune.nu", + )) } Shell::Powershell | Shell::Elvish => Err(Error::new( ErrorKind::Config, diff --git a/src/cli/config/mod.rs b/src/cli/config/mod.rs index de3cb993..a89ddb42 100644 --- a/src/cli/config/mod.rs +++ b/src/cli/config/mod.rs @@ -221,7 +221,7 @@ pub(crate) fn detect_registered_providers( let search_path = std::env::var_os("PATH"); // Provider trees resolve under the target base, but opencode's wiring // lives under the home directory wherever the trees are. - let home = dirs::home_dir().ok_or_else(|| { + let home = rune::folders::home_dir().ok_or_else(|| { Error::new(ErrorKind::Config, "cannot resolve home directory") .with_code("provider.home_unavailable") .with_fix_command("printenv HOME") diff --git a/src/cli/dashboard/routes/artifact.rs b/src/cli/dashboard/routes/artifact.rs index cf86211a..9d9403e9 100644 --- a/src/cli/dashboard/routes/artifact.rs +++ b/src/cli/dashboard/routes/artifact.rs @@ -361,7 +361,7 @@ fn read_deployed_file( provider_dir: &str, path: &str, ) -> Option<(String, String)> { - let home = dirs::home_dir(); + let home = rune::folders::home_dir(); let mut bases: Vec = Vec::new(); if let Some(ref home) = home { bases.push(home.clone()); @@ -540,11 +540,7 @@ fn resolve_effective_content( use rune::assemble::variants; match variant_path { Some(path) => { - let label = path - .strip_prefix(repo) - .unwrap_or(path) - .to_string_lossy() - .to_string(); + let label = rune::manifest::slash_lossy(path.strip_prefix(repo).unwrap_or(path)); let variant_content = match std::fs::read_to_string(path) { Ok(content) => content, Err(error) => { diff --git a/src/cli/dashboard/routes/files.rs b/src/cli/dashboard/routes/files.rs index e8b5f8a7..5eea42cf 100644 --- a/src/cli/dashboard/routes/files.rs +++ b/src/cli/dashboard/routes/files.rs @@ -297,7 +297,7 @@ pub(super) async fn schema_page( &format!("{dir}/.mdschema"), &repo_path.join(dir).join(".mdschema"), "yaml", - dirs::home_dir().as_deref(), + rune::folders::home_dir().as_deref(), ) else { return ( axum::http::StatusCode::NOT_FOUND, diff --git a/src/cli/deploy/migration.rs b/src/cli/deploy/migration.rs index aba3c2f7..81f721b8 100644 --- a/src/cli/deploy/migration.rs +++ b/src/cli/deploy/migration.rs @@ -5,6 +5,7 @@ use super::{ parse_repo, resolve_target_base, same_entry_semantics, write_manifest, }; use rune::error::{Error, ErrorKind}; +use rune::folders::Canonical as _; use rune::manifest::{self, ManifestEntry}; use rune::provider::{ContentKind, ProviderConfig}; use rune::result::{ActionResult, PrunedFile}; @@ -80,7 +81,7 @@ pub(super) fn canonical_target(path: &Path) -> Result { .find(|entry| entry.exists()) .ok_or_else(|| conflict(path, "cannot resolve the destination"))?; let mut resolved = ancestor - .canonicalize() + .canonical() .map_err(|error| Error::new(ErrorKind::Io, error.to_string()))?; for component in absolute .strip_prefix(ancestor) @@ -230,7 +231,7 @@ impl MigrationPlan { { return Err(conflict(&old_root, "migration roots escape the target")); } - let build = module.join("build/codex/skills"); + let build = rune::folders::join(module, "build/codex/skills"); let mut plan = Self { old_root, new_root, @@ -251,9 +252,8 @@ impl MigrationPlan { } if let Some(prefix) = only { let selected = collect_files_recursive(&bundle.path())?.iter().any(|file| { - file.strip_prefix(&build).is_ok_and(|path| { - super::only_matches(&format!("skills/{}", path.display()), prefix) - }) + file.strip_prefix(&build) + .is_ok_and(|path| super::only_matches(&skill_key(path), prefix)) }); if !selected { continue; @@ -277,7 +277,7 @@ impl MigrationPlan { .filter(|entry| entry.kind != manifest::bundle::BundleEntryKind::Directory) .all(|entry| { super::only_matches( - &format!("{}/{}", relative.display(), entry.path), + &format!("{}/{}", manifest::slash_lossy(&relative), entry.path), prefix, ) }); @@ -413,6 +413,11 @@ fn rollback(moved: &[(PathBuf, PathBuf)]) { } } +/// A file under the build's `skills` folder, as a manifest key names it. +fn skill_key(path: &Path) -> String { + format!("skills/{}", manifest::slash_lossy(path)) +} + fn build_source(bundle: &Path, key: &str) -> Result { let path = bundle.join("SKILL.md"); let bytes = deployed_bytes(&path).map_err(|error| conflict(&path, &error.to_string()))?; @@ -426,18 +431,18 @@ fn inspect_selected_build( relative: &Path, expected: &manifest::bundle::BundleInspection, ) -> Result<(String, String), Error> { - let source = build_source(bundle, &relative.join("SKILL.md").to_string_lossy())?; + let source = build_source(bundle, &manifest::slash_lossy(&relative.join("SKILL.md")))?; for entry in &expected.entries { if entry.kind == manifest::bundle::BundleEntryKind::Directory { continue; } - let file = bundle.join(&entry.path); + let file = rune::folders::join(bundle, &entry.path); let fingerprint = manifest::content_sha256_bytes( &deployed_bytes(&file).map_err(|error| conflict(&file, &error.to_string()))?, ); let selected_source = provenance_source( &manifest::sidecar_path(&file), - &format!("{}/{}", relative.display(), entry.path), + &format!("{}/{}", manifest::slash_lossy(relative), entry.path), &fingerprint, )?; if !same_source(&source, &selected_source) { @@ -503,7 +508,7 @@ fn inspect_legacy( "bundle contains invalid paths, references, or symbolic links", )); }; - let prefix = format!("{}/", relative.display()); + let prefix = format!("{}/", manifest::slash_lossy(relative)); let mut keys: Vec<_> = entries .keys() .filter(|key| key.starts_with(&prefix)) @@ -522,7 +527,9 @@ fn inspect_legacy( return Err(conflict(&bundle, "invalid manifest key")); } let entry = &entries[key]; - let file = root.join(key); + // A key is written with `/`. Joined part by part, a conflict names + // the file with one kind of separator. + let file = rune::folders::join(root, key); let bytes = deployed_bytes(&file).map_err(|error| conflict(&file, &error.to_string()))?; if manifest::content_sha256_bytes(&bytes) != entry.fingerprint { return Err(conflict(&file, "managed content was modified locally")); @@ -534,7 +541,8 @@ fn inspect_legacy( { return Err(conflict(&file, "provenance leaves the skill bundle")); } - let source = provenance_source(&root.join(provenance), key, &entry.fingerprint)?; + let sidecar = rune::folders::join(root, provenance); + let source = provenance_source(&sidecar, key, &entry.fingerprint)?; if !same_source(&source, expected_source) { return Err(conflict( &file, @@ -553,7 +561,7 @@ fn inspect_legacy( )); } claimed.insert(file); - claimed.insert(root.join(provenance)); + claimed.insert(sidecar); } for file in collect_files_recursive(&bundle)? { if !claimed.contains(&file) { diff --git a/src/cli/deploy/mod.rs b/src/cli/deploy/mod.rs index 75a99f22..8aeea8b0 100644 --- a/src/cli/deploy/mod.rs +++ b/src/cli/deploy/mod.rs @@ -321,7 +321,7 @@ pub fn execute( /// under it), where wiring another harness's global instruction file is /// appropriate. Project-scope installs are left untouched. fn is_home_target(target: &str) -> bool { - let Some(home) = dirs::home_dir() else { + let Some(home) = rune::folders::home_dir() else { return false; }; let expanded = if let Some(rest) = target.strip_prefix("~/") { @@ -333,8 +333,8 @@ fn is_home_target(target: &str) -> bool { }; // Canonicalize both sides: on macOS the home path may resolve through // /private symlinks, so a raw compare spuriously fails. - let canonical_home = fs::canonicalize(&home).unwrap_or(home); - fs::canonicalize(&expanded).is_ok_and(|resolved| resolved == canonical_home) + let canonical_home = rune::folders::canonicalize(&home).unwrap_or(home); + rune::folders::canonicalize(&expanded).is_ok_and(|resolved| resolved == canonical_home) } /// The instruction-file (or config) wiring for one harness, keyed off the @@ -351,7 +351,7 @@ fn wire_harness_rules( if !deploy_rules.iter().any(|rule| rule == "rulesync") { return Ok(()); } - let Some(home) = dirs::home_dir() else { + let Some(home) = rune::folders::home_dir() else { return Ok(()); }; // Rule bodies come from the build tree so wiring is independent of whether @@ -491,11 +491,9 @@ fn deploy_provider_kind_files( continue; } - let relative = build_path - .strip_prefix(kind_dir) - .unwrap_or(&build_path) - .to_string_lossy() - .to_string(); + let relative = build_path.strip_prefix(kind_dir).unwrap_or(&build_path); + // A manifest key has `/` between its parts on every platform. + let relative = manifest::slash_lossy(relative); let manifest_key = format!("{kind}/{relative}"); if only.is_some_and(|prefix| !only_matches(&manifest_key, prefix)) { continue; diff --git a/src/cli/deploy/tests.rs b/src/cli/deploy/tests.rs index c2bc566d..1f92bc0b 100644 --- a/src/cli/deploy/tests.rs +++ b/src/cli/deploy/tests.rs @@ -426,14 +426,16 @@ impl CodexSkillFixture { fixture } + // Joined part by part: a migration names these folders as text, and + // a test compares that text. fn build(&self) -> PathBuf { - self.module.path().join("build/codex/skills/Alpha") + rune::folders::join(self.module.path(), "build/codex/skills/Alpha") } fn old(&self) -> PathBuf { - self.target.path().join(".codex/skills/Alpha") + rune::folders::join(self.target.path(), ".codex/skills/Alpha") } fn new_bundle(&self) -> PathBuf { - self.target.path().join(".agents/skills/Alpha") + rune::folders::join(self.target.path(), ".agents/skills/Alpha") } fn content(&self, relative: &str, bytes: &[u8]) { @@ -684,7 +686,7 @@ fn codex_migration_preserves_conflicts_before_any_content_write_even_with_force( } fn introduce_migration_conflict(fixture: &CodexSkillFixture, scenario: &str) -> PathBuf { - let sidecar = fixture.old().join(".provenance/guide.md.yaml"); + let sidecar = rune::folders::join(&fixture.old(), ".provenance/guide.md.yaml"); match scenario { "edit" | "entrypoint-edit" | "extra" => { let relative = match scenario { @@ -731,7 +733,7 @@ fn introduce_migration_conflict(fixture: &CodexSkillFixture, scenario: &str) -> fixture.new_bundle() } "missing-source" => { - let source = fixture.build().join(".provenance/guide.md.yaml"); + let source = rune::folders::join(&fixture.build(), ".provenance/guide.md.yaml"); fs::remove_file(&source).unwrap(); source } diff --git a/src/cli/doctor.rs b/src/cli/doctor.rs index 3f9a8945..040865d9 100644 --- a/src/cli/doctor.rs +++ b/src/cli/doctor.rs @@ -651,7 +651,8 @@ fn collect_managed_files_recursive( format!("cannot relativize {}: {error}", entry_path.display()), ) })?; - files.push(relative.to_string_lossy().into_owned()); + // A manifest key has `/` between its parts on every platform. + files.push(rune::manifest::slash_lossy(relative)); } } Ok(()) @@ -784,6 +785,7 @@ const DOT_MARK: &str = "●"; #[cfg(test)] mod tests { use super::*; + use rune::folders::Canonical as _; use std::fs; use tempfile::TempDir; @@ -982,8 +984,8 @@ mod tests { let expected = format!( "rune install --source {} --target {}", - crate::cli::shell_quote(&source.canonicalize().unwrap().to_string_lossy()), - crate::cli::shell_quote(&target.canonicalize().unwrap().to_string_lossy()) + crate::cli::shell_quote(&source.canonical().unwrap().to_string_lossy()), + crate::cli::shell_quote(&target.canonical().unwrap().to_string_lossy()) ); assert_eq!(error.code(), MANIFEST_MISSING_CODE); assert_eq!(error.fix_command(), Some(expected.as_str())); @@ -1005,8 +1007,8 @@ mod tests { let expected = format!( "rune install --source {} --target {} --provider codex", - crate::cli::shell_quote(&source.canonicalize().unwrap().to_string_lossy()), - crate::cli::shell_quote(&target_base.canonicalize().unwrap().to_string_lossy()) + crate::cli::shell_quote(&source.canonical().unwrap().to_string_lossy()), + crate::cli::shell_quote(&target_base.canonical().unwrap().to_string_lossy()) ); assert_eq!(error.code(), MANIFEST_MISSING_CODE); assert_eq!(error.fix_command(), Some(expected.as_str())); diff --git a/src/cli/doctor/skills.rs b/src/cli/doctor/skills.rs index 22a7129c..6f07d1ef 100644 --- a/src/cli/doctor/skills.rs +++ b/src/cli/doctor/skills.rs @@ -1,4 +1,5 @@ use rune::error::{Error, ErrorKind}; +use rune::folders::Canonical as _; use rune::skill_readiness::{self, NativeCatalog, NativeEvidence, SkillReadiness}; use std::collections::BTreeMap; use std::fs; @@ -22,7 +23,7 @@ pub(super) fn inspect( let target = std::path::absolute(target).map_err(|error| Error::io(error.to_string()))?; // Match the native catalog's physical CWD without inventing another scope // for platform aliases such as /var and /private/var on macOS. - let target = target.canonicalize().unwrap_or(target); + let target = target.canonical().unwrap_or(target); let mut roots = Vec::new(); let mut configuration = BTreeMap::new(); let mut skill_target = None; @@ -147,7 +148,7 @@ fn include_catalog_roots( if catalog.version != "rune-native-skill-catalog/v1" || catalog.cwd != target - .canonicalize() + .canonical() .map_err(|error| Error::io(error.to_string()))? .display() .to_string() diff --git a/src/cli/dotrune/git.rs b/src/cli/dotrune/git.rs index 27cb422c..d437b2f9 100644 --- a/src/cli/dotrune/git.rs +++ b/src/cli/dotrune/git.rs @@ -64,7 +64,7 @@ fn cache_root() -> Result { if let Some(override_dir) = std::env::var_os("RUNE_GIT_CACHE_DIR") { return Ok(PathBuf::from(override_dir)); } - let base = dirs::cache_dir().ok_or_else(|| { + let base = rune::folders::cache_dir().ok_or_else(|| { Error::new( ErrorKind::Io, "cannot resolve user cache directory (set XDG_CACHE_HOME or HOME)".to_string(), diff --git a/src/cli/dotrune/mod.rs b/src/cli/dotrune/mod.rs index 60b782b9..f8090f4e 100644 --- a/src/cli/dotrune/mod.rs +++ b/src/cli/dotrune/mod.rs @@ -64,10 +64,9 @@ pub fn load(repo_root: &Path) -> Result, Error> { return Ok(None); } // The form that was read, relative to the root: `.rune` or `.rune/manifest.yaml`. - let shown = path.strip_prefix(repo_root).map_or_else( - |_| path.display().to_string(), - |relative| relative.display().to_string(), - ); + let shown = path + .strip_prefix(repo_root) + .map_or_else(|_| path.display().to_string(), rune::manifest::slash_lossy); let bytes = fs::read(&path).map_err(|error| { Error::new( diff --git a/src/cli/dotrune/resolve.rs b/src/cli/dotrune/resolve.rs index aa98532d..c1500765 100644 --- a/src/cli/dotrune/resolve.rs +++ b/src/cli/dotrune/resolve.rs @@ -4,7 +4,6 @@ use rune::error::{Error, ErrorKind}; use std::collections::HashSet; -use std::fs; use std::path::{Path, PathBuf}; use crate::cli::assemble::sources::{self, SourceFile}; @@ -200,7 +199,7 @@ fn canonicalize_local(path: &Path, source_label: &str, repo_root: &Path) -> Resu } else { repo_root.join(path) }; - fs::canonicalize(&resolved).map_err(|error| { + rune::folders::canonicalize(&resolved).map_err(|error| { Error::new( ErrorKind::Config, format!( @@ -216,7 +215,7 @@ fn canonicalize_subpath( subpath: Option<&Path>, source_label: &str, ) -> Result { - let materialized = fs::canonicalize(materialized).map_err(|error| { + let materialized = rune::folders::canonicalize(materialized).map_err(|error| { Error::new( ErrorKind::Config, format!( @@ -229,7 +228,7 @@ fn canonicalize_subpath( return Ok(materialized); }; let joined = materialized.join(subpath); - let canonical = fs::canonicalize(&joined).map_err(|error| { + let canonical = rune::folders::canonicalize(&joined).map_err(|error| { Error::new( ErrorKind::Config, format!( diff --git a/src/cli/drift/mod.rs b/src/cli/drift/mod.rs index 599e7d78..965ea640 100644 --- a/src/cli/drift/mod.rs +++ b/src/cli/drift/mod.rs @@ -665,11 +665,9 @@ fn collect_provenance_sidecars( .file_stem() .map_or_default(|stem| stem.to_string_lossy().into_owned()); let local_md = parent.join(format!("{stem}.md")); - let local_relative = local_md - .strip_prefix(base_directory) - .unwrap_or(&local_md) - .to_string_lossy() - .to_string(); + let local_relative = rune::manifest::slash_lossy( + local_md.strip_prefix(base_directory).unwrap_or(&local_md), + ); let source = sidecar .provenance @@ -734,11 +732,8 @@ fn collect_text_recursive( if path.is_dir() { collect_text_recursive(base_directory, &path, files); } else if let Ok(content) = fs::read_to_string(&path) { - let relative = path - .strip_prefix(base_directory) - .unwrap_or(&path) - .to_string_lossy() - .to_string(); + let relative = + rune::manifest::slash_lossy(path.strip_prefix(base_directory).unwrap_or(&path)); files.insert(relative, content); } } @@ -766,11 +761,8 @@ fn collect_markdown_recursive( if path.is_dir() { collect_markdown_recursive(base_directory, &path, files); } else if path.extension().is_some_and(|extension| extension == "md") { - let relative = path - .strip_prefix(base_directory) - .unwrap_or(&path) - .to_string_lossy() - .to_string(); + let relative = + rune::manifest::slash_lossy(path.strip_prefix(base_directory).unwrap_or(&path)); if let Ok(content) = fs::read_to_string(&path) { files.insert(relative, content); diff --git a/src/cli/drift/scope.rs b/src/cli/drift/scope.rs index 5dd40633..a8a0c9db 100644 --- a/src/cli/drift/scope.rs +++ b/src/cli/drift/scope.rs @@ -461,11 +461,7 @@ fn collect_recursive(base: &Path, current: &Path, files: &mut BTreeMap Vec } fn push_module(path: &Path, modules: &mut Vec, seen: &mut HashSet) { - let Ok(canonical) = fs::canonicalize(path) else { + let Ok(canonical) = rune::folders::canonicalize(path) else { return; }; if !canonical.join("module.yaml").is_file() || !seen.insert(canonical.clone()) { diff --git a/src/cli/hook/adapters.rs b/src/cli/hook/adapters.rs index e3bc251b..3034df4a 100644 --- a/src/cli/hook/adapters.rs +++ b/src/cli/hook/adapters.rs @@ -1207,7 +1207,7 @@ fn dcg(payload: &HandlerPayload) -> Result { fn git_ai(payload: &HandlerPayload) -> Result { let preset = payload.harness.as_str(); let stdin = serde_json::to_vec(&payload.raw).map_err(|e| e.to_string())?; - let program = dirs::home_dir() + let program = rune::folders::home_dir() .map(|h| h.join(".git-ai/bin/git-ai")) .filter(|p| p.is_file()) .map_or_else(|| "git-ai".to_string(), |p| p.display().to_string()); @@ -1430,7 +1430,7 @@ fn turn_checkpoint(payload: &HandlerPayload) -> Result { "session.end" => "clear", _ => return Ok(HandlerResult::default()), }; - let Some(script) = dirs::home_dir().and_then(|home| checkpoint_script(&home)) else { + let Some(script) = rune::folders::home_dir().and_then(|home| checkpoint_script(&home)) else { return Ok(HandlerResult::default()); }; let stdin = serde_json::to_vec(&claude_shaped(payload)).map_err(|e| e.to_string())?; @@ -1523,7 +1523,7 @@ fn tmux_status(payload: &HandlerPayload) -> Result { "session.end" => "clear", _ => return Ok(HandlerResult::default()), }; - let Some(program) = dirs::home_dir() + let Some(program) = rune::folders::home_dir() .map(|h| h.join(".local/bin/claude-tmux-status")) .filter(|p| p.is_file()) else { @@ -2094,6 +2094,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn an_immutable_working_copy_commit_keeps_its_author() { let home = config_home(); let dir = jj_checkout(); @@ -2117,6 +2121,7 @@ mod tests { } #[test] + #[cfg_attr(windows, ignore = "runs the authorship check, a python3 script")] fn an_unlisted_models_commit_fails_the_authorship_check() { if run_tool("python3", &["--version"], &[], None).is_err() { eprintln!("skipped: python3 is not installed"); @@ -2207,6 +2212,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_dormant_worktree_config_keeps_the_extension_off() { let home = config_home(); let a = jj_checkout(); @@ -2395,6 +2404,7 @@ mod tests { } #[test] + #[cfg_attr(windows, ignore = "runs the authorship check, a python3 script")] fn the_unlisted_identity_is_refused_by_the_push_gate() { if run_tool("python3", &["--version"], &[], None).is_err() { eprintln!("skipped: python3 is not installed"); @@ -2442,6 +2452,7 @@ mod tests { /// spelled as the helper spells it. A model under no rule gets the /// unlisted one, and the note names the policy file and the rule. #[test] + #[cfg_attr(windows, ignore = "runs the authorship check, a python3 script")] fn the_repository_policy_admits_the_models_the_gate_admits() { if run_tool("python3", &["--version"], &[], None).is_err() { eprintln!("skipped: python3 is not installed"); diff --git a/src/cli/hook/cover.rs b/src/cli/hook/cover.rs index 9f588e70..0995d5c1 100644 --- a/src/cli/hook/cover.rs +++ b/src/cli/hook/cover.rs @@ -11,7 +11,6 @@ use std::collections::BTreeMap; use std::ffi::{OsStr, OsString}; -use std::fs; use std::path::{Path, PathBuf}; use rune::hooks::{Harness, OnFailure, PlannedHandler}; @@ -211,7 +210,7 @@ fn tables_in(dir: &Path, harness: Harness) -> Vec { fn same_path(a: &Path, b: &Path) -> bool { a == b || matches!( - (fs::canonicalize(a), fs::canonicalize(b)), + (rune::folders::canonicalize(a), rune::folders::canonicalize(b)), (Ok(x), Ok(y)) if x == y ) } @@ -413,7 +412,7 @@ fn same_program(a: &str, b: &str) -> bool { match (a.contains('/'), b.contains('/')) { (false, false) => a == b, (true, true) => matches!( - (fs::canonicalize(a), fs::canonicalize(b)), + (rune::folders::canonicalize(a), rune::folders::canonicalize(b)), (Ok(x), Ok(y)) if x == y ), _ => false, @@ -621,6 +620,7 @@ pub(crate) fn holds( mod tests { use super::*; use serde_json::json; + use std::fs; fn w(words: &[&str]) -> Vec { words.iter().map(ToString::to_string).collect() @@ -632,6 +632,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_command_matches_by_program_file_and_exact_arguments() { let dir = tempfile::tempdir().unwrap(); let bin = dir.path().join("bin"); @@ -699,6 +703,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn what_an_adapter_runs_follows_the_harness_the_event_and_the_home() { let home = tempfile::tempdir().unwrap(); let at = |event: &str, adapter: &str, harness: Harness| { @@ -823,6 +831,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn the_environment_names_the_home_and_the_harness_folder_the_harness_reads() { let env = Environment { home: Some("/h".into()), diff --git a/src/cli/hook/dispatch_tests.rs b/src/cli/hook/dispatch_tests.rs index 4bac6297..daef6b75 100644 --- a/src/cli/hook/dispatch_tests.rs +++ b/src/cli/hook/dispatch_tests.rs @@ -1300,6 +1300,10 @@ fn two_hooks_on_one_event_leave_two_records_in_order_with_the_answer() { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn a_budget_spent_before_a_hook_records_the_budget_failure() { let temp = tempfile::tempdir().unwrap(); let plan = plan( @@ -1681,7 +1685,7 @@ const POLICY_PLAN: &str = "handlers:\n - id: guard\n exec: [guard]\n even /// everywhere and revokes `guard.deny` under `work/`. fn policy_scene() -> (tempfile::TempDir, std::path::PathBuf) { let temp = tempfile::tempdir().unwrap(); - let dir = std::fs::canonicalize(temp.path()).unwrap(); + let dir = rune::folders::canonicalize(temp.path()).unwrap(); for sub in ["work", "other", "record", "session"] { std::fs::create_dir_all(dir.join(sub)).unwrap(); } diff --git a/src/cli/hook/import_claude/mod.rs b/src/cli/hook/import_claude/mod.rs index 7088dcdd..12feaf40 100644 --- a/src/cli/hook/import_claude/mod.rs +++ b/src/cli/hook/import_claude/mod.rs @@ -50,7 +50,7 @@ pub(crate) struct Report { /// The default transcript store: the capture mirror when it exists, else /// the harness's own store. pub(crate) fn default_store() -> Option { - let home = dirs::home_dir()?; + let home = rune::folders::home_dir()?; let mirror = home.join("Data").join("Sessions").join("claude"); if mirror.is_dir() { return Some(mirror); @@ -81,7 +81,7 @@ pub(crate) fn import(store: &Path, dir: &Path) -> Result { }; let mut fresh: Vec = Vec::new(); for path in &transcripts { - let key = std::fs::canonicalize(path) + let key = rune::folders::canonicalize(path) .unwrap_or_else(|_| path.clone()) .display() .to_string(); @@ -295,7 +295,7 @@ fn persisted(content: &str) -> String { pub(crate) fn checkpoint_tools(dir: &Path, file: &Path) -> std::collections::BTreeSet { let text = std::fs::read_to_string(dir.join(CHECKPOINT)).unwrap_or_default(); let checkpoint: Checkpoint = serde_json::from_str(&text).unwrap_or_default(); - let key = std::fs::canonicalize(file).unwrap_or_else(|_| file.to_path_buf()); + let key = rune::folders::canonicalize(file).unwrap_or_else(|_| file.to_path_buf()); checkpoint .files .get(&key.display().to_string()) diff --git a/src/cli/hook/install.rs b/src/cli/hook/install.rs index 8481a761..762a774c 100644 --- a/src/cli/hook/install.rs +++ b/src/cli/hook/install.rs @@ -505,7 +505,7 @@ pub(crate) fn present(home: &Path, requested: &[Harness]) -> (Vec, Vec< /// write lands in the owner's file and the link stays a link. fn resolved(path: &Path) -> Result { if path.is_symlink() { - fs::canonicalize(path).map_err(|error| { + rune::folders::canonicalize(path).map_err(|error| { Error::io(format!( "{} is a link rune cannot follow: {error}", path.display() @@ -2151,6 +2151,10 @@ mod tests { const LIVE: &str = r#"{"model":"opus","hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"/Users/x/.local/bin/dcg"}]},{"hooks":[{"type":"command","command":"sh /Users/x/.sd/hook PreToolUse"}]},{"matcher":"*","hooks":[{"type":"command","command":"/Users/x/.git-ai/bin/git-ai checkpoint claude --hook-input stdin"}]}],"Notification":[{"hooks":[{"type":"command","command":"cmux hooks claude Notification"}]}]}}"#; #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn foreign_entries_survive_predecessors_are_adopted_and_one_rune_entry_per_event() { let home = tempfile::tempdir().unwrap(); let path = settings(home.path(), LIVE); @@ -2981,6 +2985,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn the_sweep_keeps_an_unnamed_generation_and_records_when_it_went() { let (home, plans, manifest) = sweep_home(); let now = at("2026-10-24T12:00:00Z"); @@ -2998,6 +3006,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn the_sweep_deletes_only_a_generation_retire_lets_go() { let (home, plans, manifest) = sweep_home(); for name in [ @@ -3248,6 +3260,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_compound_legacy_command_stays_and_is_named_for_a_hand_split() { let home = tempfile::tempdir().unwrap(); let compound = "sh ~/.sd/hook PreToolUse && /owner/check-policy"; @@ -3484,6 +3500,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn removing_rune_s_earlier_entry_waits_while_it_would_move_a_trusted_hook() { let home = tempfile::tempdir().unwrap(); fs::create_dir_all(home.path().join(".codex")).unwrap(); @@ -3570,6 +3590,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn rune_s_trusted_codex_entry_stays_until_codex_trusts_its_replacement() { let home = tempfile::tempdir().unwrap(); fs::create_dir_all(home.path().join(".codex")).unwrap(); @@ -3670,6 +3694,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn rune_s_trusted_postbox_entries_stay_at_group_one_until_codex_trusts_group_two() { const EVENTS: [&str; 2] = ["Stop", "UserPromptSubmit"]; let home = tempfile::tempdir().unwrap(); @@ -3780,6 +3808,10 @@ mod tests { /// 2026-10-26). Install reads the trust at that position and asks /// for nothing. #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn removing_a_trusted_preview_entry_keeps_the_live_entry_at_its_trusted_slot() { const EVENTS: [&str; 2] = ["Stop", "UserPromptSubmit"]; let home = tempfile::tempdir().unwrap(); @@ -3887,6 +3919,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_codex_predecessor_stays_until_codex_trusts_its_replacement() { let home = tempfile::tempdir().unwrap(); let codex = home.path().join(".codex").join("hooks.json"); @@ -3990,6 +4026,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_codex_predecessor_before_rune_in_its_group_stays_although_rune_is_trusted() { let home = tempfile::tempdir().unwrap(); let codex = home.path().join(".codex").join("hooks.json"); @@ -4289,6 +4329,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn the_owner_s_stop_parts_cover_tmux_alone_on_claude() { let home = owner_home(STOP_PARTS); let dispatcher = "sh $HOME/.config/just/hook Stop"; @@ -4390,6 +4434,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn the_owner_s_turn_wrap_part_is_the_wrapper_and_runs_twice_behind_the_first() { let home = owner_home(STOP_PARTS); // The script the part runs, so the part's command resolves. @@ -4555,6 +4603,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_covered_handler_is_skipped_at_each_firing_and_runs_once_its_part_goes() { let home = owner_home(STOP_PARTS); let dispatcher = "sh ~/.config/just/hook Stop"; @@ -4659,6 +4711,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_covered_wrapper_holds_no_time_back_from_the_handlers_before_it() { // The wrap part first in the owner's Stop.d, with its script, so // the cover skips the wrapper at each firing. @@ -4830,6 +4886,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_rewriter_is_never_covered_even_by_a_part_that_runs_its_command() { // A rewriter's output is the call the handlers after it read. A // part's output is not: with rtk covered, dcg read `git status` @@ -5042,6 +5102,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_first_part_without_the_shape_covers_nothing_and_is_named() { // The first part has no exec line, so the folder covers nothing, // even when a later part runs a handler's command: rune reads the @@ -5239,6 +5303,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_matcher_covers_nothing() { let mixed = mixed_install(); let report = &mixed.prepared.report; @@ -5263,6 +5331,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_compound_line_covers_nothing() { let mixed = mixed_install(); let report = &mixed.prepared.report; @@ -5363,6 +5435,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_gone_dispatcher_entry_an_earlier_install_adopted_is_named() { let home = owner_home(STOP_PARTS); let dispatcher = "sh ~/.config/just/hook Stop"; @@ -5526,6 +5602,10 @@ mod tests { const PLAIN_ENTRY: &str = "sh ~/.config/just/hook Stop"; #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn an_entry_with_a_key_rune_does_not_read_covers_nothing() { // Claude reads `if`, `args`, and `async` on a hook, and each // changes whether and how the command runs. Install names the key. @@ -5605,6 +5685,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_firing_covers_nothing_unless_home_and_the_harness_folder_are_install_s() { let installed = installed(&json!({"type": "command", "command": PLAIN_ENTRY})); let home = installed.home.path(); @@ -5660,6 +5744,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_handler_that_is_not_the_recorded_one_is_not_covered() { let installed = installed(&json!({"type": "command", "command": PLAIN_ENTRY})); let home = installed.home.path(); @@ -5728,6 +5816,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn one_firing_reads_the_table_the_script_and_the_parts_once() { let installed = installed(&json!({"type": "command", "command": PLAIN_ENTRY})); let home = installed.home.path(); @@ -5747,6 +5839,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_cover_that_holds_past_the_budget_still_skips_its_handler() { let installed = installed(&json!({"type": "command", "command": PLAIN_ENTRY})); let home = installed.home.path().to_path_buf(); @@ -5784,6 +5880,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn the_slot_is_the_entry_s_place_in_the_table_install_writes() { // An adopted entry before the dispatcher goes at this install, so // the dispatcher's slot is read from the table as written, and @@ -5939,6 +6039,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_firing_whose_sh_is_not_bin_sh_runs_every_handler() { let installed = installed(&json!({"type": "command", "command": "/bin/sh ~/.config/just/hook Stop"})); @@ -5981,6 +6085,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_folder_past_a_limit_covers_nothing_at_install_and_at_the_firing() { let installed = installed(&json!({"type": "command", "command": PLAIN_ENTRY})); let home = installed.home.path(); @@ -6068,6 +6176,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_first_part_with_an_unquoted_glob_covers_nothing_and_a_later_one_blocks_nothing() { // `b[ab]` names one word to rune and the files it matches to the // shell, so a part that holds one has no shape rune reads. First @@ -6135,6 +6247,10 @@ mod tests { const SNAPSHOT_WITH_COMMENT: &str = "#!/bin/sh\n# Snapshot the footprint so the ± segment and review see the turn.\n[ -f \"$HOME/.config/just/claude/turn/checkpoint\" ] || exit 0\nexec sh \"$HOME/.config/just/claude/turn/checkpoint\" snapshot\n"; #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_comment_in_a_later_part_keeps_the_handler_it_runs_named() { // The shell runs no comment, so the message about a later part // drops it before the text is checked: the `±` keeps turn named. @@ -6179,6 +6295,10 @@ mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_later_part_that_cannot_be_read_is_named_as_unreadable() { // A `±` on a line that runs is text rune does not read. The part // is named as unreadable, for no handler, and blocks nothing. diff --git a/src/cli/hook/legacy.rs b/src/cli/hook/legacy.rs index 107eb9cb..b26c5488 100644 --- a/src/cli/hook/legacy.rs +++ b/src/cli/hook/legacy.rs @@ -260,8 +260,8 @@ pub(crate) fn is_shell(word: &str) -> bool { /// The canonical path of `path` when it is the system `sh`: the file /// `/bin/sh` is, after symlinks. fn canonical_sh(path: &Path) -> Option { - let canonical = fs::canonicalize(path).ok()?; - (fs::canonicalize(SYSTEM_SH).ok()? == canonical).then_some(canonical) + let canonical = rune::folders::canonicalize(path).ok()?; + (rune::folders::canonicalize(SYSTEM_SH).ok()? == canonical).then_some(canonical) } /// The shell `word` names, as the shell that runs the line finds it: @@ -756,6 +756,10 @@ pub(crate) mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn the_dispatcher_is_read_only_in_its_exact_shapes() { let home = Path::new("/Users/x"); let of = |c: &str| dispatcher(&w(&expand_home_in(c, home))); @@ -824,6 +828,10 @@ pub(crate) mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_direct_script_needs_exactly_bin_sh_in_its_shebang() { let dir = tempfile::tempdir().unwrap(); let script = dir.path().join("hook"); @@ -985,6 +993,10 @@ pub(crate) mod tests { } #[test] + #[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" + )] fn a_part_has_one_exec_line_and_at_most_one_guard() { let home = tempfile::tempdir().unwrap(); let bin = home.path().join(".local").join("bin"); diff --git a/src/cli/hook/mod.rs b/src/cli/hook/mod.rs index 742d5933..40d7fca3 100644 --- a/src/cli/hook/mod.rs +++ b/src/cli/hook/mod.rs @@ -207,7 +207,7 @@ pub(crate) struct InstallTarget { impl InstallTarget { /// Resolve the home and apply the folder rule to `requested`. pub(crate) fn select(requested: &[Harness]) -> Result { - let home = dirs::home_dir() + let home = rune::folders::home_dir() .ok_or_else(|| Error::new(ErrorKind::Config, "cannot resolve home directory"))?; if live_home_in_proof(&home) { return Err(Error::new( diff --git a/src/cli/hook/publish.rs b/src/cli/hook/publish.rs index 2d2181be..79113384 100644 --- a/src/cli/hook/publish.rs +++ b/src/cli/hook/publish.rs @@ -297,7 +297,7 @@ impl Lock { for dir in given { let dir = std::path::absolute(dir).map_err(|e| io(dir, &e))?; fs::create_dir_all(&dir).map_err(|e| io(&dir, &e))?; - dirs.push(fs::canonicalize(&dir).map_err(|e| io(&dir, &e))?); + dirs.push(rune::folders::canonicalize(&dir).map_err(|e| io(&dir, &e))?); } dirs.sort(); dirs.dedup(); diff --git a/src/cli/hook/retire.rs b/src/cli/hook/retire.rs index 985cf234..b7e1efce 100644 --- a/src/cli/hook/retire.rs +++ b/src/cli/hook/retire.rs @@ -9,7 +9,6 @@ //! but neither adds days on which an install ran. use std::collections::BTreeSet; -use std::fs; use std::path::{Path, PathBuf}; use chrono::{DateTime, Utc}; @@ -56,7 +55,7 @@ pub(crate) fn fresh(path: &Path, now: DateTime, install: u64) -> Retired { /// A path as the file system names it, or as given when it is gone. pub(crate) fn canonical(path: &Path) -> PathBuf { - fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) + rune::folders::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) } fn keys(paths: &BTreeSet) -> BTreeSet { diff --git a/src/cli/hook/sandbox_guard/mod.rs b/src/cli/hook/sandbox_guard/mod.rs index 5f6a94e0..1f44d463 100644 --- a/src/cli/hook/sandbox_guard/mod.rs +++ b/src/cli/hook/sandbox_guard/mod.rs @@ -26,6 +26,7 @@ mod shell; #[cfg(test)] mod tests; +use rune::folders::Canonical as _; use std::path::{Path, PathBuf}; use rune::hooks::Harness; @@ -180,7 +181,7 @@ pub(crate) fn guard(payload: &HandlerPayload, args: &[String]) -> Result) -> Option { cwd?.join(manifest) }; let folder = manifest.parent()?; - let folder = folder - .canonicalize() - .unwrap_or_else(|_| folder.to_path_buf()); + let folder = folder.canonical().unwrap_or_else(|_| folder.to_path_buf()); let (checkout, config) = configured_target_dir(&folder)?; if cwd.is_some_and(|cwd| { - cwd.canonicalize() + cwd.canonical() .unwrap_or_else(|_| cwd.to_path_buf()) .starts_with(&checkout) }) { diff --git a/src/cli/hook/sandbox_guard/tests.rs b/src/cli/hook/sandbox_guard/tests.rs index 2cb97b26..d4c0ada4 100644 --- a/src/cli/hook/sandbox_guard/tests.rs +++ b/src/cli/hook/sandbox_guard/tests.rs @@ -2,6 +2,7 @@ //! owner's `sandbox.excludedCommands` of 2026-10-22, cut to the tools the //! guard exists for. +use rune::folders::Canonical as _; use serde_json::json; use super::shell::parse; @@ -460,6 +461,10 @@ fn checkout(config: Option<&str>) -> (tempfile::TempDir, PathBuf) { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn a_manifest_path_under_a_configured_target_dir_gets_advice() { let (dir, ws) = checkout(Some("[build]\ntarget-dir = \"target\"\n")); let manifest = ws.join("Cargo.toml"); @@ -482,12 +487,8 @@ fn a_manifest_path_under_a_configured_target_dir_gets_advice() { assert_eq!(result.effect, Effect::Pass, "{line}"); assert_eq!(result.context.len(), 1, "{line}: {:?}", result.context); let advice = &result.context[0]; - let folder = ws.canonicalize().unwrap(); - let config = dir - .path() - .canonicalize() - .unwrap() - .join(".cargo/config.toml"); + let folder = ws.canonical().unwrap(); + let config = dir.path().canonical().unwrap().join(".cargo/config.toml"); assert!( advice.contains(&format!("`{}`", config.display())), "{advice}" diff --git a/src/cli/hook/wrap.rs b/src/cli/hook/wrap.rs index 9cffdeb8..f18959d0 100644 --- a/src/cli/hook/wrap.rs +++ b/src/cli/hook/wrap.rs @@ -21,6 +21,7 @@ //! nothing and says so, since the turn may be unfinished. The change's //! design file maps each part to the review finding it closes. +use rune::folders::Canonical as _; use std::collections::{BTreeMap, BTreeSet}; use std::fs::{self, File}; use std::path::{Path, PathBuf}; @@ -528,7 +529,7 @@ pub(crate) fn session_key(harness: Harness, session_id: Option<&str>) -> String /// The nearest ancestor of `cwd` that holds a `.jj/` directory: the jj /// workspace root, found without a process. fn workspace_root(cwd: &Path) -> Option { - let start = cwd.canonicalize().ok()?; + let start = cwd.canonical().ok()?; start .ancestors() .find(|dir| dir.join(".jj").is_dir()) diff --git a/src/cli/hook/wrap/tests.rs b/src/cli/hook/wrap/tests.rs index e13be22c..b49df0fe 100644 --- a/src/cli/hook/wrap/tests.rs +++ b/src/cli/hook/wrap/tests.rs @@ -401,7 +401,7 @@ fn a_tool_event_registers_the_session_in_the_workspace_its_file_is_in() { ); assert_eq!( armed_roots(&payload, None), - [root.path().canonicalize().unwrap()].into_iter().collect() + [root.path().canonical().unwrap()].into_iter().collect() ); let unrelated = write_payload(elsewhere.path(), &elsewhere.path().join("x")); assert!(armed_roots(&unrelated, None).is_empty()); @@ -441,11 +441,15 @@ fn a_session_is_alone_with_its_own_key_or_an_empty_set_and_never_as_unknown() { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn a_shell_command_registers_the_session_in_every_workspace_it_names() { let root = armed_root(); let elsewhere = tempfile::tempdir().unwrap(); let here = root.path().display().to_string(); - let only_root: BTreeSet = [root.path().canonicalize().unwrap()].into_iter().collect(); + let only_root: BTreeSet = [root.path().canonical().unwrap()].into_iter().collect(); // A `cd` into the workspace, then an edit by a relative path. No // snapshot runs on `tool.after`, so no jj. let payload = bash_payload( @@ -496,6 +500,10 @@ fn a_shell_command_registers_the_session_in_every_workspace_it_names() { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn the_paths_a_command_names_come_from_its_words_without_a_shell() { let home = Path::new("/home/owner"); let base = Path::new("/work"); @@ -553,7 +561,7 @@ fn the_workspace_root_is_the_nearest_ancestor_with_a_jj_directory() { std::fs::create_dir_all(root.join("src/deep")).unwrap(); assert_eq!( workspace_root(&root.join("src/deep")), - Some(root.canonicalize().unwrap()) + Some(root.canonical().unwrap()) ); assert_eq!(workspace_root(dir.path()), None); } @@ -561,7 +569,7 @@ fn the_workspace_root_is_the_nearest_ancestor_with_a_jj_directory() { #[test] fn the_wrapper_is_armed_by_the_payload_directory_or_the_project_directory() { let root = armed_root(); - let canonical = root.path().canonicalize().unwrap(); + let canonical = root.path().canonical().unwrap(); assert_eq!( armed_in(&payload("turn.finish", Some(root.path())), None), Some(canonical.clone()) diff --git a/src/cli/init/mod.rs b/src/cli/init/mod.rs index 15e40a73..23ea724f 100644 --- a/src/cli/init/mod.rs +++ b/src/cli/init/mod.rs @@ -1,4 +1,5 @@ use rune::error::{Error, ErrorKind}; +use rune::folders::Canonical as _; use rune::manifest; use rune::ontology; use rune::result::{ActionResult, DeployedFile, SkipReason, SkippedFile}; @@ -503,20 +504,20 @@ fn dry_run_result( }; if !will_write { action.skipped.push(SkippedFile { - target: relative.to_string_lossy().into_owned(), + target: rune::manifest::slash_lossy(relative), provider: template.layer.clone(), reason: SkipReason::AlreadyExists, }); continue; } action.installed.push(DeployedFile { - source: template - .source - .strip_prefix(skeleton) - .unwrap_or(&template.source) - .to_string_lossy() - .into_owned(), - target: relative.to_string_lossy().into_owned(), + source: rune::manifest::slash_lossy( + template + .source + .strip_prefix(skeleton) + .unwrap_or(&template.source), + ), + target: rune::manifest::slash_lossy(relative), provider: template.layer.clone(), }); } @@ -590,7 +591,7 @@ fn embedded_skeleton_cache_name() -> String { /// skeleton root and no network. Extraction lands in a per-version cache /// directory and is skipped when already present. fn materialize_embedded_skeleton() -> Result { - let cache_base = dirs::cache_dir().ok_or_else(|| { + let cache_base = rune::folders::cache_dir().ok_or_else(|| { Error::new( ErrorKind::Config, "cannot resolve the user cache directory; set a skeleton root with `rune config set skeleton `".to_string(), @@ -810,7 +811,7 @@ fn bind_quest_if_requested(destination: &Path, requested: bool) -> Result Result<(PathBuf, String, Option), Error> { - let canonical_root = configured_root.canonicalize().map_err(|error| { + let canonical_root = configured_root.canonical().map_err(|error| { Error::new( ErrorKind::Io, format!("cannot resolve {}: {error}", configured_root.display()), @@ -938,7 +939,7 @@ fn resolve_project_context( // (resolving `.` and `..` components) before the containment check. // The root itself is not "under" the root. let canonical_root = targets_root - .canonicalize() + .canonical() .unwrap_or_else(|_| targets_root.clone()); let normalized_destination = lexically_normalized(&destination); let under_workshop_root = (normalized_destination.starts_with(&targets_root) @@ -975,7 +976,7 @@ fn resolve_destination( if is_explicit_path(requested, &expanded) { if expanded.is_dir() { return expanded - .canonicalize() + .canonical() .map(|path| (path, None)) .map_err(|error| { Error::new( @@ -1019,16 +1020,16 @@ fn write_templates( let mut installed_paths = Vec::new(); for (relative, template) in templates { let target_path = destination.join(&relative); - let target_display = relative.to_string_lossy().into_owned(); + let target_display = rune::manifest::slash_lossy(&relative); if relative == Path::new(".gitignore") && target_path.is_file() { if append_missing_gitignore_entries(&target_path, &template.contents)? { action.installed.push(DeployedFile { - source: template - .source - .strip_prefix(skeleton) - .unwrap_or(&template.source) - .to_string_lossy() - .into_owned(), + source: rune::manifest::slash_lossy( + template + .source + .strip_prefix(skeleton) + .unwrap_or(&template.source), + ), target: target_display, provider: template.layer, }); @@ -1066,12 +1067,12 @@ fn write_templates( make_executable_if_needed(&target_path, &template.contents)?; installed_paths.push(relative.clone()); action.installed.push(DeployedFile { - source: template - .source - .strip_prefix(skeleton) - .unwrap_or(&template.source) - .to_string_lossy() - .into_owned(), + source: rune::manifest::slash_lossy( + template + .source + .strip_prefix(skeleton) + .unwrap_or(&template.source), + ), target: target_display, provider: template.layer, }); @@ -1710,7 +1711,7 @@ fn is_os_junk(filename: &str) -> bool { fn resolve_module_name(module_root: &Path) -> String { module_root - .canonicalize() + .canonical() .unwrap_or_else(|_| module_root.to_path_buf()) .file_name() .unwrap_or_default() diff --git a/src/cli/init/tests.rs b/src/cli/init/tests.rs index 763fc288..9d6f54f7 100644 --- a/src/cli/init/tests.rs +++ b/src/cli/init/tests.rs @@ -146,6 +146,7 @@ fn setup_prompt_is_explicit_and_defaults_to_no() { } #[test] +#[cfg_attr(windows, ignore = "runs make")] fn setup_failure_remains_a_reported_optional_outcome() { let project = TempDir::new().unwrap(); std::fs::write( diff --git a/src/cli/interface/mod.rs b/src/cli/interface/mod.rs index 75224c20..811daee2 100644 --- a/src/cli/interface/mod.rs +++ b/src/cli/interface/mod.rs @@ -88,7 +88,7 @@ fn known(name: &str) -> Result<(), Error> { /// T3 Code's settings, read from this machine. fn read_settings() -> Result { - let home = dirs::home_dir() + let home = rune::folders::home_dir() .ok_or_else(|| Error::new(ErrorKind::Config, "cannot resolve home directory"))?; let path = t3code::settings_path(&home, std::env::var_os("T3CODE_HOME").as_deref()); Settings::read(&path) diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 365e4dfe..e903c297 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -72,6 +72,7 @@ mod update_check; use clap::{Parser, Subcommand}; use rune::error::{Error, ErrorKind}; +use rune::folders::Canonical as _; use rune::result::ActionResult; use std::path::PathBuf as QueuePathBuf; use std::{ffi::OsString, fmt::Write as _}; @@ -86,6 +87,9 @@ const BUILD_VERSION: &str = concat!( #[derive(Parser)] #[command(name = "rune", about = "Rune Deck toolkit", version = BUILD_VERSION)] +// Windows starts the program as `rune.exe`, and the usage line would say +// so. The command is `rune` in every shell there, as it is in the docs. +#[cfg_attr(windows, command(bin_name = "rune"))] pub(crate) struct Cli { #[command(subcommand)] command: Option, @@ -3376,7 +3380,7 @@ pub(crate) fn print_fatal(error: &E) { } pub(crate) fn resolved_path(path: &std::path::Path) -> std::path::PathBuf { - path.canonicalize() + path.canonical() .or_else(|_| std::path::absolute(path)) .unwrap_or_else(|_| path.to_path_buf()) } diff --git a/src/cli/ontology.rs b/src/cli/ontology.rs index 7d5e06d9..8037df58 100644 --- a/src/cli/ontology.rs +++ b/src/cli/ontology.rs @@ -437,10 +437,12 @@ mod tests { #[test] fn config_read_error_has_no_repair_command() { + // A folder where the file belongs cannot be read as text on any + // platform. A path under a regular file would not do: Windows + // reports it as not found, which is an absent config and no error. let directory = tempfile::tempdir().expect("tempdir"); - let parent_file = directory.path().join("not-a-directory"); - std::fs::write(&parent_file, "fixture").expect("parent fixture"); - let path = parent_file.join("config.yaml"); + let path = directory.path().join("config.yaml"); + std::fs::create_dir(&path).expect("a folder at the config path"); let error = read_config_document(&path).expect_err("read must fail"); diff --git a/src/cli/policy.rs b/src/cli/policy.rs index d6aca4ef..6602f8a3 100644 --- a/src/cli/policy.rs +++ b/src/cli/policy.rs @@ -100,7 +100,7 @@ scopes: fn scene() -> (tempfile::TempDir, PathBuf, Reader) { let temp = tempfile::tempdir().unwrap(); - let dir = std::fs::canonicalize(temp.path()).unwrap(); + let dir = rune::folders::canonicalize(temp.path()).unwrap(); let home = dir.join("home"); std::fs::create_dir_all(home.join("Atlas/notes")).unwrap(); std::fs::create_dir_all(home.join("Agents/deck")).unwrap(); diff --git a/src/cli/process/tests.rs b/src/cli/process/tests.rs index 72759344..422d5c56 100644 --- a/src/cli/process/tests.rs +++ b/src/cli/process/tests.rs @@ -13,6 +13,7 @@ fn process_request_has_no_default_timeout() { } #[test] +#[cfg_attr(windows, ignore = "starts /bin/sh and signals its process group")] fn process_captures_stdout_stderr_and_exit_code() { let request = shell_request("printf answer; printf warning >&2; exit 7"); let output = run_process_request(&request).expect("process output"); @@ -23,6 +24,7 @@ fn process_captures_stdout_stderr_and_exit_code() { } #[test] +#[cfg_attr(windows, ignore = "starts /bin/sh and signals its process group")] fn process_captures_stdin_without_deadlock() { let mut request = ProcessRequest::new("/bin/cat"); request.stdin = Some(b"question\n".to_vec()); @@ -33,6 +35,7 @@ fn process_captures_stdin_without_deadlock() { } #[test] +#[cfg_attr(windows, ignore = "starts /bin/sh and signals its process group")] fn process_preserves_exit_when_child_closes_stdin_early() { let mut request = shell_request("exit 23"); request.stdin = Some(vec![b'x'; DEFAULT_OUTPUT_LIMIT_BYTES * 2]); @@ -42,6 +45,7 @@ fn process_preserves_exit_when_child_closes_stdin_early() { } #[test] +#[cfg_attr(windows, ignore = "starts /bin/sh and signals its process group")] fn process_reports_signal_termination() { let request = shell_request("kill -TERM $$"); let output = run_process_request(&request).expect("process output"); @@ -54,6 +58,7 @@ fn process_reports_signal_termination() { } #[test] +#[cfg_attr(windows, ignore = "starts /bin/sh and signals its process group")] fn process_timeout_uses_grace_then_reports_timeout_with_partial_output() { let mut request = shell_request("printf partial; printf 'still going' >&2; trap '' TERM; sleep 5"); @@ -75,6 +80,7 @@ fn process_timeout_uses_grace_then_reports_timeout_with_partial_output() { } #[test] +#[cfg_attr(windows, ignore = "starts /bin/sh and signals its process group")] fn process_drains_output_after_limit_is_crossed() { let mut request = shell_request("i=0; while [ \"$i\" -lt 100 ]; do printf 0123456789; i=$((i + 1)); done"); @@ -98,6 +104,7 @@ fn process_drains_output_after_limit_is_crossed() { } #[test] +#[cfg_attr(windows, ignore = "starts /bin/sh and signals its process group")] fn process_cleanup_kills_a_descendant_that_holds_the_pipe() { // The leader exits at once; a background child keeps stdout open. The // supervisor kills the group after the grace period instead of waiting @@ -117,6 +124,7 @@ fn process_cleanup_kills_a_descendant_that_holds_the_pipe() { } #[test] +#[cfg_attr(windows, ignore = "starts /bin/sh and signals its process group")] fn a_forwarded_signal_leaves_the_group_its_grace_before_the_kill() { // The signal that stopped the leader is recorded already when the // drain starts. A group member that finishes within the grace is @@ -170,6 +178,7 @@ const DETACHED_SLEEP: &str = "if command -v setsid >/dev/null 2>&1; then setsid else perl -e 'use POSIX; setsid(); sleep 10' & fi;"; #[test] +#[cfg_attr(windows, ignore = "starts /bin/sh and signals its process group")] fn process_timeout_ends_promptly_when_a_setsid_descendant_holds_the_pipes() { // The leader ignores the deadline's SIGTERM and a survivor outside the // group holds every pipe. The group kill ends the leader, the bounded @@ -195,6 +204,7 @@ fn process_timeout_ends_promptly_when_a_setsid_descendant_holds_the_pipes() { } #[test] +#[cfg_attr(windows, ignore = "starts /bin/sh and signals its process group")] fn process_exit_ends_promptly_when_a_setsid_descendant_holds_stdin() { // The leader exits before it reads a stdin larger than the pipe, and a // survivor outside the group keeps the read end open, so the writer @@ -215,6 +225,7 @@ fn process_exit_ends_promptly_when_a_setsid_descendant_holds_stdin() { } #[test] +#[cfg_attr(windows, ignore = "starts /bin/sh and signals its process group")] fn process_request_removes_inherited_automation_mode() { let mut request = shell_request("printf %s \"${HARNESS_AUTOMATED-unset}\""); request.env = vec![(OsString::from("HARNESS_AUTOMATED"), OsString::from("1"))]; diff --git a/src/cli/proof/mod.rs b/src/cli/proof/mod.rs index 16243a81..829a4f37 100644 --- a/src/cli/proof/mod.rs +++ b/src/cli/proof/mod.rs @@ -73,7 +73,7 @@ pub fn execute(action: &ProofAction) -> Result { /// The repository root as an absolute canonical path, so scenes that /// change directory and `RUNE_PROOF_ROOT` both resolve. fn canonical(source: &str) -> Result { - fs::canonicalize(source).map_err(|error| Error::io(format!("{source}: {error}"))) + rune::folders::canonicalize(source).map_err(|error| Error::io(format!("{source}: {error}"))) } /// The proof whose frontmatter names `change`. @@ -584,7 +584,8 @@ fn jj_owns(root: &Path) -> bool { let Some(git_root) = vcs(root, "git", &["rev-parse", "--show-toplevel"]) else { return true; }; - let canonical = |path: &str| fs::canonicalize(path).unwrap_or_else(|_| PathBuf::from(path)); + let canonical = + |path: &str| rune::folders::canonicalize(path).unwrap_or_else(|_| PathBuf::from(path)); canonical(&jj_root).starts_with(canonical(&git_root)) } diff --git a/src/cli/proof/runner.rs b/src/cli/proof/runner.rs index 8089c1ee..d44b4eea 100644 --- a/src/cli/proof/runner.rs +++ b/src/cli/proof/runner.rs @@ -13,6 +13,7 @@ //! directory and are read through the handle the runner holds, so a //! command cannot rewrite what it printed. +use rune::folders::Canonical as _; use std::fs::{self, File}; use std::io::{Read as _, Seek as _, SeekFrom}; use std::path::{Path, PathBuf}; @@ -189,7 +190,7 @@ fn marker(capture_dir: &Path) -> PathBuf { /// line, in a file nobody else made. fn write_marker(capture_dir: &Path) -> Result<(), String> { use std::io::Write as _; - let home = dirs::home_dir().map_or_default(|home| home.display().to_string()); + let home = rune::folders::home_dir().map_or_default(|home| home.display().to_string()); File::options() .write(true) .create_new(true) @@ -217,7 +218,7 @@ fn working_directory( } let canonical = root .join(target) - .canonicalize() + .canonical() .map_err(|error| format!("`cd {target}`: {error}"))?; if !canonical.starts_with(root) { return Err(format!("`cd {target}` leaves the repository")); @@ -371,7 +372,7 @@ mod tests { } fn root() -> PathBuf { - std::env::current_dir().unwrap().canonicalize().unwrap() + std::env::current_dir().unwrap().canonical().unwrap() } #[test] @@ -432,12 +433,12 @@ mod tests { #[test] fn a_scene_has_a_marker_while_it_runs_and_its_own_state() { - let Some(home) = dirs::home_dir() else { + let Some(home) = rune::folders::home_dir() else { return; }; let (home, pid) = (home.display(), std::process::id()); let s = scene(&format!( - "$ sh -c 'echo \"$RUNE_PROOF_SCENE\"; cat \"$RUNE_PROOF_SCENE\"; test \"$RUNE_STATE_DIR\" != \"$HOME/.local/state/rune\" && echo own-state'\n[..]/scene\n{pid}\n{home}\nown-state" + "$ sh -c 'echo \"$RUNE_PROOF_SCENE\"; cat \"$RUNE_PROOF_SCENE\"; test \"$RUNE_STATE_DIR\" != \"$HOME/.local/state/rune\" && echo own-state'\n[..]scene\n{pid}\n{home}\nown-state" )); let run = run_scene(&s, &root()); assert!(run.passed, "{:?}", run.failure); @@ -446,7 +447,11 @@ mod tests { .section .lines() .map(str::trim) - .find(|line| line.ends_with("/scene")) + .find(|line| { + Path::new(line) + .file_name() + .is_some_and(|name| name == "scene") + }) .expect("the scene printed its marker"); assert!(!Path::new(marker).exists(), "{marker}"); } @@ -481,7 +486,7 @@ mod tests { ); let dir = tempfile::tempdir().unwrap(); let s = scene("$ cd ..\n$ ls"); - let run = run_scene(&s, &dir.path().canonicalize().unwrap()); + let run = run_scene(&s, &dir.path().canonical().unwrap()); assert!(run.failure.unwrap().contains("leaves the repository")); } } diff --git a/src/cli/provenance/mod.rs b/src/cli/provenance/mod.rs index 7566b421..6fe4cb6d 100644 --- a/src/cli/provenance/mod.rs +++ b/src/cli/provenance/mod.rs @@ -151,7 +151,7 @@ pub fn execute( /// that contains `module.yaml`, marking a Rune source repository. The start /// is canonicalized first so a relative target still walks to an absolute root. fn find_module_root(start: &Path) -> Option { - let absolute = fs::canonicalize(start).ok()?; + let absolute = rune::folders::canonicalize(start).ok()?; let mut current = if absolute.is_file() { absolute.parent()?.to_path_buf() } else { diff --git a/src/cli/provenance/scan.rs b/src/cli/provenance/scan.rs index 4ceb3cf0..359229b9 100644 --- a/src/cli/provenance/scan.rs +++ b/src/cli/provenance/scan.rs @@ -115,11 +115,7 @@ fn collect_recursive( continue; } - let relative = path - .strip_prefix(target_root) - .unwrap_or(&path) - .to_string_lossy() - .to_string(); + let relative = rune::manifest::slash_lossy(path.strip_prefix(target_root).unwrap_or(&path)); let Ok(sidecar) = read_sidecar(&super::resolve_sidecar_path(&path)) else { orphans.push(relative); diff --git a/src/cli/provider_cmd/tests.rs b/src/cli/provider_cmd/tests.rs index 5cd8871e..42f6c124 100644 --- a/src/cli/provider_cmd/tests.rs +++ b/src/cli/provider_cmd/tests.rs @@ -76,6 +76,9 @@ fn explain_report_has_the_required_json_fields() { fn each_non_current_state_has_a_fix_or_review_command() { let root = tempfile::tempdir().unwrap(); let target = root.path().join(".agents"); + // The command quotes the target as a shell needs it: a Windows path + // holds `\` and `:`, so it goes in quotes there. + let quoted_target = crate::cli::shell_quote(&target.to_string_lossy()); for (state, recommended_action, expected) in [ ( DeploymentState::Disabled, @@ -95,12 +98,12 @@ fn each_non_current_state_has_a_fix_or_review_command() { ( DeploymentState::NeedsRepair, RecommendedAction::Repair, - format!("rune repair --target {}", target.display()), + format!("rune repair --target {quoted_target}"), ), ( DeploymentState::Modified, RecommendedAction::Review, - format!("rune doctor --target {}", target.display()), + format!("rune doctor --target {quoted_target}"), ), ] { let detection = ProviderDetection { diff --git a/src/cli/queue/ledger.rs b/src/cli/queue/ledger.rs index afd945f8..81abb9c6 100644 --- a/src/cli/queue/ledger.rs +++ b/src/cli/queue/ledger.rs @@ -148,7 +148,7 @@ pub(crate) fn fold(events: &[Event]) -> Vec { /// `~/.rune/postbox.tsv`. pub(crate) fn path() -> Result { - dirs::home_dir() + rune::folders::home_dir() .map(|home| rune::consumer::user_directory(&home).join(FILE_NAME)) .ok_or_else(|| "cannot find the home directory for the postbox".to_string()) } diff --git a/src/cli/run/artifacts.rs b/src/cli/run/artifacts.rs index 781f519d..305daa96 100644 --- a/src/cli/run/artifacts.rs +++ b/src/cli/run/artifacts.rs @@ -39,7 +39,7 @@ pub(crate) fn agy_data_dir(invocation: &SurfaceInvocation) -> Option { .find(|(name, _)| *name == key) .map(|(_, value)| PathBuf::from(value)) .or_else(|| std::env::var_os(AGY_DATA_DIR).map(PathBuf::from)) - .or_else(|| dirs::home_dir().map(|home| home.join(AGY_DEFAULT_DATA_DIR))) + .or_else(|| rune::folders::home_dir().map(|home| home.join(AGY_DEFAULT_DATA_DIR))) } /// The folder agy fills for one conversation. @@ -59,7 +59,7 @@ pub(crate) fn find_artifacts(folder: &Path, since: SystemTime) -> Vec { .map(|entry| entry.path()) .filter(|path| path.is_file() && !is_bookkeeping(path)) .filter(|path| modified_at_or_after(path, since)) - .filter_map(|path| std::fs::canonicalize(path).ok()) + .filter_map(|path| rune::folders::canonicalize(path).ok()) .collect(); files.sort(); files @@ -100,7 +100,7 @@ pub(crate) fn copy_artifacts( destination.display() ) })?; - let destination = std::fs::canonicalize(destination).map_err(|error| { + let destination = rune::folders::canonicalize(destination).map_err(|error| { format!( "cannot resolve artifacts directory {}: {error}", destination.display() diff --git a/src/cli/run/mod.rs b/src/cli/run/mod.rs index ab8364ec..74ec4762 100644 --- a/src/cli/run/mod.rs +++ b/src/cli/run/mod.rs @@ -1022,7 +1022,7 @@ fn read_optional_text_file(path: Option<&Path>, label: &str) -> Result Result { - let repository = std::fs::canonicalize(path) + let repository = rune::folders::canonicalize(path) .map_err(|error| format!("cannot resolve repository {}: {error}", path.display()))?; if !repository.is_dir() { return Err(format!( diff --git a/src/cli/run/output.rs b/src/cli/run/output.rs index 7008da59..6718830e 100644 --- a/src/cli/run/output.rs +++ b/src/cli/run/output.rs @@ -171,21 +171,21 @@ pub(crate) fn caller_repository_root() -> Option { /// hidden-folder rule is judged from the closest one. fn permitted_roots(repository: Option<&Path>) -> Vec<(&'static str, PathBuf)> { let mut roots = Vec::new(); - if let Some(root) = repository.and_then(|path| std::fs::canonicalize(path).ok()) { + if let Some(root) = repository.and_then(|path| rune::folders::canonicalize(path).ok()) { roots.push(("the repository", root)); } for (label, path) in [ ("the temporary directory", std::env::temp_dir()), ("the temporary directory", PathBuf::from("/tmp")), ] { - if let Ok(root) = std::fs::canonicalize(&path) + if let Ok(root) = rune::folders::canonicalize(&path) && !roots.iter().any(|(_, known)| *known == root) { roots.push((label, root)); } } if let Ok(state) = crate::cli::sign::state_dir() - && let Ok(root) = std::fs::canonicalize(&state) + && let Ok(root) = rune::folders::canonicalize(&state) && !roots.iter().any(|(_, known)| *known == root) { roots.push(("the rune state directory", root)); @@ -216,7 +216,7 @@ pub(crate) fn accept(path: &Path, repository: Option<&Path>) -> Result PathBuf { _ => marker, } }; - std::fs::canonicalize(&store).unwrap_or(store) + rune::folders::canonicalize(&store).unwrap_or(store) } /// The folder under the state directory that holds every workspace of one @@ -782,7 +782,7 @@ fn find_marked(root: &Path, description: &str, start_operation: &str) -> Result< /// exist yet is judged by where it would be created. fn resolved_location(path: &Path) -> PathBuf { for ancestor in path.ancestors() { - if let Ok(canonical) = std::fs::canonicalize(ancestor) { + if let Ok(canonical) = rune::folders::canonicalize(ancestor) { let rest = path.strip_prefix(ancestor).unwrap_or(Path::new("")); return canonical.join(rest); } @@ -796,7 +796,7 @@ fn resolved_location(path: &Path) -> PathBuf { /// harness would work inside the checkout it must not touch. fn refuse_inside_checkout(path: &Path, root: &Path) -> Result<(), String> { let location = resolved_location(path); - let checkout = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); + let checkout = rune::folders::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); if location.starts_with(&checkout) { return Err(format!( "the workspace folder {} would lie inside the checkout {}; set RUNE_STATE_DIR or XDG_STATE_HOME to a folder outside the repository, or use --mode read-only", @@ -814,7 +814,8 @@ fn subfolder_of(repository: &Path, root: &Path) -> PathBuf { if let Ok(rest) = repository.strip_prefix(root) { return rest.to_path_buf(); } - let canonical = std::fs::canonicalize(repository).unwrap_or_else(|_| repository.to_path_buf()); + let canonical = + rune::folders::canonicalize(repository).unwrap_or_else(|_| repository.to_path_buf()); canonical .strip_prefix(root) .map_or_default(Path::to_path_buf) @@ -1877,7 +1878,7 @@ mod tests { assert_eq!(main_store, secondary_store); assert_eq!( main_store, - std::fs::canonicalize(main.join(".jj/repo")).expect("canonical") + rune::folders::canonicalize(main.join(".jj/repo")).expect("canonical") ); assert_eq!(repository_id(&main_store), repository_id(&secondary_store)); assert!(repository_id(&main_store).starts_with("main-")); @@ -1903,14 +1904,14 @@ mod tests { assert_eq!(before, after); assert_eq!( before, - std::fs::canonicalize(repo.join(".git")).expect("canonical") + rune::folders::canonicalize(repo.join(".git")).expect("canonical") ); } #[test] fn detect_asks_jj_for_the_root_above_a_subfolder_and_sees_colocation() { let root = tempfile::tempdir().expect("root"); - let repo = std::fs::canonicalize(root.path()).expect("canonical root"); + let repo = rune::folders::canonicalize(root.path()).expect("canonical root"); let status = Command::new("jj") .args(["--config", "git.colocate=false", "git", "init"]) .arg(&repo) @@ -1955,7 +1956,7 @@ mod tests { #[test] fn the_initial_working_copy_of_the_added_workspace_is_the_runs_own() { let root = tempfile::tempdir().expect("root"); - let base = std::fs::canonicalize(root.path()).expect("canonical root"); + let base = rune::folders::canonicalize(root.path()).expect("canonical root"); let repo = base.join("repo"); let run_path = base.join("run"); test_jj( diff --git a/src/cli/session.rs b/src/cli/session.rs index 00a9d287..ae245be1 100644 --- a/src/cli/session.rs +++ b/src/cli/session.rs @@ -227,7 +227,7 @@ fn fatal(error: &Error, json: bool) -> i32 { /// directory; the stores by the harness variables; the excluded sessions; /// and the tools the readable copy and the backup need. pub(crate) fn config() -> Result { - let home = dirs::home_dir() + let home = rune::folders::home_dir() .ok_or_else(|| Error::new(ErrorKind::Config, "cannot resolve home directory"))?; let user = ontology::load()?; let data_dir = std::env::var_os("DATA_DIR") diff --git a/src/cli/setup.rs b/src/cli/setup.rs index c8b1de8e..95f1c004 100644 --- a/src/cli/setup.rs +++ b/src/cli/setup.rs @@ -135,7 +135,7 @@ fn build_plan(automatic: bool) -> Result { .with_code("setup.current_directory_unavailable") .with_fix_command("pwd") })?; - let home = dirs::home_dir().ok_or_else(|| { + let home = rune::folders::home_dir().ok_or_else(|| { Error::new(ErrorKind::Config, "Rune cannot resolve the home directory.") .with_code("setup.home_unavailable") .with_fix_command("printenv HOME") @@ -642,7 +642,7 @@ fn setup_error(error: &Error, code: &'static str, fix_command: &str) -> Error { /// Scan two levels under ~/Developer for directories with deck.yaml. fn discover_decks() -> Vec { - let Some(home) = dirs::home_dir() else { + let Some(home) = rune::folders::home_dir() else { return Vec::new(); }; let developer = home.join("Developer"); diff --git a/src/cli/sign/queue/mod.rs b/src/cli/sign/queue/mod.rs index 10157dcc..2b43e179 100644 --- a/src/cli/sign/queue/mod.rs +++ b/src/cli/sign/queue/mod.rs @@ -454,7 +454,7 @@ fn qualify_receipt(path: &Path, commit_id: &str) -> Result { } // The owner signs from another directory, so the record keeps the // absolute path the session named. - let absolute = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); + let absolute = rune::folders::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); Ok(Receipt { path: absolute.to_string_lossy().into_owned(), digest: store::file_digest(path)?, @@ -1642,7 +1642,7 @@ fn notify(message: &str) { } fn notification_icon() -> Option { - let directory = dirs::cache_dir()?.join("rune"); + let directory = rune::folders::cache_dir()?.join("rune"); let path = directory.join("icon.png"); if !path.is_file() { fs::create_dir_all(&directory).ok()?; diff --git a/src/cli/sign/queue/repo.rs b/src/cli/sign/queue/repo.rs index 0d0cdaa2..244b7d60 100644 --- a/src/cli/sign/queue/repo.rs +++ b/src/cli/sign/queue/repo.rs @@ -1154,7 +1154,7 @@ fn jj_path(workspace: &Path, args: &[&str]) -> Result { /// The path with symlinks resolved when it exists, as given otherwise. fn canonical(path: &Path) -> PathBuf { - std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) + rune::folders::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) } /// jj on the workspace with the git it runs pinned to `git` on PATH: the diff --git a/src/cli/sign/queue/tests.rs b/src/cli/sign/queue/tests.rs index a06528fa..6136433e 100644 --- a/src/cli/sign/queue/tests.rs +++ b/src/cli/sign/queue/tests.rs @@ -208,8 +208,7 @@ fn the_store_keeps_its_own_copy_of_a_receipt_and_removes_it_with_the_request() { .expect("the copy is kept"); assert_eq!( copy, - dir.path() - .join("queue/receipts/one.log") + rune::folders::join(dir.path(), "queue/receipts/one.log") .to_string_lossy() .as_ref() ); @@ -266,6 +265,10 @@ fn removing_a_request_without_a_copy_succeeds() { } #[test] +#[cfg_attr( + windows, + ignore = "a Windows file lock is mandatory, so the holder line cannot be read while the lock is held" +)] fn repository_lock_refuses_a_live_holder_and_releases_on_drop() { let dir = TempDir::new().expect("tempdir"); std::fs::create_dir_all(dir.path().join("locks")).expect("locks dir"); diff --git a/src/cli/sign/seal.rs b/src/cli/sign/seal.rs index 1c88ce08..25bdfa0d 100644 --- a/src/cli/sign/seal.rs +++ b/src/cli/sign/seal.rs @@ -5,7 +5,6 @@ use rune::error::{Error, ErrorKind}; use serde::{Deserialize, Serialize}; -use std::io::Read; pub(crate) const OPEN_PREFIX: &str = "open-seal: "; pub(crate) const MERGE_PREFIX: &str = "merge-seal: "; @@ -94,17 +93,29 @@ fn is_hex(value: &str, length: usize) -> bool { /// request to carry it. pub(crate) fn nonce() -> Result { let mut bytes = [0u8; NONCE_BYTES]; - std::fs::File::open("/dev/urandom") - .and_then(|mut source| source.read_exact(&mut bytes)) - .map_err(|error| { - Error::new( - ErrorKind::Io, - format!("cannot read random bytes for the seal nonce: {error}"), - ) - })?; + random_bytes(&mut bytes).map_err(|error| { + Error::new( + ErrorKind::Io, + format!("cannot read random bytes for the seal nonce: {error}"), + ) + })?; Ok(hex(&bytes)) } +/// Unix reads the kernel's random device. +#[cfg(not(windows))] +fn random_bytes(bytes: &mut [u8]) -> std::io::Result<()> { + use std::io::Read as _; + std::fs::File::open("/dev/urandom").and_then(|mut source| source.read_exact(bytes)) +} + +/// Windows has no random device to open. The system's generator answers +/// through `getrandom`. +#[cfg(windows)] +fn random_bytes(bytes: &mut [u8]) -> std::io::Result<()> { + getrandom::fill(bytes).map_err(|error| std::io::Error::other(error.to_string())) +} + pub(crate) fn hex(bytes: &[u8]) -> String { use std::fmt::Write; let mut out = String::with_capacity(bytes.len() * 2); diff --git a/src/cli/skill.rs b/src/cli/skill.rs index 691bb595..cbfa0876 100644 --- a/src/cli/skill.rs +++ b/src/cli/skill.rs @@ -39,7 +39,7 @@ pub fn show() -> i32 { pub fn install(directory: Option<&str>, json: bool) -> Result { let root = match directory { Some(directory) => PathBuf::from(directory), - None => dirs::home_dir() + None => rune::folders::home_dir() .ok_or_else(|| Error::new(ErrorKind::Config, "cannot resolve home directory"))?, }; let content = rendered(); @@ -130,7 +130,7 @@ impl InstallPlan { pub(crate) fn destinations(&self) -> Vec { self.targets .iter() - .map(|(_, base)| base.join("rune/SKILL.md")) + .map(|(_, base)| rune::folders::join(base, "rune/SKILL.md")) .collect() } @@ -151,7 +151,7 @@ impl InstallPlan { let mut kept = 0usize; let mut failing = Vec::new(); for (provider, base) in &self.targets { - let path = base.join("rune/SKILL.md"); + let path = rune::folders::join(base, "rune/SKILL.md"); match std::fs::read_to_string(&path) { Ok(existing) if existing == self.content => current += 1, Ok(existing) @@ -194,7 +194,7 @@ pub(crate) fn plan_install_with( ) -> Result { let root = match directory { Some(directory) => PathBuf::from(directory), - None => dirs::home_dir().ok_or_else(|| { + None => rune::folders::home_dir().ok_or_else(|| { Error::new(ErrorKind::Config, "cannot resolve home directory") .with_code("skill.home_unavailable") .with_fix_command("printenv HOME") diff --git a/src/cli/spec_root.rs b/src/cli/spec_root.rs index bdf12a8d..a2c3b092 100644 --- a/src/cli/spec_root.rs +++ b/src/cli/spec_root.rs @@ -24,6 +24,7 @@ pub(crate) use fallback::{ #[cfg(not(feature = "spec"))] mod fallback { use rune::error::{Error, ErrorKind}; + use rune::folders::Canonical as _; use serde::Serialize; use std::ffi::OsString; use std::path::{Component, Path, PathBuf}; @@ -44,7 +45,7 @@ mod fallback { fn resolve_roots(root: &Path) -> Result { let repository = root - .canonicalize() + .canonical() .map_err(|error| root_error("resolve repository", root, error))?; let merged = crate::cli::config::load_merged_config(root)?; let configured = crate::cli::config::source_spec_root(&merged); @@ -129,7 +130,7 @@ mod fallback { } let resolved_existing = existing - .canonicalize() + .canonical() .map_err(|error| root_error("resolve spec path", existing, error))?; if !resolved_existing.starts_with(repository) { return Err(Error::new( diff --git a/src/cli/state.rs b/src/cli/state.rs index b552ef1a..e172b209 100644 --- a/src/cli/state.rs +++ b/src/cli/state.rs @@ -13,7 +13,7 @@ pub(crate) fn dir() -> Result { if let Some(dir) = std::env::var_os("XDG_STATE_HOME").filter(|dir| !dir.is_empty()) { return Ok(PathBuf::from(dir).join("rune")); } - dirs::home_dir() + rune::folders::home_dir() .map(|home| home.join(".local/state/rune")) .ok_or_else(|| Error::new(ErrorKind::Config, "cannot resolve home directory")) } diff --git a/src/cli/surface/cursor.rs b/src/cli/surface/cursor.rs index 98428064..c9768280 100644 --- a/src/cli/surface/cursor.rs +++ b/src/cli/surface/cursor.rs @@ -375,7 +375,7 @@ fn config_dir(invocation: &SurfaceInvocation) -> Option { } else { lookup("HOME") .map(PathBuf::from) - .or_else(dirs::home_dir)? + .or_else(rune::folders::home_dir)? .join(".cursor") }; Some(invocation.repository.join(directory)) diff --git a/src/cli/surface/mod.rs b/src/cli/surface/mod.rs index d470fdfe..294b728a 100644 --- a/src/cli/surface/mod.rs +++ b/src/cli/surface/mod.rs @@ -1870,7 +1870,7 @@ pub(crate) fn grok_model_env_key(source: &Path, model: &str) -> GrokKeyChoice { /// The owner's grok configuration file. pub(crate) fn grok_config_source() -> Result { - dirs::home_dir() + rune::folders::home_dir() .map(|home| home.join(".grok/config.toml")) .ok_or_else(|| SurfaceFailure::Io("cannot resolve home directory".to_string())) } @@ -1894,7 +1894,7 @@ pub(crate) fn prepare_clean_state( model: Option<&str>, env: &[(OsString, OsString)], ) -> Result<(), SurfaceFailure> { - let home = dirs::home_dir() + let home = rune::folders::home_dir() .ok_or_else(|| SurfaceFailure::Io("cannot resolve home directory".to_string()))?; match surface { Surface::Cursor => cursor::prepare_clean_state(root, cursor::has_api_key(env)), @@ -2024,7 +2024,7 @@ fn process_request( // reads first. The shim, and its sandbox, stay in the loop. if std::env::var_os("HARNESS_REAL_BIN_DIR").is_none() && let Some(real_bin) = - dirs::home_dir().and_then(|home| grok_install_dir(&home)) + rune::folders::home_dir().and_then(|home| grok_install_dir(&home)) { request .env diff --git a/src/cli/surface/tests.rs b/src/cli/surface/tests.rs index 36e26dc2..cd3cd1be 100644 --- a/src/cli/surface/tests.rs +++ b/src/cli/surface/tests.rs @@ -1362,15 +1362,18 @@ fn clean_opencode_redirects_xdg_state() { }; let request = process_request(&invocation, Vec::new(), None); + // Each folder is the root joined with a name, so it carries the + // platform's separator. + let clean = PathBuf::from("/clean"); for (key, value) in [ - ("XDG_CONFIG_HOME", "/clean/config"), - ("XDG_DATA_HOME", "/clean/data"), - ("XDG_STATE_HOME", "/clean/state"), + ("XDG_CONFIG_HOME", clean.join("config")), + ("XDG_DATA_HOME", clean.join("data")), + ("XDG_STATE_HOME", clean.join("state")), ] { assert!( request .env - .contains(&(OsString::from(key), OsString::from(value))) + .contains(&(OsString::from(key), value.into_os_string())) ); } } @@ -2510,6 +2513,13 @@ fn claude_api_error_lines_are_harness_errors() { #[test] fn planned_request_uses_the_spawn_builders_with_placeholders() { + // A file in the scratch placeholder, with the platform's separator. + let scratch = |name: &str| { + PathBuf::from("") + .join(name) + .to_string_lossy() + .into_owned() + }; let mut claude = invocation(Surface::Claude, &["--verbose"]); claude.system_prompt = "Use the rule.".to_string(); let planned = planned_request(&claude).expect("claude plan"); @@ -2531,7 +2541,7 @@ fn planned_request_uses_the_spawn_builders_with_placeholders() { assert!( strings(&grok.args) .windows(2) - .any(|pair| pair == ["--prompt-file", "/prompt.txt"]), + .any(|pair| pair == ["--prompt-file", scratch("prompt.txt").as_str()]), "{:?}", grok.args ); @@ -2551,7 +2561,7 @@ fn planned_request_uses_the_spawn_builders_with_placeholders() { assert!( agy_args .windows(2) - .any(|pair| pair == ["--log-file", "/agy.log"]), + .any(|pair| pair == ["--log-file", scratch("agy.log").as_str()]), "{agy_args:?}" ); @@ -2559,7 +2569,7 @@ fn planned_request_uses_the_spawn_builders_with_placeholders() { assert!( strings(&codex.args) .windows(2) - .any(|pair| pair == ["-o", "/last-message.txt"]), + .any(|pair| pair == ["-o", scratch("last-message.txt").as_str()]), "{:?}", codex.args ); @@ -3714,8 +3724,8 @@ fn cursor_relative_config_directory_resolves_against_the_repository() { let name = env[env.len() - 1].0.to_string_lossy().into_owned(); let directory = match name.as_str() { "CURSOR_CONFIG_DIR" => repository.join("settings"), - "XDG_CONFIG_HOME" => repository.join("xdg/cursor"), - _ => repository.join("home/.cursor"), + "XDG_CONFIG_HOME" => repository.join("xdg").join("cursor"), + _ => repository.join("home").join(".cursor"), }; std::fs::create_dir_all(&directory).expect("config directory"); std::fs::write( @@ -3769,11 +3779,17 @@ fn clean_cursor_run_moves_home_and_the_config_directory() { invocation.env = vec![(OsString::from("CURSOR_API_KEY"), OsString::from("key-1"))]; let request = process_request(&invocation, cursor::args(&invocation), None); - for (key, value) in [("HOME", "/clean"), ("CURSOR_CONFIG_DIR", "/clean/.cursor")] { + // The config directory is the root joined with a name, so it carries + // the platform's separator. + let clean = PathBuf::from("/clean"); + for (key, value) in [ + ("HOME", clean.clone()), + ("CURSOR_CONFIG_DIR", clean.join(".cursor")), + ] { assert!( request .env - .contains(&(OsString::from(key), OsString::from(value))), + .contains(&(OsString::from(key), value.into_os_string())), "{key}: {:?}", request.env ); diff --git a/src/cli/target/mod.rs b/src/cli/target/mod.rs index d7876ab1..6b9e6cdc 100644 --- a/src/cli/target/mod.rs +++ b/src/cli/target/mod.rs @@ -48,7 +48,7 @@ pub fn execute(target: Option<&str>, clone: bool, unbind: bool, list: bool) -> R pub(crate) fn bind_existing(target: &Path) -> Result<(), Error> { let resolved = - std::fs::canonicalize(target).map_err(|error| io_error(target, "read", &error))?; + rune::folders::canonicalize(target).map_err(|error| io_error(target, "read", &error))?; write_binding(&state_path()?, &resolved) } @@ -169,7 +169,8 @@ fn unbind_target(state_path: &Path) -> Result { fn resolve_target(requested: &str, clone: bool) -> Result { let as_path = PathBuf::from(requested); if as_path.is_dir() { - return std::fs::canonicalize(&as_path).map_err(|error| io_error(&as_path, "read", &error)); + return rune::folders::canonicalize(&as_path) + .map_err(|error| io_error(&as_path, "read", &error)); } let targets_root = targets_root()?; @@ -182,7 +183,7 @@ fn resolve_target(requested: &str, clone: bool) -> Result { } let candidate = targets_root.join(name); if candidate.is_dir() { - return std::fs::canonicalize(&candidate) + return rune::folders::canonicalize(&candidate) .map_err(|error| io_error(&candidate, "read", &error)); } @@ -235,7 +236,7 @@ fn clone_target(slug: &str, destination: &Path) -> Result { format!("git clone {url} failed with {status}"), )); } - std::fs::canonicalize(destination).map_err(|error| io_error(destination, "read", &error)) + rune::folders::canonicalize(destination).map_err(|error| io_error(destination, "read", &error)) } fn write_binding(state_path: &Path, target: &Path) -> Result<(), Error> { diff --git a/src/cli/todo/mod.rs b/src/cli/todo/mod.rs index 80386fba..db953a07 100644 --- a/src/cli/todo/mod.rs +++ b/src/cli/todo/mod.rs @@ -9,6 +9,7 @@ mod parse; pub use parse::{TodoItem, parse_line, render_line}; use rune::error::{Error, ErrorKind}; +use rune::folders::Canonical as _; use std::path::Path; #[derive(Debug, Clone, clap::Subcommand)] @@ -84,10 +85,10 @@ fn aggregate(root: &Path, json: bool) -> Result { // Use-time guard, independent of parse-time validation: the resolved // member stays inside the workspace container (the root's parent). let container = root - .canonicalize() + .canonical() .ok() .and_then(|canonical| canonical.parent().map(std::path::Path::to_path_buf)); - if let (Some(container), Ok(canonical_member)) = (&container, member_root.canonicalize()) + if let (Some(container), Ok(canonical_member)) = (&container, member_root.canonical()) && !canonical_member.starts_with(container) { return Err(Error::new( diff --git a/src/cli/update_check.rs b/src/cli/update_check.rs index bfadb80c..1ff2fae0 100644 --- a/src/cli/update_check.rs +++ b/src/cli/update_check.rs @@ -147,7 +147,7 @@ fn detect_manager(binary: &std::path::Path) -> Manager { if text.contains("/Cellar/") || text.contains("/homebrew/") || text.contains("/linuxbrew/") { return Manager::Homebrew; } - if let Some(home) = dirs::home_dir() + if let Some(home) = rune::folders::home_dir() && binary.starts_with(home.join(".local/bin")) { return Manager::Direct; diff --git a/src/cli/validate/check.rs b/src/cli/validate/check.rs index 39a849c3..a9fbfcfe 100644 --- a/src/cli/validate/check.rs +++ b/src/cli/validate/check.rs @@ -42,11 +42,7 @@ pub fn flat_directory( for path in files { let content = read_file(&path)?; - let relative = path - .strip_prefix(module_root) - .unwrap_or(&path) - .to_string_lossy() - .to_string(); + let relative = rune::manifest::slash_lossy(path.strip_prefix(module_root).unwrap_or(&path)); let checkpoint = report.checkpoint(); collect_diagnostics(&content, &relative, schema_content.as_ref(), None, report); @@ -84,11 +80,7 @@ pub fn flat_directory_with_json_schema( } let content = read_file(&path)?; - let relative = path - .strip_prefix(module_root) - .unwrap_or(&path) - .to_string_lossy() - .to_string(); + let relative = rune::manifest::slash_lossy(path.strip_prefix(module_root).unwrap_or(&path)); let checkpoint = report.checkpoint(); collect_diagnostics( @@ -192,11 +184,8 @@ pub fn skill_directory( // alignment contract as the entrypoint's. for companion in markdown_files(dir)? { let content = read_file(&companion)?; - let display_path = companion - .strip_prefix(module_root) - .unwrap_or(&companion) - .to_string_lossy() - .to_string(); + let display_path = + rune::manifest::slash_lossy(companion.strip_prefix(module_root).unwrap_or(&companion)); let checkpoint = report.checkpoint(); check_no_tables(&content, &display_path, report); report.record_since(display_path, checkpoint); @@ -206,10 +195,7 @@ pub fn skill_directory( } fn relative_display_path(path: &Path, module_root: &Path) -> String { - path.strip_prefix(module_root) - .unwrap_or(path) - .to_string_lossy() - .to_string() + rune::manifest::slash_lossy(path.strip_prefix(module_root).unwrap_or(path)) } fn skill_variant_files( diff --git a/src/cli/validate/plugin.rs b/src/cli/validate/plugin.rs index 5b8654f7..05ad8efd 100644 --- a/src/cli/validate/plugin.rs +++ b/src/cli/validate/plugin.rs @@ -133,8 +133,5 @@ fn push_diagnostics(diagnostics: Vec, result: &mut rune::result::Act } fn relative_path(module_root: &Path, path: &Path) -> String { - path.strip_prefix(module_root) - .unwrap_or(path) - .to_string_lossy() - .to_string() + rune::manifest::slash_lossy(path.strip_prefix(module_root).unwrap_or(path)) } diff --git a/src/cli/validate/repository/mod.rs b/src/cli/validate/repository/mod.rs index 39ffefe8..66e6c140 100644 --- a/src/cli/validate/repository/mod.rs +++ b/src/cli/validate/repository/mod.rs @@ -1,3 +1,4 @@ +use rune::folders::Canonical as _; use rune::manifest; use std::path::Path; @@ -76,7 +77,7 @@ fn template_hash(filename: &str, module_name: &str) -> Option { fn resolve_module_name(module_root: &Path) -> String { module_root - .canonicalize() + .canonical() .unwrap_or_else(|_| module_root.to_path_buf()) .file_name() .unwrap_or_default() diff --git a/src/cli/validate/skill_layers.rs b/src/cli/validate/skill_layers.rs index 512306d3..55327921 100644 --- a/src/cli/validate/skill_layers.rs +++ b/src/cli/validate/skill_layers.rs @@ -1,6 +1,7 @@ //! Strict source lint without deployment or external checkers. use rune::error::Error; +use rune::folders::Canonical as _; use rune::provider::ProviderConfig; use rune::skill_readiness::layers::{ SourceLayerFinding, SourceLayerReport, inspect_source_with_providers, @@ -18,7 +19,7 @@ pub(crate) fn execute(source: &str, json: bool) -> Result { findings: Vec::new(), valid: false, }; - match requested.canonicalize() { + match requested.canonical() { Ok(root) => { report.root = root.display().to_string(); inspect_selected(&root, &mut report); diff --git a/src/cli/validate/tools.rs b/src/cli/validate/tools.rs index e81e0eb9..38bcee1e 100644 --- a/src/cli/validate/tools.rs +++ b/src/cli/validate/tools.rs @@ -155,12 +155,7 @@ fn check_shellcheck(module_root: &Path, report: &mut ValidationReport) { let mut arguments = vec!["-S", "warning"]; let paths: Vec = shell_files .iter() - .map(|path| { - path.strip_prefix(module_root) - .unwrap_or(path) - .to_string_lossy() - .to_string() - }) + .map(|path| rune::manifest::slash_lossy(path.strip_prefix(module_root).unwrap_or(path))) .collect(); for path in &paths { arguments.push(path); @@ -314,10 +309,7 @@ fn run_command_with_env( } fn relative_path(path: &Path, module_root: &Path) -> String { - path.strip_prefix(module_root) - .unwrap_or(path) - .to_string_lossy() - .to_string() + rune::manifest::slash_lossy(path.strip_prefix(module_root).unwrap_or(path)) } fn find_text_files(module_root: &Path) -> Vec { diff --git a/src/cli/watchlist/mod.rs b/src/cli/watchlist/mod.rs index 5e23d534..ee18ed68 100644 --- a/src/cli/watchlist/mod.rs +++ b/src/cli/watchlist/mod.rs @@ -45,7 +45,7 @@ struct WatchlistConfig { } fn config_path() -> Result { - dirs::home_dir() + rune::folders::home_dir() .map(|home| home.join(".config/rune/watchlist.yaml")) .ok_or_else(|| "cannot resolve home directory".to_string()) } @@ -235,7 +235,7 @@ fn print_locations(locations: &[WatchEntry], json: bool) { /// Expands a leading `~/` and returns the resolved path. fn resolve(location: &str) -> Option { if let Some(rest) = location.strip_prefix("~/") { - return dirs::home_dir().map(|home| home.join(rest)); + return rune::folders::home_dir().map(|home| home.join(rest)); } Some(PathBuf::from(location)) } diff --git a/src/cli/watchlist/tests.rs b/src/cli/watchlist/tests.rs index 5a059a1e..d923b07a 100644 --- a/src/cli/watchlist/tests.rs +++ b/src/cli/watchlist/tests.rs @@ -7,7 +7,7 @@ fn resolve_passes_through_absolute_paths() { #[test] fn resolve_expands_leading_tilde() { - let home = dirs::home_dir().expect("home dir for test"); + let home = rune::folders::home_dir().expect("home dir for test"); assert_eq!(resolve("~/rune"), Some(home.join("rune"))); } diff --git a/src/folders.rs b/src/folders.rs new file mode 100644 index 00000000..b0e6bcc7 --- /dev/null +++ b/src/folders.rs @@ -0,0 +1,230 @@ +//! The user's folders: home, cache, data, and state. And the canonical +//! form of a path, which every folder comparison in rune starts from. +//! +//! Every lookup of one of these folders goes through this module, so one +//! rule decides where rune keeps its files. +//! +//! On Unix the rule is the one `dirs` applies: HOME and the XDG variables, +//! then the account database. +//! +//! On Windows `dirs` asks the shell for its known folders and reads no +//! environment variable. Nothing could then point rune at another home: +//! not a test, not a sandbox, and not a shell such as Git Bash, which sets +//! HOME for the commands it starts. So on Windows a HOME that holds an +//! absolute path is the home, as it is for git there, and the cache and +//! data folders sit under it where Windows keeps them. With no such HOME +//! the shell's known folders answer. + +use std::path::{Path, PathBuf}; + +/// `fs::canonicalize`, in the form a person writes a path. +/// +/// On Windows `fs::canonicalize` answers in the verbatim form, +/// `\\?\C:\repo`. In that form `/` is not a separator, so +/// `root.join("rules/Style.md")` names no file, and the path does not +/// compare equal to the same folder written `C:\repo`. This answers +/// `C:\repo`, and `\\server\share` for a network path. A path that only +/// the verbatim form can name comes back as it is: one of 260 characters +/// or more, or one with a part that is a device name or ends in a dot or +/// a space. +/// +/// On every other platform this is `fs::canonicalize`. +pub fn canonicalize(path: impl AsRef) -> std::io::Result { + std::fs::canonicalize(path).map(plain) +} + +/// [`canonicalize`] as a method, for a path at the end of a chain. +pub trait Canonical { + /// See [`canonicalize`]. + fn canonical(&self) -> std::io::Result; +} + +impl Canonical for Path { + fn canonical(&self) -> std::io::Result { + canonicalize(self) + } +} + +/// `base` joined with a path written with `/`, one part at a time. +/// +/// `base.join(".config/rune")` keeps the `/` inside the text of the path. +/// Windows reads it as a separator, so the path names the right folder, +/// but a command that prints it shows `C:\Users\owner\.config/rune`. This +/// gives `C:\Users\owner\.config\rune`, the form a person reads and the +/// form a test compares. On Unix the two are the same path and text. +#[must_use] +pub fn join(base: &Path, relative: &str) -> PathBuf { + let mut path = base.to_path_buf(); + path.extend(relative.split('/').filter(|part| !part.is_empty())); + path +} + +#[cfg(not(windows))] +fn plain(path: PathBuf) -> PathBuf { + path +} + +#[cfg(windows)] +fn plain(path: PathBuf) -> PathBuf { + match path.to_str().and_then(without_verbatim_prefix) { + Some(text) => PathBuf::from(text), + None => path, + } +} + +/// A verbatim path without its prefix, when the shorter text names the +/// same file: `\\?\C:\repo` is `C:\repo`, and `\\?\UNC\server\share` is +/// `\\server\share`. +#[cfg(any(windows, test))] +fn without_verbatim_prefix(text: &str) -> Option { + let plain = if let Some(rest) = text.strip_prefix(r"\\?\UNC\") { + format!(r"\\{rest}") + } else { + let rest = text.strip_prefix(r"\\?\")?; + let mut characters = rest.chars(); + let drive = characters.next()?; + if !drive.is_ascii_alphabetic() || characters.next() != Some(':') { + return None; + } + rest.to_owned() + }; + (plain.len() < 260 && plain.split('\\').all(part_reads_as_written)).then_some(plain) +} + +/// Whether Windows reads this part of a plain path as the name written. +/// It drops a trailing dot or space, and it reads a device name such as +/// `NUL`, with or without an extension, as the device. +#[cfg(any(windows, test))] +fn part_reads_as_written(part: &str) -> bool { + if part.ends_with('.') || part.ends_with(' ') { + return false; + } + let stem = part + .split('.') + .next() + .unwrap_or(part) + .trim_end() + .to_ascii_uppercase(); + let numbered = |device: &str| { + stem.strip_prefix(device).is_some_and(|number| { + matches!(number, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9") + }) + }; + !(matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") || numbered("COM") || numbered("LPT")) +} + +/// The user's home folder. +#[must_use] +pub fn home_dir() -> Option { + #[cfg(windows)] + if let Some(home) = home_from_environment() { + return Some(home); + } + dirs::home_dir() +} + +/// The folder for files rune can make again, such as a clone or a download. +#[must_use] +pub fn cache_dir() -> Option { + #[cfg(windows)] + if let Some(home) = home_from_environment() { + return Some(home.join("AppData").join("Local")); + } + dirs::cache_dir() +} + +/// The folder for files rune keeps for the user, such as shell completions. +#[must_use] +pub fn data_dir() -> Option { + #[cfg(windows)] + if let Some(home) = home_from_environment() { + return Some(home.join("AppData").join("Roaming")); + } + dirs::data_dir() +} + +/// The folder for state that outlives a run. Only Linux has one, so a +/// caller names its own fallback. +#[must_use] +pub fn state_dir() -> Option { + dirs::state_dir() +} + +#[cfg(windows)] +fn home_from_environment() -> Option { + absolute_home(std::env::var_os("HOME")) +} + +/// HOME as a home folder. Only an absolute path names one: an empty or a +/// relative HOME would move with the working directory. +#[cfg(any(windows, test))] +fn absolute_home(home: Option) -> Option { + home.map(PathBuf::from).filter(|home| home.is_absolute()) +} + +#[cfg(test)] +mod tests { + use super::{Canonical as _, absolute_home, canonicalize, without_verbatim_prefix}; + use std::ffi::OsString; + + #[test] + fn a_verbatim_drive_or_network_path_loses_its_prefix() { + assert_eq!( + without_verbatim_prefix(r"\\?\C:\repo\rules").as_deref(), + Some(r"C:\repo\rules") + ); + assert_eq!( + without_verbatim_prefix(r"\\?\UNC\server\share\repo").as_deref(), + Some(r"\\server\share\repo") + ); + } + + #[test] + fn a_path_only_the_verbatim_form_names_keeps_its_prefix() { + let long = format!(r"\\?\C:\{}", "a".repeat(260)); + for path in [ + r"\\?\Volume{b75e2c83-0000-0000-0000-602f00000000}\repo", + r"\\?\C:\repo\NUL", + r"\\?\C:\repo\com1.txt", + r"\\?\C:\repo\name.", + r"\\?\C:\repo\name \file", + long.as_str(), + ] { + assert_eq!(without_verbatim_prefix(path), None, "{path}"); + } + } + + #[test] + fn a_path_without_the_prefix_is_not_a_verbatim_path() { + assert_eq!(without_verbatim_prefix(r"C:\repo"), None); + assert_eq!(without_verbatim_prefix("/home/user"), None); + } + + #[test] + fn a_canonical_folder_joins_a_path_written_with_slashes() { + let folder = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(folder.path().join("rules")).unwrap(); + std::fs::write(folder.path().join("rules").join("Style.md"), "").unwrap(); + let canonical = canonicalize(folder.path()).unwrap(); + assert_eq!(canonical, folder.path().canonical().unwrap()); + assert!(canonical.join("rules/Style.md").is_file()); + assert!(!canonical.to_string_lossy().starts_with(r"\\?\")); + } + + #[test] + fn an_absolute_home_is_the_home() { + let home = std::env::temp_dir(); + assert!(home.is_absolute(), "{}", home.display()); + assert_eq!( + absolute_home(Some(home.clone().into_os_string())), + Some(home) + ); + } + + #[test] + fn an_unset_an_empty_or_a_relative_home_is_ignored() { + assert_eq!(absolute_home(None), None); + assert_eq!(absolute_home(Some(OsString::new())), None); + assert_eq!(absolute_home(Some(OsString::from("home/user"))), None); + } +} diff --git a/src/lib.rs b/src/lib.rs index 6b02ced5..8c83d02e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ pub const VALIDATE_SH_SHA: &str = env!("VALIDATE_SH_SHA"); pub mod consumer; pub mod deck; pub mod error; +pub mod folders; pub mod hooks; pub mod manifest; pub mod module; diff --git a/src/manifest/bundle.rs b/src/manifest/bundle.rs index 14aeec61..f4ec8853 100644 --- a/src/manifest/bundle.rs +++ b/src/manifest/bundle.rs @@ -1,5 +1,6 @@ //! Read-only identity and reference checks for a complete deployed skill. +use crate::folders::Canonical as _; use pulldown_cmark::{Event, LinkType, Parser, Tag}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -72,7 +73,8 @@ impl BundleProblem { fn new(kind: BundleProblemKind, path: &Path, message: impl Into) -> Self { Self { kind, - path: path.to_string_lossy().into_owned(), + // A bundle path, like an entry's: `/` between its parts. + path: super::slash_lossy(path), message: message.into(), } } @@ -90,7 +92,7 @@ struct Inventory { /// Relative symlinks may resolve only to entries inside this bundle. pub fn inspect_bundle(root: &Path) -> BundleInspection { let mut inventory = Inventory::default(); - match root.canonicalize() { + match root.canonical() { Ok(root) if root.is_dir() => { inventory.walk(&root, Path::new("")); inventory.check(&root); @@ -144,7 +146,7 @@ impl Inventory { continue; } let path = relative.join(child.file_name()); - let Some(path_text) = path.to_str() else { + let Some(path_text) = super::slash_text(&path) else { self.incomplete = true; self.problems.push(BundleProblem::new( BundleProblemKind::InvalidPath, @@ -153,6 +155,7 @@ impl Inventory { )); continue; }; + let path_text = path_text.as_str(); if path_text.contains('\\') || path_text.chars().any(char::is_control) { self.problems.push(BundleProblem::new( BundleProblemKind::InvalidPath, @@ -261,7 +264,7 @@ impl Inventory { } else if entry.kind == BundleEntryKind::Symlink { match contained_symlink_target(root, &root.join(path)) { Ok(target) => { - let target = target.to_string_lossy().into_owned(); + let target = super::slash_lossy(&target); if !target.is_empty() && !self.entries.contains_key(&target) { self.problems.push(BundleProblem::new( BundleProblemKind::BrokenSymlink, @@ -516,7 +519,7 @@ fn check_references( match result { Ok(target) if target.as_os_str().is_empty() - || entries.contains_key(target.to_string_lossy().as_ref()) => {} + || entries.contains_key(&super::slash_lossy(&target)) => {} Ok(_) => problems.push(BundleProblem::new( BundleProblemKind::BrokenReference, Path::new(document), diff --git a/src/manifest/mod.rs b/src/manifest/mod.rs index fe5d284e..ab7a9f1e 100644 --- a/src/manifest/mod.rs +++ b/src/manifest/mod.rs @@ -62,10 +62,7 @@ pub fn provenance_path(manifest_key: &str) -> String { let file_name = path.file_name().unwrap_or_default().to_string_lossy(); let provenance_dir = parent.join(PROVENANCE_DIRECTORY); - provenance_dir - .join(format!("{file_name}.{SIDECAR_EXTENSION}")) - .to_string_lossy() - .to_string() + slash_lossy(&provenance_dir.join(format!("{file_name}.{SIDECAR_EXTENSION}"))) } /// The stem-named sidecar location written by earlier versions @@ -77,10 +74,7 @@ pub fn legacy_provenance_path(manifest_key: &str) -> String { let stem = path.file_stem().unwrap_or_default().to_string_lossy(); let provenance_dir = parent.join(PROVENANCE_DIRECTORY); - provenance_dir - .join(format!("{stem}.{SIDECAR_EXTENSION}")) - .to_string_lossy() - .to_string() + slash_lossy(&provenance_dir.join(format!("{stem}.{SIDECAR_EXTENSION}"))) } /// Sidecar path beside a file on disk, full-filename encoded. @@ -113,6 +107,40 @@ pub fn sidecar_path(content_path: &std::path::Path) -> std::path::PathBuf { sidecar_for(content_path) } +/// A path as text with `/` between its parts on every platform, so a +/// record and its digest are the same wherever they are made. +/// +/// Windows writes `\` between the parts, and no file name can hold one +/// there, so each `\` is a separator and becomes `/`. On Unix a `\` is a +/// character of a name. It stays, and the caller refuses the path as +/// ambiguous: a record with it could not be told from a Windows path. +/// A path that is not valid UTF-8 has no text. +#[must_use] +pub fn slash_text(path: &std::path::Path) -> Option { + let text = path.to_str()?; + if cfg!(windows) { + Some(text.replace('\\', "/")) + } else { + Some(text.to_owned()) + } +} + +/// [`slash_text`] for a path that is a key or is shown, where a name that +/// is not valid UTF-8 is written with replacement characters instead of +/// refused. A relative path under a module, a build, or a target is such a +/// path: `rules/nested/Style.md` on every platform. +#[must_use] +pub fn slash_lossy(path: &std::path::Path) -> String { + slash_text(path).unwrap_or_else(|| { + let text = path.to_string_lossy(); + if cfg!(windows) { + text.replace('\\', "/") + } else { + text.into_owned() + } + }) +} + pub fn content_sha256(content: &str) -> String { content_sha256_bytes(content.as_bytes()) } diff --git a/src/manifest/source_snapshot.rs b/src/manifest/source_snapshot.rs index d8f4df8a..e40800ec 100644 --- a/src/manifest/source_snapshot.rs +++ b/src/manifest/source_snapshot.rs @@ -298,11 +298,11 @@ fn validate_symlink(relative: &Path, target: &Path) -> Result<(), String> { } fn path_text(path: &Path) -> Result { - let text = path.to_str().ok_or("source paths must be valid UTF-8")?; + let text = super::slash_text(path).ok_or("source paths must be valid UTF-8")?; if text.contains('\\') || text.chars().any(char::is_control) { return Err("source path has an ambiguous separator or control character".into()); } - Ok(text.into()) + Ok(text) } fn valid_label(label: &str) -> bool { diff --git a/src/ontology.rs b/src/ontology.rs index 0107c66a..6e7750cb 100644 --- a/src/ontology.rs +++ b/src/ontology.rs @@ -511,7 +511,7 @@ impl ResolvedConfig { pub fn env_file(&self) -> Option { match &self.env { Some(value) => Some(expand_tilde(&value.value)), - None => dirs::home_dir().map(|home| home.join(".env")), + None => crate::folders::home_dir().map(|home| home.join(".env")), } } @@ -725,8 +725,8 @@ pub fn load() -> Result { } pub fn config_dir() -> Result { - dirs::home_dir() - .map(|home| home.join(".config/rune")) + crate::folders::home_dir() + .map(|home| crate::folders::join(&home, ".config/rune")) .ok_or_else(|| Error::new(ErrorKind::Config, "cannot resolve home directory")) } @@ -784,10 +784,11 @@ pub fn fields(config: &ResolvedConfig) -> Vec { pub fn expand_tilde(value: &str) -> PathBuf { if value == "~" { - return dirs::home_dir().unwrap_or_else(|| PathBuf::from(value)); + return crate::folders::home_dir().unwrap_or_else(|| PathBuf::from(value)); } if let Some(rest) = value.strip_prefix("~/") { - return dirs::home_dir().map_or_else(|| PathBuf::from(value), |home| home.join(rest)); + return crate::folders::home_dir() + .map_or_else(|| PathBuf::from(value), |home| home.join(rest)); } PathBuf::from(value) } diff --git a/src/ontology/tests.rs b/src/ontology/tests.rs index c7348dd9..3cf4fbca 100644 --- a/src/ontology/tests.rs +++ b/src/ontology/tests.rs @@ -174,7 +174,7 @@ fn secrets_manifest_env_beats_config_and_keeps_a_missing_path() { ..Config::default() }; let from_config = resolve_config(&config, &no_env); - let home = dirs::home_dir().expect("home for test"); + let home = crate::folders::home_dir().expect("home for test"); assert_eq!( from_config.secrets_manifest(), Some(home.join("configured/secretspec.toml")), @@ -259,7 +259,7 @@ fn default_manifest_applies_only_when_present_and_no_env_file_is_named() { #[test] fn tilde_expansion_resolves_under_home() { - let home = dirs::home_dir().expect("home for test"); + let home = crate::folders::home_dir().expect("home for test"); assert_eq!(expand_tilde("~/Agents"), home.join("Agents")); } diff --git a/src/policy/mod.rs b/src/policy/mod.rs index f9f4ad76..a157acee 100644 --- a/src/policy/mod.rs +++ b/src/policy/mod.rs @@ -112,11 +112,7 @@ impl Environment { /// because the rune state directory is a CLI concern. #[must_use] pub fn from_process(session_dir: Option) -> Self { - let home = std::env::var_os("HOME") - .filter(|home| !home.is_empty()) - .map(PathBuf::from) - .or_else(dirs::home_dir) - .unwrap_or_default(); + let home = crate::folders::home_dir().unwrap_or_default(); let file = path_from(std::env::var_os(POLICY_ENV).as_deref(), &home); let disable = disabled_from(std::env::var(DISABLE_ENV).ok().as_deref()); Self { diff --git a/src/policy/paths.rs b/src/policy/paths.rs index f4fffa39..281a26f6 100644 --- a/src/policy/paths.rs +++ b/src/policy/paths.rs @@ -46,7 +46,7 @@ pub fn realpath_nearest(abs: &Path) -> PathBuf { let mut tail: Vec = Vec::new(); let mut head = abs.to_path_buf(); loop { - if let Ok(real) = std::fs::canonicalize(&head) { + if let Ok(real) = crate::folders::canonicalize(&head) { let mut out = real; for part in tail.iter().rev() { out.push(part); diff --git a/src/policy/tests.rs b/src/policy/tests.rs index 38bf5e1f..2b805f89 100644 --- a/src/policy/tests.rs +++ b/src/policy/tests.rs @@ -19,7 +19,7 @@ impl Scene { let root = tempfile::tempdir().unwrap(); // The real path, so a scope written under the temp root compares // equal to a resolved subject. - let dir = std::fs::canonicalize(root.path()).unwrap(); + let dir = crate::folders::canonicalize(root.path()).unwrap(); let home = dir.join("home"); for sub in ["Developer/work/mail", "Atlas/notes", "Agents/deck"] { std::fs::create_dir_all(home.join(sub)).unwrap(); @@ -52,11 +52,14 @@ impl Scene { Reader::load(env) } + /// A path under the home, with the platform's separator between its + /// parts: `relative` is written with `/`, and a test compares the + /// result with a path the policy resolved. fn at(&self, relative: &str) -> PathBuf { if relative.is_empty() { self.home.clone() } else { - self.home.join(relative) + self.home.join(relative).components().collect() } } } @@ -424,10 +427,13 @@ fn letter_case_is_ignored_where_the_file_system_ignores_it() { #[test] fn a_scope_contains_itself_and_its_children_not_a_sibling_with_its_prefix() { - assert!(contains("/a/b", "/a/b")); - assert!(contains("/a/b", "/a/b/c")); - assert!(!contains("/a/b", "/a/bc")); - assert!(contains("/", "/a")); + // Normalized paths carry the platform's separator. + let separator = std::path::MAIN_SEPARATOR_STR; + let path = |parts: &[&str]| format!("{separator}{}", parts.join(separator)); + assert!(contains(&path(&["a", "b"]), &path(&["a", "b"]))); + assert!(contains(&path(&["a", "b"]), &path(&["a", "b", "c"]))); + assert!(!contains(&path(&["a", "b"]), &path(&["a", "bc"]))); + assert!(contains(separator, &path(&["a"]))); } #[test] diff --git a/src/provider/detection.rs b/src/provider/detection.rs index 5472294a..fb20fc7c 100644 --- a/src/provider/detection.rs +++ b/src/provider/detection.rs @@ -1180,7 +1180,7 @@ fn inspect_build_kind( let Ok(relative) = build_path.strip_prefix(&kind_root) else { continue; }; - let key = format!("{kind}/{}", relative.to_string_lossy()); + let key = format!("{kind}/{}", crate::manifest::slash_lossy(relative)); build_keys.insert((target.clone(), key.clone())); inspect_build_file( &build_path, diff --git a/src/provider/tests.rs b/src/provider/tests.rs index f2f52a15..5aeb4e01 100644 --- a/src/provider/tests.rs +++ b/src/provider/tests.rs @@ -460,7 +460,7 @@ fn missing_managed_file_with_matching_build_can_be_repaired() { assert!(report.evidence.iter().any(|evidence| { evidence.kind == detection::EvidenceKind::ManagedFile && evidence.result == detection::EvidenceResult::Missing - && evidence.value.ends_with(".codex/skills/Alpha/SKILL.md") + && std::path::Path::new(&evidence.value).ends_with(".codex/skills/Alpha/SKILL.md") })); } @@ -548,7 +548,7 @@ fn new_and_removed_build_files_make_the_deployment_outdated() { assert!(report.evidence.iter().any(|evidence| { evidence.kind == detection::EvidenceKind::ManagedFile && evidence.result == detection::EvidenceResult::Outdated - && evidence.value.ends_with(".codex/skills/New/SKILL.md") + && std::path::Path::new(&evidence.value).ends_with(".codex/skills/New/SKILL.md") })); let removed_file = tempfile::tempdir().unwrap(); @@ -810,7 +810,7 @@ fn opencode_managed_instruction_is_checked() { assert!(current.evidence.iter().any(|evidence| { evidence.kind == detection::EvidenceKind::ManagedFile && evidence.result == detection::EvidenceResult::Current - && evidence.value.ends_with(".config/opencode/opencode.json") + && std::path::Path::new(&evidence.value).ends_with(".config/opencode/opencode.json") })); std::fs::write( @@ -838,7 +838,7 @@ fn opencode_managed_instruction_is_checked() { assert!(missing.evidence.iter().any(|evidence| { evidence.kind == detection::EvidenceKind::ManagedFile && evidence.result == detection::EvidenceResult::Missing - && evidence.value.ends_with(".config/opencode/opencode.json") + && std::path::Path::new(&evidence.value).ends_with(".config/opencode/opencode.json") })); } diff --git a/src/services/confine.rs b/src/services/confine.rs index f360cbe4..7e74168a 100644 --- a/src/services/confine.rs +++ b/src/services/confine.rs @@ -6,6 +6,7 @@ //! A refusal is a [`Violation`], so a caller can keep its own wording for //! each kind while the walk itself lives here once. +use crate::folders::Canonical as _; use std::fmt; use std::path::{Component, Path, PathBuf}; @@ -150,11 +151,10 @@ pub fn confine_for_write(base: &Path, candidate: &Path) -> Result<(), Violation> } fn canonicalize(path: &Path) -> Result { - path.canonicalize() - .map_err(|error| Violation::Unresolvable { - path: path.to_path_buf(), - error, - }) + path.canonical().map_err(|error| Violation::Unresolvable { + path: path.to_path_buf(), + error, + }) } #[cfg(test)] @@ -168,7 +168,7 @@ mod tests { std::fs::write(&inside, "content for the confinement test\n").unwrap(); let resolved = confine_existing(root.path(), &inside).unwrap(); - assert_eq!(resolved, inside.canonicalize().unwrap()); + assert_eq!(resolved, inside.canonical().unwrap()); } #[test] diff --git a/src/services/discovery.rs b/src/services/discovery.rs index 7b283a48..07db4d30 100644 --- a/src/services/discovery.rs +++ b/src/services/discovery.rs @@ -18,13 +18,13 @@ pub(super) fn discover_targets( watched_locations: &[PathBuf], ) -> Vec { let mut targets = Vec::new(); - let home = dirs::home_dir(); + let home = crate::folders::home_dir(); if let Some(ref home_path) = home && has_provider_manifests(home_path, providers) { targets.push(home_path.clone()); } - let root_abs = fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); + let root_abs = crate::folders::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); let is_home = home .as_ref() .is_some_and(|home_path| root_abs == *home_path); @@ -32,7 +32,7 @@ pub(super) fn discover_targets( targets.push(root_abs.clone()); } for location in watched_locations { - let canonical = fs::canonicalize(location).unwrap_or_else(|_| location.clone()); + let canonical = crate::folders::canonicalize(location).unwrap_or_else(|_| location.clone()); if canonical != root_abs && !targets.contains(&canonical) && has_provider_manifests(&canonical, providers) @@ -55,14 +55,14 @@ pub fn discover_local_repos( watched_locations: &[PathBuf], ) -> HashMap { let mut repos = HashMap::new(); - let canonical = fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); + let canonical = crate::folders::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); let mut search_dirs: Vec = Vec::new(); if let Some(parent) = canonical.parent() { search_dirs.push(parent.to_path_buf()); } for location in watched_locations { - let loc = fs::canonicalize(location).unwrap_or_else(|_| location.clone()); + let loc = crate::folders::canonicalize(location).unwrap_or_else(|_| location.clone()); register_repo(&loc, &mut repos); if let Some(parent) = loc.parent() { search_dirs.push(parent.to_path_buf()); @@ -192,11 +192,8 @@ fn scan_hook_kind(root: &Path) -> Vec { if !file_type.is_file() { continue; } - let relative_path = path - .strip_prefix(root) - .unwrap_or(&path) - .to_string_lossy() - .to_string(); + let relative_path = + crate::manifest::slash_lossy(path.strip_prefix(root).unwrap_or(&path)); let Some(name) = relative_path .strip_prefix("hooks/") .map(Path::new) diff --git a/src/services/files.rs b/src/services/files.rs index c1e43cf7..e62b88af 100644 --- a/src/services/files.rs +++ b/src/services/files.rs @@ -102,7 +102,7 @@ pub fn collect_dashboard_config_files( root, provider_targets, settings_filenames, - dirs::home_dir().as_deref(), + crate::folders::home_dir().as_deref(), ) } @@ -127,7 +127,7 @@ pub fn collect_dashboard_config_files_with_home( /// Rune config files at the scanned root plus allowlisted rune config files. #[must_use] pub fn collect_rune_config_files(root: &Path) -> Vec { - collect_rune_config_files_with_home(root, dirs::home_dir().as_deref()) + collect_rune_config_files_with_home(root, crate::folders::home_dir().as_deref()) } /// Rune config files using an explicit home directory, useful for tests. @@ -184,7 +184,12 @@ pub fn settings_by_harness( provider_targets: &[(String, String)], allowed: &[String], ) -> Vec { - settings_by_harness_with_home(root, provider_targets, allowed, dirs::home_dir().as_deref()) + settings_by_harness_with_home( + root, + provider_targets, + allowed, + crate::folders::home_dir().as_deref(), + ) } /// Settings/config files grouped per harness using an explicit home directory. @@ -251,7 +256,7 @@ pub fn schemas_by_source( local_repos: &HashMap, allowed: &HashSet, ) -> Vec { - let home = dirs::home_dir(); + let home = crate::folders::home_dir(); schemas_by_source_with_home( root, provider_targets, diff --git a/src/services/mod.rs b/src/services/mod.rs index d5aef5dd..357e0e4d 100644 --- a/src/services/mod.rs +++ b/src/services/mod.rs @@ -32,6 +32,7 @@ pub use source::{parse_frontmatter, strip_frontmatter}; pub use target::git_log_in_repo; use crate::error::{Error, ErrorKind}; +use crate::folders::canonicalize; use crate::manifest::FileStatus; use crate::provider::ContentKind; use crate::view::{ @@ -97,7 +98,7 @@ pub fn build_view( let mut modules: Vec = modules_by_source.into_values().collect(); for location in watched_locations { - let module_root = fs::canonicalize(location).unwrap_or_else(|_| location.clone()); + let module_root = canonicalize(location).unwrap_or_else(|_| location.clone()); if let Some(mut watched_module) = scan_source_module(&module_root) { watched_module.is_target = true; modules.push(watched_module); @@ -180,7 +181,7 @@ fn build_deck_view( providers: &[(String, String)], watched_locations: &[PathBuf], ) -> Result { - let root = fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); + let root = canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); let deck = crate::deck::load(&root).map_err(|message| Error::new(ErrorKind::Config, message))?; let repo_vcs = vcs::repo_vcs(&root); @@ -383,7 +384,7 @@ fn discover_deck_targets( providers: &[(String, String)], watched_locations: &[PathBuf], ) -> Vec { - let deck_root = fs::canonicalize(&deck.root).unwrap_or_else(|_| deck.root.clone()); + let deck_root = canonicalize(&deck.root).unwrap_or_else(|_| deck.root.clone()); let deck_remote = discovery::git_remote(&deck_root); let mut source_roots = std::collections::HashMap::new(); for deck_entry in &deck.entries { @@ -405,7 +406,7 @@ fn discover_deck_targets( let mut locations = watched_locations .iter() - .map(|path| fs::canonicalize(path).unwrap_or_else(|_| path.clone())) + .map(|path| canonicalize(path).unwrap_or_else(|_| path.clone())) .filter(|path| path != &deck_root) .filter(|path| target_points_at_deck(path, &deck_root, deck_remote.as_deref())) .collect::>(); @@ -510,7 +511,7 @@ fn target_points_at_deck(target: &Path, deck_root: &Path, deck_remote: Option<&s } else { target.join(local) }; - return fs::canonicalize(&resolved).unwrap_or(resolved) == deck_root; + return canonicalize(&resolved).unwrap_or(resolved) == deck_root; } source .get("git") @@ -751,7 +752,7 @@ fn atomic_write(path: &Path, content: &[u8]) -> Result<(), Error> { /// rest of the dashboard, dropping ADRs from unrelated sibling repos. pub fn active_repo_names(modules: &[ModuleView], root: &Path) -> HashSet { let mut names: HashSet = modules.iter().map(|module| module.name.clone()).collect(); - if let Some(root_name) = fs::canonicalize(root) + if let Some(root_name) = canonicalize(root) .unwrap_or_else(|_| root.to_path_buf()) .file_name() { @@ -809,11 +810,7 @@ pub(super) fn collect_variants( } pub(super) fn make_variant(repo: &Path, provider: &str, model: &str, file: &Path) -> Variant { - let relative_path = file - .strip_prefix(repo) - .unwrap_or(file) - .to_string_lossy() - .to_string(); + let relative_path = crate::manifest::slash_lossy(file.strip_prefix(repo).unwrap_or(file)); let content = fs::read_to_string(file).unwrap_or_default(); let mode = match extract_frontmatter_field(&content, "mode") { mode if mode.is_empty() => "replace".to_string(), diff --git a/src/services/provenance.rs b/src/services/provenance.rs index 2cec502a..65a3f0e5 100644 --- a/src/services/provenance.rs +++ b/src/services/provenance.rs @@ -28,7 +28,7 @@ pub(super) fn collect_provenance( /// Short label for a deployment target base: `~` for the home directory, /// otherwise the final path component. pub(super) fn deployment_target_label(target_base: &Path) -> String { - if let Some(home) = dirs::home_dir() + if let Some(home) = crate::folders::home_dir() && target_base == home { return "~".to_string(); diff --git a/src/services/vcs.rs b/src/services/vcs.rs index 592fcca8..239e618b 100644 --- a/src/services/vcs.rs +++ b/src/services/vcs.rs @@ -76,13 +76,13 @@ impl RepoVcs { pub(super) fn repo_vcs(module_dir: &Path) -> Option { let root_raw = git_stdout(module_dir, &["rev-parse", "--show-toplevel"])?; - let root = std::fs::canonicalize(root_raw.trim()).ok()?; + let root = crate::folders::canonicalize(root_raw.trim()).ok()?; let jj_colocated = root.join(".jj").is_dir(); let branch = branch_label(module_dir, jj_colocated); let (behind, ahead) = upstream_counts(module_dir, &branch); let status = git_stdout(module_dir, &["status", "--porcelain", "-z"]).unwrap_or_default(); let (dirty, untracked) = parse_status(&status); - let module_canonical = std::fs::canonicalize(module_dir).ok()?; + let module_canonical = crate::folders::canonicalize(module_dir).ok()?; let prefix = module_canonical .strip_prefix(&root) .unwrap_or(Path::new("")) diff --git a/src/session/exclude.rs b/src/session/exclude.rs index d95e12b4..a76d21f7 100644 --- a/src/session/exclude.rs +++ b/src/session/exclude.rs @@ -25,17 +25,22 @@ impl Exclude { /// Expand `~` in each glob against `home`, drop a trailing slash, and /// resolve the folder before the first wildcard through its symlinks, /// so a glob written through a linked path matches the real one. + /// + /// A glob and the folder it is matched against are compared as text + /// with `/` between the parts. On Windows a glob written with `\` and + /// a working folder such as `C:\Users\owner\work` are both brought to + /// that form first. #[must_use] pub fn resolve(paths: &[String], sessions: &[String], home: &Path) -> Self { let paths = paths .iter() .map(|glob| { let expanded = if glob == "~" { - home.to_string_lossy().into_owned() + slash_form(home) } else if let Some(rest) = glob.strip_prefix("~/") { - home.join(rest).to_string_lossy().into_owned() + slash_form(&home.join(rest)) } else { - glob.clone() + slash_form(Path::new(glob)) }; canonical_glob(expanded.trim_end_matches('/')) }) @@ -63,10 +68,10 @@ impl Exclude { /// also matches the folder itself. #[must_use] pub fn folder(&self, cwd: &Path) -> bool { - let given = cwd.to_string_lossy().trim_end_matches('/').to_string(); - let canonical = std::fs::canonicalize(cwd) + let given = slash_form(cwd).trim_end_matches('/').to_string(); + let canonical = crate::folders::canonicalize(cwd) .ok() - .map(|path| path.to_string_lossy().into_owned()) + .map(|path| slash_form(&path)) .filter(|path| *path != given); self.paths.iter().any(|glob| { glob_matches(glob, &given) @@ -103,12 +108,17 @@ fn canonical_glob(glob: &str) -> String { }; let (folder, rest) = glob.split_at(slash.max(1)); let folder = if slash == 0 { "/" } else { folder }; - match std::fs::canonicalize(folder) { - Ok(path) => format!("{}{rest}", path.to_string_lossy().trim_end_matches('/')), + match crate::folders::canonicalize(folder) { + Ok(path) => format!("{}{rest}", slash_form(&path).trim_end_matches('/')), Err(_) => glob.to_string(), } } +/// A path as the globs compare it: text with `/` between its parts. +fn slash_form(path: &Path) -> String { + crate::manifest::slash_lossy(path) +} + /// The working folder a session file records: the first `cwd` member in /// its first 64 KiB. Claude Code writes one on every line and Codex in /// its `session_meta` line. A compressed file goes through diff --git a/src/skill_readiness.rs b/src/skill_readiness.rs index 42b08b46..220d0cb0 100644 --- a/src/skill_readiness.rs +++ b/src/skill_readiness.rs @@ -1,5 +1,6 @@ //! Read-only skill inventory. Native discovery is a separate evidence gate. +use crate::folders::Canonical as _; use crate::manifest::{ self, bundle::{BundleEntryKind, BundleInspection, inspect_bundle}, @@ -113,7 +114,7 @@ pub fn inspect( roots: &[(PathBuf, String)], configuration_digest: String, ) -> SkillReadiness { - let cwd = cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf()); + let cwd = cwd.canonical().unwrap_or_else(|_| cwd.to_path_buf()); let boundary = cwd .ancestors() .find(|path| path.join(".git").exists() || path.join(".jj").exists()); @@ -237,7 +238,9 @@ fn inspect_expected_claims(root: &Path, report: &mut SkillReadiness) { ); continue; } - let expected = provider.join(key); + // The key is written with `/`: joined part by part, the + // finding names the file with one kind of separator. + let expected = crate::folders::join(provider, key); if expected.starts_with(root) && expected.file_name().is_some_and(|name| name == "SKILL.md") && !expected.is_file() @@ -266,7 +269,7 @@ fn scan( report: &mut SkillReadiness, ancestors: &mut BTreeSet, ) -> Result<(), String> { - let canonical = root.canonicalize().map_err(|error| error.to_string())?; + let canonical = root.canonical().map_err(|error| error.to_string())?; if !ancestors.insert(canonical.clone()) { return Err(format!("cyclic discovery directory: {}", root.display())); } @@ -310,7 +313,11 @@ fn inspect_skill(root: &Path, scope: &str, report: &mut SkillReadiness) { report.finding( "CSI003_INVALID_BUNDLE", name.clone(), - vec![root.join(&problem.path).display().to_string()], + vec![ + crate::folders::join(root, &problem.path) + .display() + .to_string(), + ], &problem.message, ); } @@ -360,7 +367,8 @@ fn owned_source(root: &Path, bundle: &BundleInspection) -> Result Result Result root, result => { let message = result.map_or_else( @@ -227,7 +228,7 @@ fn collect_text( report.problem( "CSI008_LAYER_SOURCE", "generic", - &relative.display().to_string(), + &report_path(relative), "", "source traversal exceeds the bounded inspection limit", ); @@ -253,14 +254,15 @@ fn collect_text( let bytes = fs::read(&physical).map_err(|error| error.to_string())?; match String::from_utf8(bytes) { Ok(content) if !content.contains('\0') => { - let path = logical.to_str().ok_or("source paths must be valid UTF-8")?; - files.insert(path.into(), content.replace("\r\n", "\n")); + let path = crate::manifest::slash_text(&logical) + .ok_or("source paths must be valid UTF-8")?; + files.insert(path, content.replace("\r\n", "\n")); } _ if required_text(&logical) => { report.problem( "CSI008_LAYER_SOURCE", "generic", - &logical.display().to_string(), + &report_path(&logical), "", "instruction text is not valid UTF-8 text", ); @@ -277,13 +279,18 @@ fn collect_text( report.problem( "CSI008_LAYER_SOURCE", "generic", - &relative.display().to_string(), + &report_path(relative), "", &message, ); } } +/// A source path as a finding names it, with `/` between its parts. +fn report_path(path: &Path) -> String { + crate::manifest::slash_lossy(path) +} + fn required_text(path: &Path) -> bool { path.extension() .and_then(|value| value.to_str()) diff --git a/src/skill_readiness/portability.rs b/src/skill_readiness/portability.rs index 2e684a37..f7a0114d 100644 --- a/src/skill_readiness/portability.rs +++ b/src/skill_readiness/portability.rs @@ -1,5 +1,6 @@ //! Literal harness rules for rendered instructions and source validation. +use crate::folders::Canonical as _; use crate::manifest::{ self, bundle::{BundleEntry, BundleEntryKind, BundleInspection}, @@ -224,7 +225,11 @@ pub(super) fn inspect_rendered(root: &Path, bundle: &BundleInspection) -> Vec Result, String> { return Err("instruction file changed its type after bundle inspection".into()); } - let canonical_root = root.canonicalize().map_err(|error| error.to_string())?; - let canonical = path.canonicalize().map_err(|error| error.to_string())?; + let canonical_root = root.canonical().map_err(|error| error.to_string())?; + let canonical = path.canonical().map_err(|error| error.to_string())?; if canonical != canonical_root.join(relative) { return Err("instruction path changed or leaves its bundle".into()); } diff --git a/src/skill_readiness/portability/tests.rs b/src/skill_readiness/portability/tests.rs index ea79fb7e..9aae0fe7 100644 --- a/src/skill_readiness/portability/tests.rs +++ b/src/skill_readiness/portability/tests.rs @@ -128,9 +128,12 @@ fn rendered_companions_are_scanned_but_provenance_and_binary_assets_are_not() { assert!( findings .iter() - .any(|finding| finding.path.ends_with("references/guide.MD") - && finding.line == Some(2) - && finding.token.as_deref() == Some("AskUserQuestion")) + // By path part: the separator differs by platform. + .any( + |finding| Path::new(&finding.path).ends_with("references/guide.MD") + && finding.line == Some(2) + && finding.token.as_deref() == Some("AskUserQuestion") + ) ); assert!( !findings diff --git a/src/target/mod.rs b/src/target/mod.rs index 8b34eb39..e8d210ea 100644 --- a/src/target/mod.rs +++ b/src/target/mod.rs @@ -38,7 +38,15 @@ pub fn resolve_paths( .ok_or_else(|| "Project scope requires home_directory".to_string())?; let cwd = std::env::current_dir().unwrap_or_default(); let cwd_string = cwd.to_string_lossy().to_string(); - let project_key = cwd_string.replace('/', "-"); + // The key is one path part. A Windows working directory holds + // `\` and a drive colon: left in, the key is an absolute path, + // and joining it drops the home before it. + let separators: &[char] = if cfg!(windows) { + &['/', '\\', ':'] + } else { + &['/'] + }; + let project_key = cwd_string.replace(separators, "-"); let project_key = project_key.trim_start_matches('-'); let path = home diff --git a/src/target/tests.rs b/src/target/tests.rs index c12d1c96..2ce6de46 100644 --- a/src/target/tests.rs +++ b/src/target/tests.rs @@ -52,9 +52,9 @@ fn project_scope_includes_cwd_based_key() { let paths = resolve_paths(Scope::Project, PROVIDER, "agents", Some(home()), None).unwrap(); assert_eq!(paths.len(), 1); - let path_string = paths[0].to_string_lossy().to_string(); - assert!(path_string.starts_with("/home/user/.claude/")); - assert!(path_string.ends_with("/agents")); + // By path part, not by text: the separator differs by platform. + assert!(paths[0].starts_with(home().join(".claude")), "{paths:?}"); + assert!(paths[0].ends_with("agents"), "{paths:?}"); } #[test] diff --git a/src/tui/app.rs b/src/tui/app.rs index d210966a..0594305e 100644 --- a/src/tui/app.rs +++ b/src/tui/app.rs @@ -3572,7 +3572,7 @@ impl App { format!("module {module_name}") }; let mut options: Vec<(String, PathBuf)> = Vec::new(); - if let Some(home) = dirs::home_dir() { + if let Some(home) = rune::folders::home_dir() { options.push(("user scope (~)".to_string(), home)); } options.push(( @@ -3670,7 +3670,7 @@ impl App { let raw = input.trim().to_string(); picker.input = None; let expanded = expand_home(&raw); - let Ok(path) = std::fs::canonicalize(&expanded) else { + let Ok(path) = rune::folders::canonicalize(&expanded) else { self.toast = Some(format!("not a directory: {raw}")); return; }; @@ -3968,7 +3968,7 @@ impl App { self.toast = Some("validation problem not found".to_string()); return; }; - let root = match std::fs::canonicalize(&self.root) { + let root = match rune::folders::canonicalize(&self.root) { Ok(root) if !is_git_cache_source(&root) => root, _ => { self.toast = Some("read-only source".to_string()); @@ -3985,7 +3985,7 @@ impl App { } else { root.join("runes").join(&violation.artifact) }; - let Ok(candidate) = std::fs::canonicalize(candidate) else { + let Ok(candidate) = rune::folders::canonicalize(candidate) else { self.toast = Some(format!("source file not found: {}", violation.artifact)); return; }; @@ -4025,7 +4025,7 @@ impl App { .local_path .as_ref() .ok_or_else(|| "read-only source".to_string())?; - let root = std::fs::canonicalize(root).map_err(|_| "read-only source".to_string())?; + let root = rune::folders::canonicalize(root).map_err(|_| "read-only source".to_string())?; if is_git_cache_source(&root) || std::fs::metadata(&root).map_or(true, |metadata| metadata.permissions().readonly()) { @@ -4036,7 +4036,7 @@ impl App { } else { artifact.source_path.as_str() }; - let source = std::fs::canonicalize(root.join(relative)) + let source = rune::folders::canonicalize(root.join(relative)) .map_err(|_| "read-only source".to_string())?; if !source.starts_with(&root) { return Err("read-only source".to_string()); @@ -6360,7 +6360,7 @@ pub fn load_provider_targets(root: &Path) -> Vec<(String, String)> { /// Provider deployment states for the status bar, in provider order. /// Detection is bounded filesystem evidence, so it runs once at load. fn detect_provider_states(root: &Path) -> Vec<(String, DeploymentState)> { - let Some(home) = dirs::home_dir() else { + let Some(home) = rune::folders::home_dir() else { return Vec::new(); }; config::detect_registered_providers(root, &home).map_or_default(|detections| { @@ -6863,12 +6863,12 @@ fn artifact_only_prefix(kind: &str, relative_path: &str) -> String { /// Expands a leading `~` to the home directory. fn expand_home(raw: &str) -> PathBuf { if raw == "~" - && let Some(home) = dirs::home_dir() + && let Some(home) = rune::folders::home_dir() { return home; } if let Some(rest) = raw.strip_prefix("~/") - && let Some(home) = dirs::home_dir() + && let Some(home) = rune::folders::home_dir() { return home.join(rest); } @@ -6895,8 +6895,8 @@ fn artifact_source(module: &ModuleView, artifact: &ArtifactView) -> (String, Str }; if let Some(repo) = module.local_path.as_ref() && let (Ok(repo), Ok(candidate)) = ( - std::fs::canonicalize(repo), - std::fs::canonicalize(repo.join(relative)), + rune::folders::canonicalize(repo), + rune::folders::canonicalize(repo.join(relative)), ) && candidate.starts_with(&repo) && let Ok(source) = std::fs::read_to_string(&candidate) @@ -6909,9 +6909,9 @@ fn artifact_source(module: &ModuleView, artifact: &ArtifactView) -> (String, Str fn is_git_cache_source(path: &Path) -> bool { let configured = std::env::var_os("RUNE_GIT_CACHE_DIR") .map(PathBuf::from) - .or_else(|| dirs::cache_dir().map(|cache| cache.join("rune/git"))); + .or_else(|| rune::folders::cache_dir().map(|cache| cache.join("rune/git"))); configured.is_some_and(|cache| { - let cache = std::fs::canonicalize(&cache).unwrap_or(cache); + let cache = rune::folders::canonicalize(&cache).unwrap_or(cache); path.starts_with(cache) }) } diff --git a/src/tui/cast_editor.rs b/src/tui/cast_editor.rs index 9a586d2a..ed07b0de 100644 --- a/src/tui/cast_editor.rs +++ b/src/tui/cast_editor.rs @@ -1,3 +1,4 @@ +use rune::folders::Canonical as _; use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; @@ -544,14 +545,15 @@ fn manifest_root() -> Option { } fn display_install_target(path: &Path) -> String { - let canonical_path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); - if let Some(home) = dirs::home_dir() { - let canonical_home = home.canonicalize().unwrap_or(home); + let canonical_path = path.canonical().unwrap_or_else(|_| path.to_path_buf()); + if let Some(home) = rune::folders::home_dir() { + let canonical_home = home.canonical().unwrap_or(home); if let Ok(rest) = canonical_path.strip_prefix(canonical_home) { return if rest.as_os_str().is_empty() { "~".to_string() } else { - format!("~/{}", rest.display()) + // The `~/` form is written with `/` on every platform. + format!("~/{}", rune::manifest::slash_lossy(rest)) }; } } diff --git a/src/tui/tests.rs b/src/tui/tests.rs index dbf73c69..d5fc3329 100644 --- a/src/tui/tests.rs +++ b/src/tui/tests.rs @@ -1248,7 +1248,7 @@ fn file_editor_save_stays_bound_to_artifact_selected_when_opened() { app.code_source_override_for_test(), Some(( "rune-core:skills/BuildSkill/SKILL.md", - std::fs::canonicalize(root.path().join(first_source)) + rune::folders::canonicalize(root.path().join(first_source)) .unwrap() .as_path(), )) diff --git a/tests/cli.rs b/tests/cli.rs index 542bbdb9..5a1bf41a 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -1,6 +1,7 @@ mod support; use assert_cmd::Command; use predicates::prelude::*; +use rune::folders::Canonical as _; #[cfg(unix)] use std::os::unix::fs::PermissionsExt; @@ -410,7 +411,8 @@ fn setup_invalid_selection_names_the_retry_command() { } fn create_setup_deck(home: &std::path::Path) -> std::path::PathBuf { - let deck = home.join("Developer/demo"); + // Joined part by part: a test compares this path as text. + let deck = home.join("Developer").join("demo"); std::fs::create_dir_all(&deck).unwrap(); std::fs::write(deck.join("deck.yaml"), "name: demo\n").unwrap(); deck @@ -565,12 +567,12 @@ fn setup_prints_every_write_before_apply() { assert!(output.status.success(), "{output:?}"); let stdout = String::from_utf8(output.stdout).unwrap(); let apply = stdout.find(" Apply").unwrap(); + // Joined part by part, as rune prints them: the text is compared. let paths = [ - home.path().join(".config/rune/config.yaml"), + rune::folders::join(home.path(), ".config/rune/config.yaml"), source.path().join("config.yaml"), - home.path() - .join(".local/share/bash-completion/completions/rune"), - home.path().join(".agents/skills/rune/SKILL.md"), + rune::folders::join(home.path(), ".local/share/bash-completion/completions/rune"), + rune::folders::join(home.path(), ".agents/skills/rune/SKILL.md"), ]; for path in paths { let path = path.display().to_string(); @@ -608,7 +610,7 @@ fn strict_install_error_uses_the_resolved_review_command() { assert_eq!(output.status.code(), Some(1)); assert_eq!(output.stderr, [] as [u8; 0]); let error: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); - let source = source.canonicalize().unwrap(); + let source = source.canonical().unwrap(); let expected = format!( "rune adopt status --root {}", shell_quote_for_test(&source.to_string_lossy()) @@ -841,6 +843,10 @@ fn tui_snapshot_renders_batched_deck_history() { } #[test] +#[cfg_attr( + windows, + ignore = "runs a shell script through bash, and on Windows the bash in System32 is the WSL launcher" +)] fn exec_shell_fixture_round_trips_json() { let root = tempfile::tempdir().unwrap(); let home = tempfile::tempdir().unwrap(); diff --git a/tests/codex_skill_aliases.rs b/tests/codex_skill_aliases.rs index a3838936..d98225e5 100644 --- a/tests/codex_skill_aliases.rs +++ b/tests/codex_skill_aliases.rs @@ -1,3 +1,4 @@ +use rune::folders::Canonical as _; use rune::skill_readiness::{self, SkillReadiness}; use std::fs; use std::path::{Path, PathBuf}; @@ -46,11 +47,11 @@ fn sibling_directory_aliases_remain_distinct_without_native_evidence() { use std::os::unix::fs::symlink; let fixture = tempfile::tempdir().unwrap(); - let workspace = fixture.path().canonicalize().unwrap(); + let workspace = fixture.path().canonical().unwrap(); let original = write_skill(&workspace, "original"); let alias = original.parent().unwrap().join("alias"); symlink("original", &alias).unwrap(); - assert_eq!(alias.canonicalize().unwrap(), original); + assert_eq!(alias.canonical().unwrap(), original); let report = inspect(&workspace); // Static candidates retain logical paths until native evidence resolves discovery. @@ -60,13 +61,10 @@ fn sibling_directory_aliases_remain_distinct_without_native_evidence() { #[test] fn distinct_physical_same_name_skills_remain_duplicates() { let fixture = tempfile::tempdir().unwrap(); - let workspace = fixture.path().canonicalize().unwrap(); + let workspace = fixture.path().canonical().unwrap(); let first = write_skill(&workspace, "first"); let second = write_skill(&workspace, "second"); - assert_ne!( - first.canonicalize().unwrap(), - second.canonicalize().unwrap() - ); + assert_ne!(first.canonical().unwrap(), second.canonical().unwrap()); assert_eq!( fs::read(first.join("SKILL.md")).unwrap(), fs::read(second.join("SKILL.md")).unwrap() diff --git a/tests/codex_skill_identity.rs b/tests/codex_skill_identity.rs index 9f694adf..47a05579 100644 --- a/tests/codex_skill_identity.rs +++ b/tests/codex_skill_identity.rs @@ -1,4 +1,5 @@ mod support; +use rune::folders::Canonical as _; use rune::manifest::{self, bundle::inspect_bundle}; use rune::skill_readiness::{self, CatalogEntry, NativeEvidence, ObservedAccess, SkillReadiness}; use std::collections::BTreeMap; @@ -23,25 +24,34 @@ impl Fixture { b"name: identity-fixture\nversion: 0.1.0\ndescription: fixture\nevents: []\n", ); write(&fixture.source.path().join("defaults.yaml"), b""); - let skill = fixture.source.path().join("skills/IdentityCanary"); + let skill = rune::folders::join(fixture.source.path(), "skills/IdentityCanary"); write(&skill.join("SKILL.md"), BASE.as_bytes()); - write(&skill.join("codex/SKILL.md"), VARIANT.as_bytes()); + write( + &rune::folders::join(&skill, "codex/SKILL.md"), + VARIANT.as_bytes(), + ); write( &skill.join("Workflow.md"), b"Read [detail](references/detail.md).\n", ); write( - &skill.join("references/detail.md"), + &rune::folders::join(&skill, "references/detail.md"), b"RUNE_IDENTITY_CANARY_7b91\n", ); write( - &skill.join("scripts/read.py"), + &rune::folders::join(&skill, "scripts/read.py"), b"from helper import value\nprint(value)\n", ); - write(&skill.join("scripts/helper.py"), b"value = 'canary'\n"); - write(&skill.join("assets/data.bin"), &[0, 255, 128, 1]); write( - &skill.join("agents/openai.yaml"), + &rune::folders::join(&skill, "scripts/helper.py"), + b"value = 'canary'\n", + ); + write( + &rune::folders::join(&skill, "assets/data.bin"), + &[0, 255, 128, 1], + ); + write( + &rune::folders::join(&skill, "agents/openai.yaml"), b"interface:\n short_description: Canary\n", ); fixture @@ -64,14 +74,16 @@ impl Fixture { .assert() .success(); } + // Joined part by part: a report names these paths as text, and a test + // compares that text. fn skill(&self) -> PathBuf { - self.target.path().join(".agents/skills/IdentityCanary") + rune::folders::join(self.target.path(), ".agents/skills/IdentityCanary") } fn report(&self) -> SkillReadiness { skill_readiness::inspect( self.target.path(), &[( - self.target.path().join(".agents/skills"), + rune::folders::join(self.target.path(), ".agents/skills"), "repository".into(), )], manifest::content_sha256("fixture configuration"), @@ -91,9 +103,10 @@ fn assert_duplicate_paths(report: &SkillReadiness, name: &str, paths: &[PathBuf] .collect(); assert_eq!(duplicates.len(), 1, "{report:#?}"); assert_eq!(duplicates[0].identity.as_deref(), Some(name)); + // A report names a path with the platform's separator throughout. let mut expected: Vec<_> = paths .iter() - .map(|path| path.display().to_string()) + .map(|path| path.components().collect::().display().to_string()) .collect(); expected.sort(); assert_eq!(duplicates[0].paths, expected, "{report:#?}"); @@ -212,8 +225,14 @@ fn portable_metadata_survives_codex_assembly() { #[test] fn equal_duplicate_names_are_ambiguous() { let temp = tempfile::tempdir().unwrap(); - write(&temp.path().join("one/Alpha/SKILL.md"), BASE.as_bytes()); - write(&temp.path().join("two/Alpha/SKILL.md"), BASE.as_bytes()); + write( + &rune::folders::join(temp.path(), "one/Alpha/SKILL.md"), + BASE.as_bytes(), + ); + write( + &rune::folders::join(temp.path(), "two/Alpha/SKILL.md"), + BASE.as_bytes(), + ); let mut roots = vec![ (temp.path().join("one"), "user".into()), (temp.path().join("two"), "repository".into()), @@ -226,8 +245,8 @@ fn equal_duplicate_names_are_ambiguous() { &first, "IdentityCanary", &[ - temp.path().join("one/Alpha/SKILL.md"), - temp.path().join("two/Alpha/SKILL.md"), + rune::folders::join(temp.path(), "one/Alpha/SKILL.md"), + rune::folders::join(temp.path(), "two/Alpha/SKILL.md"), ], ); } @@ -330,11 +349,11 @@ fn retained_legacy_copy_blocks_unique_readiness_until_migration_completes() { b"providers:\n codex:\n target: .codex\n", ); fixture.install(); - let legacy = fixture.target.path().join(".codex/skills/IdentityCanary"); - let legacy_manifest = fixture.target.path().join(".codex/.manifest"); + let legacy = rune::folders::join(fixture.target.path(), ".codex/skills/IdentityCanary"); + let legacy_manifest = rune::folders::join(fixture.target.path(), ".codex/.manifest"); let preserved = [ legacy.join("SKILL.md"), - legacy.join(".provenance/SKILL.md.yaml"), + rune::folders::join(&legacy, ".provenance/SKILL.md.yaml"), legacy_manifest.clone(), ] .map(|path| { @@ -343,10 +362,13 @@ fn retained_legacy_copy_blocks_unique_readiness_until_migration_completes() { }); let roots = [ ( - fixture.target.path().join(".agents/skills"), + rune::folders::join(fixture.target.path(), ".agents/skills"), "repository".into(), ), - (fixture.target.path().join(".codex/skills"), "legacy".into()), + ( + rune::folders::join(fixture.target.path(), ".codex/skills"), + "legacy".into(), + ), ]; let inspect = || skill_readiness::inspect(fixture.target.path(), &roots, "migration fixture".into()); @@ -416,13 +438,13 @@ fn native_catalog_and_cwd_alias_share_one_inventory_path() { let alias_root = tempfile::tempdir().unwrap(); let alias = alias_root.path().join("cwd-alias"); symlink(fixture.target.path(), &alias).unwrap(); - let physical = fixture.target.path().canonicalize().unwrap(); + let physical = fixture.target.path().canonical().unwrap(); let catalog = alias_root.path().join("catalog.json"); write(&catalog, serde_json::to_string(&serde_json::json!({ "version": "rune-native-skill-catalog/v1", "cwd": physical, "harness_version": "fixture", - "catalog": [{"name": "IdentityCanary", "path": fixture.skill().join("SKILL.md").canonicalize().unwrap(), "enabled": true}], + "catalog": [{"name": "IdentityCanary", "path": fixture.skill().join("SKILL.md").canonical().unwrap(), "enabled": true}], "errors": [], "raw_transcript_sha256": "fixture" })).unwrap().as_bytes()); @@ -459,8 +481,14 @@ fn native_catalog_and_cwd_alias_share_one_inventory_path() { #[test] fn declared_name_controls_duplicate_detection() { let temp = tempfile::tempdir().unwrap(); - write(&temp.path().join("Alpha/SKILL.md"), BASE.as_bytes()); - write(&temp.path().join("OldAlpha/SKILL.md"), BASE.as_bytes()); + write( + &rune::folders::join(temp.path(), "Alpha/SKILL.md"), + BASE.as_bytes(), + ); + write( + &rune::folders::join(temp.path(), "OldAlpha/SKILL.md"), + BASE.as_bytes(), + ); let report = skill_readiness::inspect( temp.path(), &[(temp.path().to_path_buf(), "test".into())], @@ -470,8 +498,8 @@ fn declared_name_controls_duplicate_detection() { &report, "IdentityCanary", &[ - temp.path().join("Alpha/SKILL.md"), - temp.path().join("OldAlpha/SKILL.md"), + rune::folders::join(temp.path(), "Alpha/SKILL.md"), + rune::folders::join(temp.path(), "OldAlpha/SKILL.md"), ], ); } @@ -488,7 +516,7 @@ fn incomplete_scope_cannot_pass() { fixture.target.path(), &[ ( - fixture.target.path().join(".agents/skills"), + rune::folders::join(fixture.target.path(), ".agents/skills"), "repository".into(), ), (unavailable.clone(), "test".into()), @@ -517,14 +545,14 @@ fn incomplete_scope_cannot_pass() { fn missing_whole_managed_bundle_cannot_hide_behind_a_valid_skill() { let fixture = Fixture::new(); write( - &fixture.source.path().join("skills/Other/SKILL.md"), + &rune::folders::join(fixture.source.path(), "skills/Other/SKILL.md"), b"---\nname: Other\ndescription: Other skill\n---\nHarmless.\n", ); fixture.install(); let complete = fixture.report(); assert!(complete.static_valid, "{complete:#?}"); assert_eq!(complete.skills.len(), 2); - let missing = fixture.target.path().join(".agents/skills/Other/SKILL.md"); + let missing = rune::folders::join(fixture.target.path(), ".agents/skills/Other/SKILL.md"); fs::remove_dir_all(missing.parent().unwrap()).unwrap(); let report = fixture.report(); assert!(!report.static_valid); @@ -549,14 +577,14 @@ fn bundle_digest_covers_companions_and_entry_types() { fixture.install(); let initial = inspect_bundle(&fixture.skill()).digest.unwrap(); write( - &fixture.skill().join("scripts/helper.py"), + &rune::folders::join(&fixture.skill(), "scripts/helper.py"), b"value = 'changed'\n", ); let changed = inspect_bundle(&fixture.skill()).digest.unwrap(); assert_ne!(initial, changed); assert!(!fixture.report().static_valid); write( - &fixture.skill().join(".provenance/ignored.yaml"), + &rune::folders::join(&fixture.skill(), ".provenance/ignored.yaml"), b"timestamp: changes\n", ); assert_eq!(changed, inspect_bundle(&fixture.skill()).digest.unwrap()); @@ -566,7 +594,10 @@ fn bundle_digest_covers_companions_and_entry_types() { fn modified_doctor_finding_overrides_zero_exit() { let fixture = Fixture::new(); fixture.install(); - write(&fixture.skill().join("scripts/helper.py"), b"changed\n"); + write( + &rune::folders::join(&fixture.skill(), "scripts/helper.py"), + b"changed\n", + ); let output = support::rune() .current_dir(fixture.source.path()) .args([ @@ -743,7 +774,7 @@ fn current_source_changes_invalidate_deployed_selection() { let snapshot = fixture .target .path() - .canonicalize() + .canonical() .unwrap() .join(".agents") .join(manifest::source_snapshot::SOURCE_SNAPSHOT_PATH); @@ -761,7 +792,7 @@ fn current_source_changes_invalidate_deployed_selection() { fixture.install(); assert_eq!(check()["source_verification"], "verified"); write( - &fixture.source.path().join("skills/NewSelection/SKILL.md"), + &rune::folders::join(fixture.source.path(), "skills/NewSelection/SKILL.md"), b"---\nname: NewSelection\ndescription: Newly selected skill\n---\nHarmless.\n", ); assert_stale_source_path(&check(), &snapshot); @@ -777,7 +808,7 @@ fn case_aliases_and_symlinks_are_accounted_for() { fixture.install(); let root = fixture.skill(); let initial = inspect_bundle(&root).digest.unwrap(); - let script = root.join("scripts/read.py"); + let script = rune::folders::join(&root, "scripts/read.py"); let mut permissions = fs::metadata(&script).unwrap().permissions(); permissions.set_mode(0o755); fs::set_permissions(&script, permissions).unwrap(); @@ -902,9 +933,9 @@ fn doctor_is_read_only_and_repair_restores_after_a_real_deployment() { assert!(snapshot.is_file(), "install writes the source snapshot"); // Break the deployment: delete a managed file and add an orphan. - let removed = fixture.skill().join("scripts/helper.py"); + let removed = rune::folders::join(&fixture.skill(), "scripts/helper.py"); fs::remove_file(&removed).unwrap(); - let orphan = fixture.target.path().join(".agents/rules/Orphan.md"); + let orphan = rune::folders::join(fixture.target.path(), ".agents/rules/Orphan.md"); write(&orphan, b"orphan\n"); let before = tree_bytes(fixture.target.path()); @@ -993,7 +1024,7 @@ fn doctor_is_read_only_and_repair_restores_after_a_real_deployment() { .stdout(predicates::str::contains("quarantined")); assert!(removed.is_file()); assert!(!orphan.exists()); - let trash = fixture.target.path().join(".agents/.trash"); + let trash = rune::folders::join(fixture.target.path(), ".agents/.trash"); assert!(trash.is_dir(), "orphan is quarantined, never deleted"); let (ok, report) = doctor_json(&fixture, &["--verify"]); @@ -1035,7 +1066,7 @@ fn adopt_doctor_and_provenance_accept_a_real_deployment_snapshot() { let fixture = Fixture::new(); fixture.install(); let root = fixture.target.path(); - let snapshot = root.join(".agents/.provenance/source-snapshot.json"); + let snapshot = rune::folders::join(root, ".agents/.provenance/source-snapshot.json"); assert!(snapshot.is_file(), "install writes the source snapshot"); // The deployed-file scan resolves sidecars from deployed files and never diff --git a/tests/codex_skill_metadata.rs b/tests/codex_skill_metadata.rs index e973fa40..98c9725a 100644 --- a/tests/codex_skill_metadata.rs +++ b/tests/codex_skill_metadata.rs @@ -59,6 +59,7 @@ fn write(path: &Path, content: &str) { } #[test] +#[cfg_attr(windows, ignore = "runs a companion script with python3")] fn codex_selected_companions_remain_runnable_and_excluded_bundles_stay_absent() { let fixture = Fixture::new(); let selected = fixture.source_skill("Runnable"); diff --git a/tests/codex_skill_portability.rs b/tests/codex_skill_portability.rs index a67a3c88..a03225fb 100644 --- a/tests/codex_skill_portability.rs +++ b/tests/codex_skill_portability.rs @@ -94,7 +94,8 @@ fn installed_companion_leak_blocks_strict_readiness() { .unwrap(); assert_eq!(finding.line, Some(1)); assert_eq!(finding.token.as_deref(), Some("AskUserQuestion")); - assert!(finding.paths[0].ends_with("Question/Workflow.md")); + // By path part: the separator differs by platform. + assert!(Path::new(&finding.paths[0]).ends_with("Question/Workflow.md")); let output = support::rune_clean() .timeout(Duration::from_secs(60)) .current_dir(source.path()) @@ -112,9 +113,7 @@ fn installed_companion_leak_blocks_strict_readiness() { .any(|finding| { finding["code"] == "CSI007_HARNESS_LEAKAGE" && finding["token"] == "AskUserQuestion" - && finding["paths"][0] - .as_str() - .unwrap() + && Path::new(finding["paths"][0].as_str().unwrap()) .ends_with("Question/Workflow.md") }), "{json}" diff --git a/tests/config_recovery.rs b/tests/config_recovery.rs index 33acfb78..07d8158e 100644 --- a/tests/config_recovery.rs +++ b/tests/config_recovery.rs @@ -1,5 +1,6 @@ mod support; use assert_cmd::Command; +use rune::folders::Canonical as _; use serde_json::Value; use std::collections::HashSet; use std::ffi::OsString; @@ -10,8 +11,10 @@ fn rune() -> Command { support::rune() } +/// Joined part by part: a test compares this path as text with the one +/// rune prints, and on Windows a `/` inside a part would stay in the text. fn user_config_path(home: &Path) -> PathBuf { - home.join(".config/rune/config.yaml") + home.join(".config").join("rune").join("config.yaml") } fn write_config(path: &Path, content: &str) { @@ -32,7 +35,7 @@ fn directory_entries(path: &Path) -> Vec { fn assert_reported_path(reported: &str, expected: &Path) { let direct_match = reported == expected.to_string_lossy().as_ref(); let canonical_match = expected - .canonicalize() + .canonical() .is_ok_and(|path| reported == path.to_string_lossy().as_ref()); assert!( direct_match || canonical_match, diff --git a/tests/hook_dispatch.rs b/tests/hook_dispatch.rs index cbf6cdba..21b169fe 100644 --- a/tests/hook_dispatch.rs +++ b/tests/hook_dispatch.rs @@ -182,6 +182,10 @@ fn named_generations(scene: &Scene) -> Vec { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn an_unreadable_codex_table_stops_the_install_before_anything_is_written() { let scene = Scene::new(); std::fs::create_dir_all(scene.home().join(".claude")).unwrap(); @@ -273,6 +277,10 @@ fn an_install_from_a_second_copy_of_rune_keeps_one_dispatcher_per_event() { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn emptying_the_handlers_takes_rune_s_entries_back_and_keeps_the_owner_s() { let scene = Scene::new(); std::fs::create_dir_all(scene.home().join(".claude")).unwrap(); @@ -551,6 +559,10 @@ fn rune_install_in_a_proof_scene_with_the_runner_s_home_reports_the_hooks_skippe } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn a_stale_or_bare_proof_marker_skips_nothing() { // The variable of the old marker, a marker file that is gone, and a // marker whose runner has exited are no proof scene: install runs. @@ -656,6 +668,10 @@ fn a_proof_scene_with_the_runner_s_home_installs_no_hook() { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn a_relative_state_directory_registers_an_absolute_plan_path() { let scene = Scene::new(); std::fs::create_dir_all(scene.home().join(".claude")).unwrap(); @@ -955,6 +971,10 @@ fn cursor_payload(event: &str, own: Value) -> String { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn a_claude_registration_steps_aside_when_cursor_runs_it() { // Cursor loads `~/.claude/settings.json` beside its own table and // runs every matching entry from both with its own payload, whose @@ -1083,6 +1103,10 @@ fn a_mismatched_event_that_is_nobody_s_name_for_it_still_fails() { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn the_registration_finds_the_plan_under_another_state_directory() { let scene = Scene::new(); denying_guard(&scene); @@ -1380,6 +1404,10 @@ fn an_explicit_provider_never_switches_a_handler() { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn a_harness_without_its_folder_is_skipped_and_returns_with_it() { // `rune install` and a bare `rune hook install` attempt every // registered harness. One whose folder does not exist is skipped and @@ -1444,6 +1472,10 @@ fn a_harness_without_its_folder_is_skipped_and_returns_with_it() { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn an_unselected_harness_s_table_is_neither_read_nor_locked_nor_created() { // An install into Cursor alone once read every registered table and // locked every table directory, so a garbled Claude `settings.json` @@ -1494,6 +1526,10 @@ fn an_unselected_harness_s_table_is_neither_read_nor_locked_nor_created() { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn a_switch_rewrites_the_harness_table_at_once() { // `rune hook off --harness cursor` leaves the handler out of // Cursor's plan and installs that plan into Cursor's table in the same @@ -1671,6 +1707,10 @@ fn a_codex_switch_holds_where_codex_keeps_the_trusted_entry() { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn a_switch_waits_for_the_lock_before_it_reads_the_state() { // `rune hook off A` once read the switches, then took the lock to // write them, so two switches that read before either wrote kept one @@ -1699,7 +1739,7 @@ fn a_switch_waits_for_the_lock_before_it_reads_the_state() { assert!( !so_far.contains(&format!( "held {}\n", - std::fs::canonicalize(&hooks).unwrap().display() + rune::folders::canonicalize(&hooks).unwrap().display() )), "the switch took the lock the test holds: {so_far}" ); @@ -1723,6 +1763,10 @@ fn a_switch_waits_for_the_lock_before_it_reads_the_state() { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn a_switch_the_install_refuses_leaves_the_state_as_it_was() { // `rune hook off` wrote the switches, then ran the install, with no // way back: an install the table refused left the file saying the @@ -1858,7 +1902,7 @@ fn rune_in(scene: &Scene, args: &[&str], trace: &Path) -> std::process::Child { /// holds and nothing more. A fixed sleep and a child still running proved /// neither (review, 2026-11-02). Returns the trace so far. fn waits_for(child: &mut std::process::Child, trace: &Path, dir: &Path) -> String { - let dir = std::fs::canonicalize(dir).unwrap(); + let dir = rune::folders::canonicalize(dir).unwrap(); let line = format!("wait {}\n", dir.display()); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); loop { @@ -1914,6 +1958,10 @@ fn planned_handlers(entry: &str, harness: &str, native: &str) -> Vec { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn a_switch_takes_the_install_s_whole_lock_set_in_the_install_s_order() { // `rune hook off` locked the state directory alone, then its install // asked for the tables; a plain install took the tables first and the @@ -1961,6 +2009,10 @@ fn a_switch_takes_the_install_s_whole_lock_set_in_the_install_s_order() { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn an_install_reads_the_switches_under_its_lock() { // `rune hook install` compiled its plan, then took the lock. A switch // that landed in between was undone when the install went on to @@ -2268,6 +2320,10 @@ fn a_firing_records_what_a_passive_event_s_merge_discarded() { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn a_switches_file_that_does_not_read_follows_the_registration_s_policy() { // A firing ran its generation as installed when `switches.json` was // there and did not parse, so a handler the owner turned off fired @@ -2395,6 +2451,10 @@ fn a_refused_switch_puts_the_switches_file_back_as_it_was() { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn a_firing_reads_the_switches_beside_its_plan_whatever_the_state_directory_says() { // A registration names its plan by path; a firing looked the // switches up beside the plan only when the plan was a generation, diff --git a/tests/hook_policy.rs b/tests/hook_policy.rs index d0052399..236378c3 100644 --- a/tests/hook_policy.rs +++ b/tests/hook_policy.rs @@ -21,7 +21,7 @@ impl Scene { let temp = tempfile::tempdir().unwrap(); // The real path, so the paths the test writes and the paths the // policy resolves read alike. - let root = std::fs::canonicalize(temp.path()).unwrap(); + let root = rune::folders::canonicalize(temp.path()).unwrap(); let scene = Self { _root: temp, root }; for dir in ["home/.config/rune", "home/work", "home/other", "bin"] { std::fs::create_dir_all(scene.path(dir)).unwrap(); diff --git a/tests/hook_wrap.rs b/tests/hook_wrap.rs index 6f30b82d..2ac69b25 100644 --- a/tests/hook_wrap.rs +++ b/tests/hook_wrap.rs @@ -5,6 +5,7 @@ mod support; +use rune::folders::Canonical as _; use std::ffi::OsString; use std::io::Write as _; use std::path::PathBuf; @@ -419,7 +420,7 @@ fn the_switch_round_trips_and_reads_from_a_subdirectory() { assert_eq!(out["turn_wrap"], "on"); assert_eq!( out["root"].as_str().map(PathBuf::from), - Some(scene.repo().canonicalize().unwrap()) + Some(scene.repo().canonical().unwrap()) ); scene .rune() @@ -642,6 +643,10 @@ fn a_session_that_wrote_a_file_from_another_directory_touched_the_workspace() { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn a_session_whose_shell_command_named_the_workspace_touched_it() { let Some(scene) = Scene::new() else { return }; scene.config(WRAPPER); @@ -846,6 +851,10 @@ fn a_turn_after_a_failed_stop_handler_waits_for_the_next_stop() { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn a_first_touch_keeps_its_key_when_the_snapshot_runs_past_the_timeout() { let Some(scene) = Scene::new() else { return }; scene.config(WRAPPER); @@ -959,7 +968,7 @@ fn a_workspace_two_sessions_touched_is_wrapped_by_neither_until_the_owner_resets .success() .stdout(format!( "turn wrap reset in {}: forgot {listed}\n", - scene.repo().canonicalize().unwrap().display() + scene.repo().canonical().unwrap().display() )); let stop = scene.turn("s1", "c.txt", "three\n"); assert!( @@ -973,6 +982,10 @@ fn a_workspace_two_sessions_touched_is_wrapped_by_neither_until_the_owner_resets } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn a_prompt_during_another_sessions_wrap_leaves_a_touch_the_wrap_cannot_miss() { let Some(scene) = Scene::new() else { return }; scene.config(PATIENT_WRAPPER); @@ -1067,16 +1080,16 @@ fn a_prompt_during_another_sessions_wrap_leaves_a_touch_the_wrap_cannot_miss() { } #[test] +#[cfg_attr( + windows, + ignore = "rune hooks are not supported on Windows yet: they assume a Unix shell, the executable bit, and Unix paths" +)] fn a_locked_slot_wraps_nothing_and_a_prompt_leaves_its_touch() { let Some(scene) = Scene::new() else { return }; scene.config(WRAPPER); scene.write_plan(); scene.switch_on(); - let lock = scene - .repo() - .canonicalize() - .unwrap() - .join(".jj/turn-wrap.lock"); + let lock = scene.repo().canonical().unwrap().join(".jj/turn-wrap.lock"); let held = std::fs::File::create(&lock).unwrap(); held.try_lock().unwrap(); let stop = scene.turn("s1", "a.txt", "one\n"); @@ -1119,7 +1132,7 @@ fn a_malformed_slot_wraps_nothing_until_the_owner_resets() { assert!( message.starts_with(&format!( "turn-wrap: nothing wrapped: {} is not a turn-wrap slot: ", - scene.slot().canonicalize().unwrap().display() + scene.slot().canonical().unwrap().display() )), "{message}" ); diff --git a/tests/init.rs b/tests/init.rs index 3169257b..176cd82a 100644 --- a/tests/init.rs +++ b/tests/init.rs @@ -23,6 +23,20 @@ fn skeleton_fixture() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/support/skeleton") } +/// Whether `make` starts on this machine. rune checks this before it +/// offers the project setup, and a run that cannot start `make` says so +/// instead of naming the noninteractive run. A Windows machine often has +/// no `make`. +fn make_starts() -> bool { + std::process::Command::new("make") + .arg("--version") + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .is_ok() +} + fn init(home: &Path, quests: &Path, args: &[&str]) -> assert_cmd::assert::Assert { rune() .env("HOME", home) @@ -452,12 +466,15 @@ fn noninteractive_init_without_templates_applies_base_only() { let quests = tempfile::tempdir().unwrap(); let destination = quests.path().join("base-only"); + let setup = if make_starts() { + "setup: skipped in noninteractive mode" + } else { + "setup: make is unavailable" + }; init(home.path(), quests.path(), &["base-only"]) .success() .stdout(predicate::str::contains("layers: base")) - .stdout(predicate::str::contains( - "setup: skipped in noninteractive mode", - )) + .stdout(predicate::str::contains(setup)) .stdout(predicate::str::contains(" make install")); assert!(destination.join("Makefile").is_file()); @@ -559,7 +576,14 @@ fn dry_run_predicts_gitignore_retrofit_performed_by_real_init() { .clone(); let real_run_result: serde_json::Value = serde_json::from_slice(&real_run_output).unwrap(); assert_eq!(dry_run_result["setup"]["status"], "dry_run"); - assert_eq!(real_run_result["setup"]["status"], "non_interactive"); + assert_eq!( + real_run_result["setup"]["status"], + if make_starts() { + "non_interactive" + } else { + "make_unavailable" + } + ); let real_run_gitignore = real_run_result["installed"] .as_array() .unwrap() diff --git a/tests/interface.rs b/tests/interface.rs index 2158974f..cab40ebe 100644 --- a/tests/interface.rs +++ b/tests/interface.rs @@ -69,8 +69,9 @@ impl Scene { .expect("settings fixture"); } + /// Joined part by part, as rune prints it: a test compares the text. fn settings(&self) -> PathBuf { - self.home.join(".t3/userdata/settings.json") + rune::folders::join(&self.home, ".t3/userdata/settings.json") } /// Replace the rune configuration of the scene. @@ -514,7 +515,7 @@ fn list_says_whether_the_interface_is_present_and_follows_t3code_home() { let scene = Scene::without_t3code(); let (code, stdout, _) = scene.run(&["interface", "list"]); assert_eq!(code, Some(0)); - let expected = scene.home.join(".t3/userdata/settings.json"); + let expected = scene.settings(); assert_eq!( stdout.trim_end(), format!("t3code absent {}", expected.display()) @@ -541,8 +542,7 @@ fn list_says_whether_the_interface_is_present_and_follows_t3code_home() { assert_eq!(listed[0]["present"], true); assert_eq!( listed[0]["settings"], - elsewhere - .join("userdata/settings.json") + rune::folders::join(&elsewhere, "userdata/settings.json") .to_string_lossy() .as_ref() ); diff --git a/tests/proof_head.rs b/tests/proof_head.rs index f797a240..4e8dfa8b 100644 --- a/tests/proof_head.rs +++ b/tests/proof_head.rs @@ -100,7 +100,9 @@ fn fixture() -> Option { fs::write( &config, format!( - "[signing]\nbehavior = \"drop\"\nbackend = \"ssh\"\nkey = \"{}\"\n[revset-aliases]\n\"immutable_heads()\" = \"none()\"\n", + // The key is a TOML literal string, in single quotes: a Windows + // path holds `\`, which a basic string reads as an escape. + "[signing]\nbehavior = \"drop\"\nbackend = \"ssh\"\nkey = '{}'\n[revset-aliases]\n\"immutable_heads()\" = \"none()\"\n", key.display() ), ) diff --git a/tests/run.rs b/tests/run.rs index 16a22ae0..f0db4a12 100644 --- a/tests/run.rs +++ b/tests/run.rs @@ -2578,7 +2578,7 @@ fn artifacts_of(output: &std::process::Output) -> Vec { #[cfg(unix)] fn canonical(path: &std::path::Path) -> String { - std::fs::canonicalize(path) + rune::folders::canonicalize(path) .expect("canonical path") .to_string_lossy() .into_owned() diff --git a/tests/session_capture.rs b/tests/session_capture.rs index 1aab5bc2..3d322468 100644 --- a/tests/session_capture.rs +++ b/tests/session_capture.rs @@ -72,7 +72,10 @@ fn write(path: &Path, text: &str) { } fn claude_line(cwd: &str, text: &str) -> String { - format!("{{\"cwd\":\"{cwd}\",\"type\":\"user\",\"message\":\"{text}\"}}\n") + // The folder goes in as a JSON string: a Windows path holds `\`, which + // JSON writes as `\\`. + let cwd = serde_json::to_string(cwd).expect("a path is a JSON string"); + format!("{{\"cwd\":{cwd},\"type\":\"user\",\"message\":\"{text}\"}}\n") } fn json_of(output: &std::process::Output) -> Value { diff --git a/tests/sign_queue.rs b/tests/sign_queue.rs index 4d4b2a4d..26847b4a 100644 --- a/tests/sign_queue.rs +++ b/tests/sign_queue.rs @@ -271,6 +271,10 @@ fn configure(command: &mut Process, fixture: &Fixture) { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn stacked_requests_sign_base_first_and_the_descendant_stays_current() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -353,6 +357,10 @@ fn stacked_requests_sign_base_first_and_the_descendant_stays_current() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_request_refuses_a_failing_receipt_a_foreign_receipt_and_a_signed_head() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -397,6 +405,10 @@ fn a_request_refuses_a_failing_receipt_a_foreign_receipt_and_a_signed_head() { /// or one beneath the remote head, would come back as a force-push of a /// published tip (2026-09-20: `4fa850b9` re-signed sideways to `64fc7e85`). #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_request_refuses_a_head_the_remote_already_holds() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -443,6 +455,10 @@ fn a_request_refuses_a_head_the_remote_already_holds() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_moved_head_is_stale_and_is_never_signed() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -478,6 +494,10 @@ fn a_moved_head_is_stale_and_is_never_signed() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_timed_out_pinentry_is_retried_and_a_cancelled_one_is_not() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -515,6 +535,10 @@ fn a_timed_out_pinentry_is_retried_and_a_cancelled_one_is_not() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_signature_from_a_key_outside_keys_is_a_failure() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -567,6 +591,10 @@ fn kept_receipts(fixture: &Fixture) -> Vec { /// The receipt of 2026-11-14 sat in a session scratch folder that was gone /// when the owner came to the key, and the request could never be signed. #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_receipt_deleted_after_queueing_still_signs_from_the_queue_s_copy() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -610,6 +638,10 @@ fn a_receipt_deleted_after_queueing_still_signs_from_the_queue_s_copy() { /// A later check that failed writes the same path. The request must not /// sign on the strength of the copy then. #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_receipt_edited_after_queueing_is_refused_although_the_copy_holds() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -639,6 +671,10 @@ fn a_receipt_edited_after_queueing_is_refused_although_the_copy_holds() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_changed_copy_is_refused_when_the_receipt_is_gone() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -668,6 +704,10 @@ fn a_changed_copy_is_refused_when_the_receipt_is_gone() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn dropping_a_request_removes_the_queue_s_copy() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -691,6 +731,10 @@ fn dropping_a_request_removes_the_queue_s_copy() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_repository_level_signing_program_is_never_run() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -751,6 +795,10 @@ fn a_repository_level_signing_program_is_never_run() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn queueing_with_json_emits_a_json_object() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -780,6 +828,10 @@ fn the_ceremony_forms_and_the_queue_do_not_mix() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_dead_claim_on_a_head_the_owner_already_signed_is_recorded_not_resigned() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -852,6 +904,10 @@ fn wait_for_signing(wait: &Path) { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_bookmark_moved_after_the_claim_is_stale_and_nothing_is_signed() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -887,6 +943,10 @@ fn a_bookmark_moved_after_the_claim_is_stale_and_nothing_is_signed() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_second_signer_on_the_same_repository_is_refused_while_the_first_runs() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -920,6 +980,10 @@ fn a_second_signer_on_the_same_repository_is_refused_while_the_first_runs() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_stale_request_is_skipped_and_the_next_current_one_is_signed() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -956,6 +1020,10 @@ fn a_stale_request_is_skipped_and_the_next_current_one_is_signed() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_repository_that_aliases_a_listing_keyword_is_refused() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -983,6 +1051,10 @@ fn a_repository_that_aliases_a_listing_keyword_is_refused() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_cancelled_attempt_on_a_rewritten_head_leaves_the_request_signable() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -1024,6 +1096,10 @@ fn a_cancelled_attempt_on_a_rewritten_head_leaves_the_request_signable() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn an_empty_queue_names_the_ledger_it_read() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -1045,6 +1121,10 @@ fn an_empty_queue_names_the_ledger_it_read() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_relative_receipt_is_recorded_absolute_and_the_owner_signs_from_elsewhere() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -1074,6 +1154,10 @@ fn a_relative_receipt_is_recorded_absolute_and_the_owner_signs_from_elsewhere() } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_request_whose_workspace_is_gone_is_stale_and_prunable_not_fatal() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -1421,6 +1505,10 @@ fn open_top(ceremony: &Ceremony) -> String { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn open_refuses_the_protected_branch_and_a_branch_without_a_draft() { let Some(ceremony) = ceremony() else { eprintln!("skipped: jj, gpg, or python3 is not installed"); @@ -1450,6 +1538,10 @@ fn open_refuses_the_protected_branch_and_a_branch_without_a_draft() { /// Every other refusal of `rune sign open`, in the order the command /// checks them, each leaving the head unsigned and the remote untouched. #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn open_refuses_a_ready_draft_a_stale_head_two_drafts_a_bad_body_and_a_foreign_branch_and_seals_above_an_owner_signed_head() { let Some(ceremony) = ceremony() else { @@ -1546,6 +1638,10 @@ fn open_refuses_a_ready_draft_a_stale_head_two_drafts_a_bad_body_and_a_foreign_b } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn open_seals_pushes_flips_the_draft_and_appends_the_nonce() { let Some(ceremony) = ceremony() else { eprintln!("skipped: jj, gpg, or python3 is not installed"); @@ -1578,6 +1674,10 @@ fn open_seals_pushes_flips_the_draft_and_appends_the_nonce() { /// `open --queue` records the request; `next` shows the view, declines on /// `n`, and completes the whole flow on `y`. #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn open_queued_is_completed_by_next_after_the_acknowledgment() { let Some(ceremony) = ceremony() else { eprintln!("skipped: jj, gpg, or python3 is not installed"); @@ -1642,6 +1742,10 @@ fn tree_of(ceremony: &Ceremony, commit: &str) -> String { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn submit_refuses_an_open_thread_and_an_undisposed_generation() { let Some(ceremony) = ceremony() else { eprintln!("skipped: jj, gpg, or python3 is not installed"); @@ -1721,6 +1825,10 @@ fn submit_top(ceremony: &Ceremony) -> (String, PathBuf) { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn next_shows_the_view_refuses_on_n_and_seals_on_y() { let Some(ceremony) = ceremony() else { eprintln!("skipped: jj, gpg, or python3 is not installed"); @@ -1779,6 +1887,10 @@ fn next_shows_the_view_refuses_on_n_and_seals_on_y() { /// The view shows the coverage state the ledger recorded when Runeseer /// stood down, with its reason, before the key. #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn next_shows_free_lanes_only_with_its_reason() { let Some(ceremony) = ceremony() else { eprintln!("skipped: jj, gpg, or python3 is not installed"); @@ -1826,6 +1938,10 @@ fn next_shows_free_lanes_only_with_its_reason() { /// ledger, a newer forged run does not win over the controller's, and an /// artifact that does not hash to the controller's line is refused. #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn submit_reads_the_ledger_from_the_controller_alone() { let Some(ceremony) = ceremony() else { eprintln!("skipped: jj, gpg, or python3 is not installed"); @@ -1987,6 +2103,10 @@ fn install_schema(fixture: &Fixture) { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn verify_accepts_a_valid_pair_and_rejects_an_inherited_open_seal() { let Some(ceremony) = ceremony() else { eprintln!("skipped: jj, gpg, or python3 is not installed"); @@ -2093,6 +2213,10 @@ fn verify_accepts_a_valid_pair_and_rejects_an_inherited_open_seal() { /// binds one of them, and without the number two pull requests at one /// head are refused rather than guessed. #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn verify_rejects_a_merged_seal_and_a_second_base() { let Some(ceremony) = ceremony() else { eprintln!("skipped: jj, gpg, or python3 is not installed"); @@ -2172,6 +2296,10 @@ fn verify_rejects_a_merged_seal_and_a_second_base() { /// The path the `owner-seal` workflow runs: a plain `git clone` with no /// jj, `gpg` from PATH, and `KEYS` from `origin/main`. #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn verify_runs_on_a_plain_git_checkout() { let Some(ceremony) = ceremony() else { eprintln!("skipped: jj, gpg, or python3 is not installed"); @@ -2260,6 +2388,10 @@ fn verify_runs_on_a_plain_git_checkout() { /// origin, and the pushed branch is the sealed one, which the app's draft /// then carries with the nonce. The seal names the outside pull request. #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn adopt_seals_the_outside_head_before_anything_is_pushed() { let Some(ceremony) = ceremony() else { eprintln!("skipped: jj, gpg, or python3 is not installed"); @@ -2352,6 +2484,10 @@ fn adopt_seals_the_outside_head_before_anything_is_pushed() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn verify_rejects_a_moved_parent_and_an_unequal_tree() { let Some(ceremony) = ceremony() else { eprintln!("skipped: jj, gpg, or python3 is not installed"); @@ -2389,6 +2525,10 @@ fn verify_rejects_a_moved_parent_and_an_unequal_tree() { /// commits it, not from the working copy: the workspace `open` runs in sits /// on another change whose copy of the file says something else. #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn open_reads_the_body_from_the_bookmark_tree_not_the_working_copy() { let Some(ceremony) = ceremony() else { eprintln!("skipped: jj, gpg, or python3 is not installed"); @@ -2435,6 +2575,10 @@ fn open_reads_the_body_from_the_bookmark_tree_not_the_working_copy() { /// helper, an HTTPS origin is refused before the key touch, not after the /// seal is signed. #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn open_refuses_an_https_origin_with_only_a_repository_scope_helper() { let Some(ceremony) = ceremony() else { eprintln!("skipped: jj, gpg, or python3 is not installed"); @@ -2509,6 +2653,10 @@ fn queue_range(fixture: &Fixture, head: &str) { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_range_of_model_commits_is_signed_in_one_run_and_every_commit_verifies() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -2557,6 +2705,10 @@ fn a_range_of_model_commits_is_signed_in_one_run_and_every_commit_verifies() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_declined_range_signs_nothing_and_stays_current() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -2580,6 +2732,10 @@ fn a_declined_range_signs_nothing_and_stays_current() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_declined_range_under_json_leaves_stdout_to_the_outcomes() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -2606,6 +2762,10 @@ fn a_declined_range_under_json_leaves_stdout_to_the_outcomes() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_range_goes_stale_when_its_head_or_the_protected_branch_moves() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -2652,6 +2812,10 @@ fn a_range_goes_stale_when_its_head_or_the_protected_branch_moves() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_range_the_owner_already_signed_is_recorded_without_the_key() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -2671,6 +2835,10 @@ fn a_range_the_owner_already_signed_is_recorded_without_the_key() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_bookmark_named_after_the_commit_id_does_not_redirect_the_key() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -2694,6 +2862,10 @@ fn a_bookmark_named_after_the_commit_id_does_not_redirect_the_key() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_commit_id_alias_is_refused_and_nothing_is_signed() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -2729,6 +2901,10 @@ fn a_commit_id_alias_is_refused_and_nothing_is_signed() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_signed_request_whose_bookmark_moved_lists_as_moved_and_fails_nothing() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -2768,6 +2944,10 @@ fn a_signed_request_whose_bookmark_moved_lists_as_moved_and_fails_nothing() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_commit_id_alias_scoped_to_the_sign_command_is_refused() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -2803,6 +2983,10 @@ fn a_commit_id_alias_scoped_to_the_sign_command_is_refused() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_commit_id_alias_in_a_scope_nested_in_a_scope_is_refused() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -2940,6 +3124,10 @@ fn expect_refused(fixture: &Fixture, path: &str, side_change: &str) { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_run_that_asks_the_key_for_a_commit_outside_the_named_set_is_refused_at_the_key() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -2962,6 +3150,10 @@ fn a_run_that_asks_the_key_for_a_commit_outside_the_named_set_is_refused_at_the_ /// `side`. The shim refuses it, so nothing signed of `side` exists for a /// push to carry. #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn an_alias_written_after_the_guard_and_before_the_run_is_refused_at_the_key() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -2989,6 +3181,10 @@ fn an_alias_written_after_the_guard_and_before_the_run_is_refused_at_the_key() { /// `side` whatever the operation store holds, and the request fails /// instead of staying current with `side` signed. #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_concurrent_operation_during_the_run_does_not_let_a_refused_commit_through() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -3080,6 +3276,10 @@ fn header(object: &str, name: &str) -> Vec { /// change id, and message, and the payload with the signature as a /// `gpgsig` header hashes to the id jj stores for the signed commit. #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn the_sign_payload_is_a_rewrite_whose_parents_are_signed_ids_and_the_signed_object_rebuilds() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -3179,6 +3379,10 @@ fn the_sign_payload_is_a_rewrite_whose_parents_are_signed_ids_and_the_signed_obj } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_merge_seal_rewritten_by_signing_its_ancestor_needs_the_key_and_never_lists_as_done() { let Some(ceremony) = ceremony() else { eprintln!("skipped: jj, gpg, or python3 is not installed"); @@ -3235,6 +3439,10 @@ fn a_merge_seal_rewritten_by_signing_its_ancestor_needs_the_key_and_never_lists_ } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_git_replacement_object_never_hides_what_the_range_shows_or_signs() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -3266,6 +3474,10 @@ fn a_git_replacement_object_never_hides_what_the_range_shows_or_signs() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_git_graft_never_hides_a_commit_the_range_shows_or_signs() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -3291,6 +3503,10 @@ fn a_git_graft_never_hides_a_commit_the_range_shows_or_signs() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_signed_head_rewritten_by_signing_its_ancestor_is_current_and_signed_again() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -3344,6 +3560,10 @@ fn a_signed_head_rewritten_by_signing_its_ancestor_is_current_and_signed_again() } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_protected_branch_that_moves_before_a_retry_stops_the_range() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -3377,6 +3597,10 @@ fn a_protected_branch_that_moves_before_a_retry_stops_the_range() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_protected_branch_that_moves_while_the_key_signs_fails_the_range() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); @@ -3410,6 +3634,10 @@ fn a_protected_branch_that_moves_while_the_key_signs_fails_the_range() { } #[test] +#[cfg_attr( + windows, + ignore = "signs through a fake gpg, a shell script that jj must start as its signing program" +)] fn a_range_head_written_by_plain_git_verifies_after_jj_adds_its_change_id() { let Some(fixture) = fixture() else { eprintln!("skipped: jj or gpg is not installed"); diff --git a/tests/skill_layer_config.rs b/tests/skill_layer_config.rs index 35580683..3b38aa3e 100644 --- a/tests/skill_layer_config.rs +++ b/tests/skill_layer_config.rs @@ -89,9 +89,8 @@ fn source_target_directory_can_select_multiple_providers() { finding["code"] == "CSI007_HARNESS_LEAKAGE" && finding["layer"] == format!("effective:{provider}") && finding["token"] == "AskUserQuestion" - && finding["path"] - .as_str() - .unwrap() + // By path part: the separator differs by platform. + && Path::new(finding["path"].as_str().unwrap()) .ends_with("skills/Portable/SKILL.md") }), "{report}" @@ -137,10 +136,7 @@ fn invalid_provider_configuration_cannot_fall_back_to_defaults() { .iter() .any(|finding| { finding["code"] == "SL000_INVALID_INPUT" - && finding["path"] - .as_str() - .unwrap() - .ends_with("skills/Portable") + && Path::new(finding["path"].as_str().unwrap()).ends_with("skills/Portable") }), "{report}" ); diff --git a/tests/support/mod.rs b/tests/support/mod.rs index 53118296..014e6b1b 100644 --- a/tests/support/mod.rs +++ b/tests/support/mod.rs @@ -68,17 +68,29 @@ const INHERITED: &[&str] = &[ "CURSOR_API_KEY", ]; -/// The variables to drop and the one to set for an isolated command. With +/// The variables to drop and the ones to set for an isolated command. With /// every `XDG_*` variable and directory override gone, rune's config and /// state, and the config of jj and git, all follow HOME, so a test that /// sets a HOME of its own moves all of them with it. -fn isolation() -> (Vec, [(&'static str, PathBuf); 1]) { +/// +/// On Windows rune follows HOME as well, but the tools a test starts read +/// the profile folders from USERPROFILE, APPDATA, and LOCALAPPDATA. Those +/// name the scratch HOME too, so jj reads no config of the developer's. +fn isolation() -> (Vec, Vec<(&'static str, PathBuf)>) { let mut removed: Vec = std::env::vars_os() .map(|(key, _)| key) .filter(|key| key.to_string_lossy().starts_with("XDG_")) .collect(); removed.extend(INHERITED.iter().map(std::ffi::OsString::from)); - (removed, [("HOME", scratch().join("home"))]) + let home = scratch().join("home"); + let mut set = Vec::new(); + if cfg!(windows) { + set.push(("USERPROFILE", home.clone())); + set.push(("APPDATA", home.join("AppData").join("Roaming"))); + set.push(("LOCALAPPDATA", home.join("AppData").join("Local"))); + } + set.push(("HOME", home)); + (removed, set) } /// Point a command at the scratch HOME, and drop every inherited `XDG_*` diff --git a/tests/target.rs b/tests/target.rs index 16d11800..f3fe2568 100644 --- a/tests/target.rs +++ b/tests/target.rs @@ -131,7 +131,7 @@ fn target_history_deduplicates_and_caps_at_ten() { assert_eq!( history[0].as_str(), Some( - std::fs::canonicalize(targets.path().join("quest-5")) + rune::folders::canonicalize(targets.path().join("quest-5")) .unwrap() .to_str() .unwrap() diff --git a/tests/toolchain_pin.rs b/tests/toolchain_pin.rs index 841d6776..f7cf39ea 100644 --- a/tests/toolchain_pin.rs +++ b/tests/toolchain_pin.rs @@ -38,6 +38,7 @@ fn workflow(steps: &str) -> String { const PINNED_STEP: &str = " - uses: dtolnay/rust-toolchain@0000000000000000000000000000000000000000 # stable\n with:\n toolchain: 1.100.0\n components: clippy\n"; #[test] +#[cfg_attr(windows, ignore = "runs scripts/check-toolchain-pin with python3")] fn repository_workflows_pin_rust_in_every_cargo_job() { let workflows = Path::new(env!("CARGO_MANIFEST_DIR")).join(".github/workflows"); let output = check(&workflows); @@ -54,6 +55,7 @@ fn repository_workflows_pin_rust_in_every_cargo_job() { } #[test] +#[cfg_attr(windows, ignore = "runs scripts/check-toolchain-pin with python3")] fn pinned_job_passes() { let (passed, report) = check_one(&workflow(&format!( "{PINNED_STEP} - name: Test\n run: cargo test --workspace\n" @@ -62,6 +64,7 @@ fn pinned_job_passes() { } #[test] +#[cfg_attr(windows, ignore = "runs scripts/check-toolchain-pin with python3")] fn job_without_cargo_needs_no_pin() { let (passed, report) = check_one(&workflow( " # cargo test would need Rust, and this job runs none.\n - name: Lint\n run: actionlint\n", @@ -70,6 +73,7 @@ fn job_without_cargo_needs_no_pin() { } #[test] +#[cfg_attr(windows, ignore = "runs scripts/check-toolchain-pin with python3")] fn toolchain_step_without_a_version_fails() { let (passed, report) = check_one(&workflow( " - uses: dtolnay/rust-toolchain@0000000000000000000000000000000000000000 # stable\n with:\n components: clippy\n - name: Test\n run: cargo test --workspace\n", @@ -82,6 +86,7 @@ fn toolchain_step_without_a_version_fails() { } #[test] +#[cfg_attr(windows, ignore = "runs scripts/check-toolchain-pin with python3")] fn stale_version_fails_and_is_named() { let (passed, report) = check_one(&workflow( " - uses: dtolnay/rust-toolchain@0000000000000000000000000000000000000000 # stable\n with:\n toolchain: 1.98.1\n - name: Build\n run: cargo build --release --locked\n", @@ -94,6 +99,7 @@ fn stale_version_fails_and_is_named() { } #[test] +#[cfg_attr(windows, ignore = "runs scripts/check-toolchain-pin with python3")] fn cargo_before_the_pin_fails() { let (passed, report) = check_one(&workflow(&format!( " - name: Build\n run: |\n set -euo pipefail\n cargo build --release\n{PINNED_STEP}" @@ -106,6 +112,7 @@ fn cargo_before_the_pin_fails() { } #[test] +#[cfg_attr(windows, ignore = "runs scripts/check-toolchain-pin with python3")] fn prek_hooks_without_the_pin_fail() { for run in ["prek run --all-files", "make validate"] { let (passed, report) = check_one(&workflow(&format!( @@ -117,6 +124,7 @@ fn prek_hooks_without_the_pin_fail() { } #[test] +#[cfg_attr(windows, ignore = "runs scripts/check-toolchain-pin with python3")] fn directory_without_workflows_is_an_error() { let directory = tempfile::tempdir().expect("temporary workflow directory"); let output = check(directory.path());