diff --git a/CHANGELOG.md b/CHANGELOG.md index 4aab13e3..10d895ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,10 +15,21 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). [0.2.0]: https://github.com/runedeck/rune/compare/v0.1.0...v0.2.0 [0.1.0]: https://github.com/runedeck/rune/releases/tag/v0.1.0 -## [0.7.1] - 2026-11-17 +## [0.7.1] - 2026-11-19 ### Fixed +- Make `rune install`, `deploy`, `drift`, `prune`, `doctor`, `validate`, and `spec` work on Windows. Hooks, `rune exec` of a shell script, and `rune sign queue` still need a Unix shell. +- Write manifest keys with `/` on Windows. `rune install` refused every skill there, and `rune doctor` reported every deployed file as an orphan. +- Follow `HOME` on Windows, as git does there. `rune.exe` read only the profile folder of the account, so nothing could point it at another home. +- Print a path on Windows without the `\\?\` prefix and with one kind of separator, and name `rune`, not `rune.exe`, in the usage line. +- Treat a file more than 260 characters deep as inside its folder on Windows. rune wrote the two paths in different forms, and a check that a path stays inside a folder gave the wrong answer. +- Refuse a path on Windows that only the `\\?\` form can name: one with a part that is a device name such as `NUL`, or that ends in a dot or a space. +- Match a session exclusion against the working folder on Windows. An excluded session was captured. +- Keep a project-scope target under the home folder on Windows. Its key held `\` and the drive colon. +- Draw the seal nonce of `rune sign` from the system on Windows, which has no `/dev/urandom`. +- Give `rune.exe` the stack size of the Linux and macOS builds. A debug build overflowed its stack. +- Show an artifact outside the module root with its whole path in `rune adopt`. It printed `C:/\/module` on Windows and `//tmp/module` elsewhere. - Build for Windows again. The 0.7.0 release build for `x86_64-pc-windows-msvc` did not compile. - Read a file's identity on Windows from an open handle, as the volume serial number and the file index, so the spec transaction can tell a replaced file from the one it hashed. - Skip the directory flush on Windows, where a directory does not open as a file. Spec transactions no longer fail there when they sync a directory. diff --git a/rune-docs/src/support.rs b/rune-docs/src/support.rs index f43133f2..987ebd1a 100644 --- a/rune-docs/src/support.rs +++ b/rune-docs/src/support.rs @@ -135,13 +135,18 @@ pub fn confine_existing(base: &Path, candidate: &Path) -> Result) -> std::io::Result { - fs::canonicalize(path).map(plain) + canonical_form(path.as_ref()) } /// [`canonicalize`] as a method, for a path at the end of a chain. @@ -157,57 +162,88 @@ impl Canonical for Path { } #[cfg(not(windows))] -fn plain(path: PathBuf) -> PathBuf { - path +fn canonical_form(path: &Path) -> std::io::Result { + fs::canonicalize(path) } +/// The text is the path's own UTF-16, not a `str`: a file name on Windows +/// need not be valid Unicode, and such a path gets the same form as any +/// other. #[cfg(windows)] -fn plain(path: PathBuf) -> PathBuf { - match path.to_str().and_then(without_verbatim_prefix) { - Some(text) => PathBuf::from(text), - None => path, +fn canonical_form(path: &Path) -> std::io::Result { + use std::os::windows::ffi::{OsStrExt as _, OsStringExt as _}; + + let verbatim = fs::canonicalize(path)?; + let text: Vec = verbatim.as_os_str().encode_wide().collect(); + let Some(plain) = without_verbatim_prefix(&text) else { + return Ok(verbatim); + }; + let plain = PathBuf::from(std::ffi::OsString::from_wide(&plain)); + // The names Windows reads as devices differ between its versions, so a + // part that looks like one is put to Windows itself. + let separator = u16::from(b'\\'); + if text.split(|unit| *unit == separator).all(part_looks_plain) + || fs::canonicalize(&plain).is_ok_and(|read| read == verbatim) + { + return Ok(plain); } + Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!( + "{} has a part that Windows reads as a device, or without its last dot or space", + verbatim.display() + ), + )) } -/// 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`. +/// A verbatim path without its prefix, when it is on a drive or a share: +/// `\\?\C:\repo` is `C:\repo`, and `\\?\UNC\server\share` is +/// `\\server\share`. Any other verbatim path, such as a volume named by +/// its id, has no shorter form, and neither has a path under it. #[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) +fn without_verbatim_prefix(text: &[u16]) -> Option> { + let utf16 = |text: &str| text.encode_utf16().collect::>(); + if let Some(rest) = text.strip_prefix(utf16(r"\\?\UNC\").as_slice()) { + let mut share = utf16(r"\\"); + share.extend_from_slice(rest); + return Some(share); + } + let rest = text.strip_prefix(utf16(r"\\?\").as_slice())?; + let drive = char::from_u32(u32::from(*rest.first()?))?; + (drive.is_ascii_alphabetic() && rest.get(1) == Some(&u16::from(b':'))).then(|| rest.to_vec()) } -/// 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. +/// Whether this part of a path is sure to read the same without the +/// verbatim prefix. Windows drops a trailing dot or space, and it can read +/// 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(' ') { +fn part_looks_plain(part: &[u16]) -> bool { + let (dot, space) = (u16::from(b'.'), u16::from(b' ')); + if part + .last() + .is_some_and(|last| *last == dot || *last == space) + { return false; } - let stem = part - .split('.') - .next() - .unwrap_or(part) - .trim_end() + let stem = part.split(|unit| *unit == dot).next().unwrap_or(part); + let stem = String::from_utf16_lossy(stem) + .trim_end_matches(' ') .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") + let mut digits = number.chars(); + matches!( + (digits.next(), digits.next()), + (Some('0'..='9' | '\u{b9}' | '\u{b2}' | '\u{b3}'), None) + ) }) }; - !(matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") || numbered("COM") || numbered("LPT")) + !(matches!( + stem.as_str(), + "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" + ) || numbered("COM") + || numbered("LPT")) } /// Split `---`-fenced YAML frontmatter from a markdown body. Returns `None` @@ -239,29 +275,59 @@ pub fn split_frontmatter(content: &str) -> Option<(&str, &str)> { #[cfg(test)] mod tests { - use super::without_verbatim_prefix; + use super::{canonicalize, confine_existing, part_looks_plain, without_verbatim_prefix}; + + fn utf16(text: &str) -> Vec { + text.encode_utf16().collect() + } + + fn plain(verbatim: &str) -> Option { + without_verbatim_prefix(&utf16(verbatim)).map(|plain| String::from_utf16(&plain).unwrap()) + } #[test] fn a_verbatim_drive_or_network_path_loses_its_prefix() { + assert_eq!(plain(r"\\?\C:\repo\docs").as_deref(), Some(r"C:\repo\docs")); 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(), + plain(r"\\?\UNC\server\share\repo").as_deref(), Some(r"\\server\share\repo") ); } #[test] - fn a_path_only_the_verbatim_form_names_keeps_its_prefix() { + fn a_long_path_loses_its_prefix_as_a_short_one_does() { + let long = format!(r"C:\repo\{}", "a".repeat(300)); + assert_eq!(plain(&format!(r"\\?\{long}")), Some(long)); + } + + #[test] + fn a_path_that_is_not_on_a_drive_or_a_share_keeps_its_prefix() { for path in [ r"\\?\Volume{b75e2c83-0000-0000-0000-602f00000000}\repo", - r"\\?\C:\repo\NUL", - r"\\?\C:\repo\name.", + r"\\?\repo", r"C:\repo", ] { - assert_eq!(without_verbatim_prefix(path), None, "{path}"); + assert_eq!(plain(path), None, "{path}"); } } + + #[test] + fn a_device_name_or_a_trailing_dot_or_space_does_not_look_plain() { + for part in ["NUL", "nul.txt", "com1.txt", "COM0", "aux ", "name."] { + assert!(!part_looks_plain(&utf16(part)), "{part}"); + } + for part in ["", "C:", "docs", "null", "console.md", "com10", ".git"] { + assert!(part_looks_plain(&utf16(part)), "{part}"); + } + } + + #[test] + fn a_long_path_inside_the_base_is_confined_to_it() { + let folder = tempfile::tempdir().unwrap(); + let mut deep = canonicalize(folder.path()).unwrap(); + deep.extend(std::iter::repeat_n("a".repeat(50), 6)); + std::fs::create_dir_all(&deep).unwrap(); + assert!(deep.as_os_str().len() > 300); + assert_eq!(confine_existing(folder.path(), &deep), Ok(deep)); + } } diff --git a/src/cli/adopt/review.rs b/src/cli/adopt/review.rs index 27e28d1a..dde344b5 100644 --- a/src/cli/adopt/review.rs +++ b/src/cli/adopt/review.rs @@ -1923,11 +1923,12 @@ fn atomic_write(path: &Path, content: &str) -> Result<(), String> { crate::cli::config::write_atomic(path, content).map_err(|error| error.to_string()) } +/// `path` under `root`, written with `/`. A path that is not under `root` +/// is shown whole, as the platform writes it: its parts joined with `/` +/// gave `//tmp/module` on Unix and `C:/\/module` on Windows. fn display_relative(root: &Path, path: &Path) -> String { - path.strip_prefix(root) - .unwrap_or(path) - .components() - .map(|component| component.as_os_str().to_string_lossy().to_string()) - .collect::>() - .join("/") + match path.strip_prefix(root) { + Ok(relative) => manifest::slash_lossy(relative), + Err(_) => path.display().to_string(), + } } diff --git a/src/cli/adopt/tests.rs b/src/cli/adopt/tests.rs index 236a4c4b..18d65051 100644 --- a/src/cli/adopt/tests.rs +++ b/src/cli/adopt/tests.rs @@ -826,6 +826,32 @@ fn verdicts_carry_timestamp_and_transport() { assert!(decided.contains('T'), "RFC 3339 timestamp, got: {decided}"); } +/// The hand `mv` of a folder a test has just written into. Windows refuses +/// a rename with "Access is denied" while any program has a file in the +/// folder open, and a virus scanner opens each new file for a moment. On a +/// loaded machine that moment outlasts the test's next line, so the rename +/// is tried again for up to five seconds. +fn move_folder(from: &std::path::Path, to: &std::path::Path) { + let started = std::time::Instant::now(); + loop { + match std::fs::rename(from, to) { + Ok(()) => return, + Err(error) + if cfg!(windows) + && error.kind() == std::io::ErrorKind::PermissionDenied + && started.elapsed() < std::time::Duration::from_secs(5) => + { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + Err(error) => panic!( + "cannot rename {} to {}: {error}", + from.display(), + to.display() + ), + } + } +} + fn finalize_all_keep(dir: &tempfile::TempDir, root: &std::path::Path) { let record_path = session_path(root); let record: serde_yaml::Value = @@ -959,16 +985,30 @@ fn modules_in_one_repository_use_distinct_session_directories() { /// process's directory, so a relative path has to climb from cargo's /// 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 { +/// +/// `None` when no relative path leads there: on Windows, when the two are +/// on different drives. +fn relative_path(base: &std::path::Path, target: &std::path::Path) -> Option { + use std::path::Component; + let base = base.canonical().expect("canonical base"); + let is_root = + |component: &Component| matches!(component, Component::Prefix(_) | Component::RootDir); + if !base + .components() + .take_while(is_root) + .eq(target.components().take_while(is_root)) + { + return None; + } let mut relative = std::path::PathBuf::new(); - for _ in base.components().skip(1) { + for _ in base.components().skip_while(is_root) { relative.push(".."); } - for component in target.components().skip(1) { + for component in target.components().skip_while(is_root) { relative.push(component); } - relative + Some(relative) } #[test] @@ -980,6 +1020,13 @@ fn relative_root_selects_an_open_session_by_artifact() { // names its artifact relative to the canonical module root. let repository = tempfile::tempdir().expect("repository"); let root = repository.path().canonical().expect("canonical repository"); + let current = std::env::current_dir().expect("current directory"); + let Some(relative_root) = relative_path(¤t, &root) else { + // A GitHub Windows runner: the checkout is on `D:` and the temp + // folder is on `C:`. + eprintln!("skipped: the temp folder is on another drive than the current directory"); + return; + }; init_git(&root); std::fs::write(root.join("module.yaml"), "name: fixture\n").expect("module"); @@ -991,9 +1038,8 @@ fn relative_root_selects_an_open_session_by_artifact() { .expect("session opens"); } - let current = std::env::current_dir().expect("current directory"); - let relative_root = relative_path(¤t, &root); assert!(relative_root.is_relative(), "{}", relative_root.display()); + assert!(!relative_root.has_root(), "{}", relative_root.display()); assert_eq!( review::next(&relative_root, Some("skills/Second"), 1, true).expect("session selected"), 0 @@ -1242,7 +1288,7 @@ fn doctor_flags_subject_name_disagreeing_with_holder() { finalize_all_keep(&dir, &root); // A hand `mv` leaves the sidecar recording the old module-relative name. let moved = dir.path().join("skills/Renamed"); - std::fs::rename(&root, &moved).unwrap(); + move_folder(&root, &moved); assert_eq!(review::doctor(dir.path(), false).unwrap(), 1); let sidecar = manifest::provenance::read(&moved.join(".provenance/SKILL.md.yaml")).unwrap(); @@ -1258,7 +1304,7 @@ fn repair_rewrites_stale_subject_name_and_reseal_agrees() { let root = adopt_fixture_skill(&dir); finalize_all_keep(&dir, &root); let moved = dir.path().join("skills/Renamed"); - std::fs::rename(&root, &moved).unwrap(); + move_folder(&root, &moved); assert_eq!(review::repair_source(dir.path()).unwrap().len(), 1); let sidecar = manifest::provenance::read(&moved.join(".provenance/SKILL.md.yaml")).unwrap(); @@ -1280,7 +1326,7 @@ fn source_dry_run_plans_the_rename_and_changes_nothing() { let root = adopt_fixture_skill(&dir); finalize_all_keep(&dir, &root); let moved = dir.path().join("skills/Renamed"); - std::fs::rename(&root, &moved).unwrap(); + move_folder(&root, &moved); let planned = review::plan_source_repairs(dir.path()).unwrap(); assert_eq!(planned.len(), 1); diff --git a/src/cli/install/tests.rs b/src/cli/install/tests.rs index f1e1c268..c012528e 100644 --- a/src/cli/install/tests.rs +++ b/src/cli/install/tests.rs @@ -123,7 +123,11 @@ fn execute_unknown_provider_lists_available_choices() { let fix_command = error .fix_command() .expect("unknown provider must include a provider-list command"); - assert!(fix_command.contains(&module_directory.path().display().to_string())); + // The command names the folder in its canonical form. The temp folder + // can be written another way: Windows gives a GitHub runner a short + // name for it, `C:\Users\RUNNER~1\AppData\Local\Temp`. + let module_folder = rune::folders::canonicalize(module_directory.path()).unwrap(); + assert!(fix_command.contains(&module_folder.display().to_string())); assert!(fix_command.ends_with("rune provider")); assert!(!fix_command.contains('<')); assert!(!fix_command.contains('>')); @@ -273,8 +277,12 @@ fn install_command_preserves_options_and_resolves_paths() { false, ); - assert!(command.contains(&source.path().to_string_lossy().to_string())); - assert!(command.contains(&target.path().to_string_lossy().to_string())); + // The command names both folders in their canonical form, and the temp + // folder can be written another way, as a short name on Windows. + let source_folder = rune::folders::canonicalize(source.path()).unwrap(); + let target_folder = rune::folders::canonicalize(target.path()).unwrap(); + assert!(command.contains(&source_folder.to_string_lossy().to_string())); + assert!(command.contains(&target_folder.to_string_lossy().to_string())); assert!(command.contains("--provider codex")); assert!(command.contains("--force")); assert!(command.contains("--no-prune")); diff --git a/src/cli/state.rs b/src/cli/state.rs index e172b209..fdfb94b5 100644 --- a/src/cli/state.rs +++ b/src/cli/state.rs @@ -14,6 +14,6 @@ pub(crate) fn dir() -> Result { return Ok(PathBuf::from(dir).join("rune")); } rune::folders::home_dir() - .map(|home| home.join(".local/state/rune")) + .map(|home| rune::folders::join(&home, ".local/state/rune")) .ok_or_else(|| Error::new(ErrorKind::Config, "cannot resolve home directory")) } diff --git a/src/folders.rs b/src/folders.rs index b0e6bcc7..7a47e118 100644 --- a/src/folders.rs +++ b/src/folders.rs @@ -23,14 +23,18 @@ use std::path::{Path, PathBuf}; /// `\\?\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. +/// `C:\repo`, and `\\server\share` for a network path. +/// +/// Every path on a drive or a share comes back in that one form, however +/// long it is, so a folder and a file inside it always compare as prefix +/// and rest. The standard library puts the prefix back for a call that +/// needs it. A path that Windows reads as another file without the prefix +/// is an error: one with a part that is a device name such as `NUL`, or +/// that ends in a dot or a space. rune has no single way to write it. /// /// On every other platform this is `fs::canonicalize`. pub fn canonicalize(path: impl AsRef) -> std::io::Result { - std::fs::canonicalize(path).map(plain) + canonical_form(path.as_ref()) } /// [`canonicalize`] as a method, for a path at the end of a chain. @@ -60,57 +64,88 @@ pub fn join(base: &Path, relative: &str) -> PathBuf { } #[cfg(not(windows))] -fn plain(path: PathBuf) -> PathBuf { - path +fn canonical_form(path: &Path) -> std::io::Result { + std::fs::canonicalize(path) } +/// The text is the path's own UTF-16, not a `str`: a file name on Windows +/// need not be valid Unicode, and such a path gets the same form as any +/// other. #[cfg(windows)] -fn plain(path: PathBuf) -> PathBuf { - match path.to_str().and_then(without_verbatim_prefix) { - Some(text) => PathBuf::from(text), - None => path, +fn canonical_form(path: &Path) -> std::io::Result { + use std::os::windows::ffi::{OsStrExt as _, OsStringExt as _}; + + let verbatim = std::fs::canonicalize(path)?; + let text: Vec = verbatim.as_os_str().encode_wide().collect(); + let Some(plain) = without_verbatim_prefix(&text) else { + return Ok(verbatim); + }; + let plain = PathBuf::from(std::ffi::OsString::from_wide(&plain)); + // The names Windows reads as devices differ between its versions, so a + // part that looks like one is put to Windows itself. + let separator = u16::from(b'\\'); + if text.split(|unit| *unit == separator).all(part_looks_plain) + || std::fs::canonicalize(&plain).is_ok_and(|read| read == verbatim) + { + return Ok(plain); } + Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!( + "{} has a part that Windows reads as a device, or without its last dot or space", + verbatim.display() + ), + )) } -/// 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`. +/// A verbatim path without its prefix, when it is on a drive or a share: +/// `\\?\C:\repo` is `C:\repo`, and `\\?\UNC\server\share` is +/// `\\server\share`. Any other verbatim path, such as a volume named by +/// its id, has no shorter form, and neither has a path under it. #[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) +fn without_verbatim_prefix(text: &[u16]) -> Option> { + let utf16 = |text: &str| text.encode_utf16().collect::>(); + if let Some(rest) = text.strip_prefix(utf16(r"\\?\UNC\").as_slice()) { + let mut share = utf16(r"\\"); + share.extend_from_slice(rest); + return Some(share); + } + let rest = text.strip_prefix(utf16(r"\\?\").as_slice())?; + let drive = char::from_u32(u32::from(*rest.first()?))?; + (drive.is_ascii_alphabetic() && rest.get(1) == Some(&u16::from(b':'))).then(|| rest.to_vec()) } -/// 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. +/// Whether this part of a path is sure to read the same without the +/// verbatim prefix. Windows drops a trailing dot or space, and it can read +/// 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(' ') { +fn part_looks_plain(part: &[u16]) -> bool { + let (dot, space) = (u16::from(b'.'), u16::from(b' ')); + if part + .last() + .is_some_and(|last| *last == dot || *last == space) + { return false; } - let stem = part - .split('.') - .next() - .unwrap_or(part) - .trim_end() + let stem = part.split(|unit| *unit == dot).next().unwrap_or(part); + let stem = String::from_utf16_lossy(stem) + .trim_end_matches(' ') .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") + let mut digits = number.chars(); + matches!( + (digits.next(), digits.next()), + (Some('0'..='9' | '\u{b9}' | '\u{b2}' | '\u{b3}'), None) + ) }) }; - !(matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") || numbered("COM") || numbered("LPT")) + !(matches!( + stem.as_str(), + "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" + ) || numbered("COM") + || numbered("LPT")) } /// The user's home folder. @@ -164,40 +199,102 @@ fn absolute_home(home: Option) -> Option { #[cfg(test)] mod tests { - use super::{Canonical as _, absolute_home, canonicalize, without_verbatim_prefix}; + use super::{ + Canonical as _, absolute_home, canonicalize, part_looks_plain, without_verbatim_prefix, + }; use std::ffi::OsString; + fn utf16(text: &str) -> Vec { + text.encode_utf16().collect() + } + + fn plain(verbatim: &str) -> Option { + without_verbatim_prefix(&utf16(verbatim)).map(|plain| String::from_utf16(&plain).unwrap()) + } + #[test] fn a_verbatim_drive_or_network_path_loses_its_prefix() { assert_eq!( - without_verbatim_prefix(r"\\?\C:\repo\rules").as_deref(), + plain(r"\\?\C:\repo\rules").as_deref(), Some(r"C:\repo\rules") ); assert_eq!( - without_verbatim_prefix(r"\\?\UNC\server\share\repo").as_deref(), + plain(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)); + fn a_long_path_loses_its_prefix_as_a_short_one_does() { + let long = format!(r"C:\repo\{}", "a".repeat(300)); + assert_eq!(plain(&format!(r"\\?\{long}")), Some(long)); + } + + #[test] + fn a_path_that_is_not_on_a_drive_or_a_share_keeps_its_prefix() { 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(), + r"\\?\repo", + r"\\?\", + r"C:\repo", + "/home/user", + ] { + assert_eq!(plain(path), None, "{path}"); + } + } + + #[test] + fn a_device_name_or_a_trailing_dot_or_space_does_not_look_plain() { + for part in [ + "NUL", + "nul.txt", + "com1.txt", + "COM0", + "lpt\u{b9}", + "aux ", + "name.", + "name ", + "CONOUT$", + ] { + assert!(!part_looks_plain(&utf16(part)), "{part}"); + } + for part in [ + "", + "C:", + "repo", + "null", + "console.md", + "com10", + "COM", + ".git", + "a.b", ] { - assert_eq!(without_verbatim_prefix(path), None, "{path}"); + assert!(part_looks_plain(&utf16(part)), "{part}"); } } #[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); + fn a_folder_and_a_long_path_inside_it_share_one_form() { + let folder = tempfile::tempdir().unwrap(); + let base = canonicalize(folder.path()).unwrap(); + let mut deep = base.clone(); + deep.extend(std::iter::repeat_n("a".repeat(50), 6)); + std::fs::create_dir_all(&deep).unwrap(); + assert!(deep.as_os_str().len() > 300); + assert!(canonicalize(&deep).unwrap().starts_with(&base)); + } + + #[cfg(windows)] + #[test] + fn a_path_only_the_verbatim_form_names_is_an_error() { + let folder = tempfile::tempdir().unwrap(); + // Only the verbatim form can make a name that ends in a dot. + let file = std::fs::canonicalize(folder.path()).unwrap().join("name."); + std::fs::write(&file, "").unwrap(); + let error = canonicalize(&file).unwrap_err(); + std::fs::remove_file(&file).unwrap(); + assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput); + assert!(error.to_string().contains("name."), "{error}"); } #[test] diff --git a/tests/hook_dispatch.rs b/tests/hook_dispatch.rs index 21b169fe..fc082143 100644 --- a/tests/hook_dispatch.rs +++ b/tests/hook_dispatch.rs @@ -2161,7 +2161,10 @@ fn a_firing_records_the_context_cursor_s_stop_has_no_field_for() { ); let quiet = scene.handler("quiet", "cat > /dev/null; printf '{}'"); scene.config(&format!( - "hooks:\n handlers:\n - id: jev\n exec: [sh, {jev}]\n events: [tool.after, turn.finish]\n - id: quiet\n exec: [sh, {quiet}]\n events: [turn.finish]\n" + // 20 seconds for each handler and 30 for each event. The test is + // about the record, not the deadline, and a machine that starts + // `sh` slowly reads the default 500 ms as a timeout. + "hooks:\n events:\n tool.after: {{budget_ms: 30000}}\n turn.finish: {{budget_ms: 30000}}\n handlers:\n - id: jev\n exec: [sh, {jev}]\n events: [tool.after, turn.finish]\n timeout_ms: 20000\n - id: quiet\n exec: [sh, {quiet}]\n events: [turn.finish]\n timeout_ms: 20000\n" )); scene.write_plan(); let records = |scene: &Scene| -> Vec { @@ -2273,7 +2276,10 @@ fn a_firing_records_what_a_passive_event_s_merge_discarded() { ); let quiet = scene.handler("quiet", "cat > /dev/null; printf '{}'"); scene.config(&format!( - "hooks:\n handlers:\n - id: guard\n exec: [sh, {guard}]\n events: [session.end]\n - id: rewrite\n exec: [sh, {rewrite}]\n events: [session.end]\n rewrites: true\n - id: quiet\n exec: [sh, {quiet}]\n events: [session.end]\n" + // 20 seconds for each handler and 30 for the event. The test is + // about the record, not the deadline, and a machine that starts + // `sh` slowly reads the default 500 ms as a timeout. + "hooks:\n events:\n session.end: {{budget_ms: 30000}}\n handlers:\n - id: guard\n exec: [sh, {guard}]\n events: [session.end]\n timeout_ms: 20000\n - id: rewrite\n exec: [sh, {rewrite}]\n events: [session.end]\n rewrites: true\n timeout_ms: 20000\n - id: quiet\n exec: [sh, {quiet}]\n events: [session.end]\n timeout_ms: 20000\n" )); scene.write_plan(); let end = serde_json::json!({ diff --git a/tests/hook_wrap.rs b/tests/hook_wrap.rs index 2ac69b25..d38d3e84 100644 --- a/tests/hook_wrap.rs +++ b/tests/hook_wrap.rs @@ -18,7 +18,12 @@ use serde_json::Value; /// The wrapper alone, on every event that shows a session in a workspace. const WRAPPER: &str = "hooks:\n handlers:\n - id: turn-wrap\n exec: [rune-hook-turn-wrap]\n events: [prompt.before, tool.before, tool.after, turn.finish]\n"; -/// The wrapper with room to be held mid-commit. +/// The wrapper with room to be held mid-commit, and with room for a slow +/// machine. A wrap is a snapshot and a commit, a handful of jj processes. +/// Under the default deadline of 1200 ms a loaded machine, or one with the +/// temp folder on a hard disk, reads `turn-wrap failed: timed out` where a +/// test expects the wrap. A test about what the wrapper does uses this +/// one. A test about the deadline keeps `WRAPPER`. const PATIENT_WRAPPER: &str = "hooks:\n events:\n turn.finish: {budget_ms: 20000}\n handlers:\n - id: turn-wrap\n exec: [rune-hook-turn-wrap]\n events: [prompt.before, tool.before, tool.after, turn.finish]\n timeout_ms: 15000\n"; const CLAUDE_PROMPT: [&str; 4] = ["--harness", "claude", "--native-event", "UserPromptSubmit"]; @@ -535,7 +540,7 @@ fn a_turn_is_not_wrapped_while_the_switch_is_off() { #[test] fn a_turn_of_one_session_is_wrapped_as_one_described_change() { let Some(scene) = Scene::new() else { return }; - scene.config(WRAPPER); + scene.config(PATIENT_WRAPPER); scene.write_plan(); scene.switch_on(); let prompt = scene.prompt("s1"); @@ -577,7 +582,7 @@ fn a_turn_of_one_session_is_wrapped_as_one_described_change() { #[test] fn a_turn_on_a_described_working_copy_keeps_the_owners_change() { let Some(scene) = Scene::new() else { return }; - scene.config(WRAPPER); + scene.config(PATIENT_WRAPPER); scene.write_plan(); scene.switch_on(); scene.edit("owner.txt", "the owner's edit\n"); @@ -819,7 +824,7 @@ fn a_turn_after_a_failed_stop_handler_waits_for_the_next_stop() { ), ); scene.config(&format!( - "hooks:\n handlers:\n - id: tests\n exec: [sh, {gate}]\n events: [turn.finish]\n order: 20\n - id: turn-wrap\n exec: [rune-hook-turn-wrap]\n events: [prompt.before, tool.before, tool.after, turn.finish]\n order: 10\n" + "hooks:\n events:\n turn.finish: {{budget_ms: 20000}}\n handlers:\n - id: tests\n exec: [sh, {gate}]\n events: [turn.finish]\n order: 20\n - id: turn-wrap\n exec: [rune-hook-turn-wrap]\n events: [prompt.before, tool.before, tool.after, turn.finish]\n order: 10\n timeout_ms: 15000\n" )); scene.write_plan(); scene.switch_on(); @@ -914,7 +919,7 @@ fn a_first_touch_keeps_its_key_when_the_snapshot_runs_past_the_timeout() { #[test] fn a_workspace_two_sessions_touched_is_wrapped_by_neither_until_the_owner_resets() { let Some(scene) = Scene::new() else { return }; - scene.config(WRAPPER); + scene.config(PATIENT_WRAPPER); scene.write_plan(); scene.switch_on(); scene.prompt("s1"); @@ -1122,7 +1127,7 @@ fn a_locked_slot_wraps_nothing_and_a_prompt_leaves_its_touch() { #[test] fn a_malformed_slot_wraps_nothing_until_the_owner_resets() { let Some(scene) = Scene::new() else { return }; - scene.config(WRAPPER); + scene.config(PATIENT_WRAPPER); scene.write_plan(); scene.switch_on(); std::fs::write(scene.slot(), "{not json").unwrap(); @@ -1176,7 +1181,7 @@ fn a_continued_turn_is_wrapped_only_when_it_finally_stops() { ), ); scene.config(&format!( - "hooks:\n handlers:\n - id: steer\n exec: [sh, {steer}]\n events: [turn.finish]\n order: 200\n - id: turn-wrap\n exec: [rune-hook-turn-wrap]\n events: [prompt.before, turn.finish]\n order: 10\n" + "hooks:\n events:\n turn.finish: {{budget_ms: 20000}}\n handlers:\n - id: steer\n exec: [sh, {steer}]\n events: [turn.finish]\n order: 200\n - id: turn-wrap\n exec: [rune-hook-turn-wrap]\n events: [prompt.before, turn.finish]\n order: 10\n timeout_ms: 15000\n" )); scene.write_plan(); scene.switch_on(); diff --git a/tests/init.rs b/tests/init.rs index 176cd82a..0c713934 100644 --- a/tests/init.rs +++ b/tests/init.rs @@ -392,6 +392,9 @@ fn bare_name_resolves_under_rune_quests_and_quest_flag_binds_it() { let destination = quests.path().join("demo"); assert!(destination.join("Makefile").is_file()); let state = fs::read_to_string(home.path().join(".config/rune/state.yaml")).unwrap(); + // The state names the destination in its canonical form, and the temp + // folder can be written another way, as a short name on Windows. + let destination = rune::folders::canonicalize(&destination).unwrap(); assert!(state.contains(&destination.to_string_lossy().to_string())); } diff --git a/tests/install_freshness.rs b/tests/install_freshness.rs index 6f2f62d9..d72adc4c 100644 --- a/tests/install_freshness.rs +++ b/tests/install_freshness.rs @@ -122,8 +122,12 @@ fn stale_git_source_refuses_install_without_allow_stale() { .lines() .find(|line| line.starts_with("fix: ")) .expect("the error must include one fix line"); - assert!(fix_line.contains(&module.path().display().to_string())); - assert!(fix_line.contains(&target.path().display().to_string())); + // The fix line names both folders in their canonical form, and the temp + // folder can be written another way, as a short name on Windows. + let module_folder = rune::folders::canonicalize(module.path()).unwrap(); + let target_folder = rune::folders::canonicalize(target.path()).unwrap(); + assert!(fix_line.contains(&module_folder.display().to_string())); + assert!(fix_line.contains(&target_folder.display().to_string())); assert!(fix_line.ends_with("--allow-stale")); assert!(!fix_line.contains('<')); assert!(!fix_line.contains('>'));