From 140b884a1a4463d91ce1041185ff8bf5b8a786da Mon Sep 17 00:00:00 2001 From: jj Date: Tue, 17 Nov 2026 13:14:17 +0100 Subject: [PATCH 1/5] refresh, diff: fix -f, -P and -z on files shadowed by later patches refresh -f on a stack without Index: lines could emit a file twice, once from the fresh diff and once from the old patch. diff of a lower patch now takes files changed by later patches from the next patch's backup, which also works for stacks pushed by gnu quilt without q's metadata. diff -z and refresh -z no longer trust an expected state recorded for a different patch text, like after checking the patch file out again --- src/apply.rs | 63 +++++++++++++------- src/commands/diff.rs | 31 ++++++---- src/commands/mod.rs | 68 ++++++++++++++++++++- src/commands/refresh.rs | 29 ++++++--- src/diff.rs | 57 ++++++++++-------- src/expected.rs | 6 +- src/patchfile.rs | 125 ++++++++++++++++++++++++++++++++------ tests/stack.rs | 129 ++++++++++++++++++++++++++++++++++++++++ 8 files changed, 420 insertions(+), 88 deletions(-) diff --git a/src/apply.rs b/src/apply.rs index 23adbfe..317ff75 100644 --- a/src/apply.rs +++ b/src/apply.rs @@ -11,7 +11,7 @@ use std::collections::HashSet; use std::fs::{self, File}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; -use tempfile::{NamedTempFile, tempdir}; +use tempfile::{NamedTempFile, TempDir, tempdir}; pub struct ApplyResult { pub clean: bool, @@ -464,34 +464,22 @@ pub(crate) fn restore_patch_files( Ok(()) } -/// Whether popping `entry` would lose no changes: the working tree matches -/// what applying the patch to its backups produces. `use_expected_state` -/// trusts a current recorded expected state outright (for the top patch). -pub(crate) fn patch_removes_cleanly( +/// A scratch tree with `entry` applied to copies of its backups of +/// `tracked`: the files as the patch file says it leaves them. `None` if the +/// patch doesn't apply to them. +pub(crate) fn apply_to_backups( state: &State, entry: &PatchEntry, - use_expected_state: bool, tracked: &[PathBuf], -) -> Result { +) -> Result> { let patch = &entry.name; - if expected_state_is_current(state, patch) { - if use_expected_state { - return expected_state_matches(state, patch, tracked); - } - // A match is conclusive for any patch in the stack and saves - // re-applying it below; a mismatch still gets the full check. - if expected_state_matches(state, patch, tracked)? { - return Ok(true); - } - } + let workdir = tempdir()?; + populate_pop_workdir(state, patch, tracked, workdir.path())?; if patch_body(&state.patch_path(patch))?.is_empty() { - return Ok(tracked.is_empty()); + return Ok(Some(workdir)); } let patch_path = patch_file_for_apply(&state.patch_path(patch), entry)?; let input = fs::read(patch_path.path())?; - - let workdir = tempdir()?; - populate_pop_workdir(state, patch, tracked, workdir.path())?; let args = PatchFlags { strip: strip_level(entry), reverse: is_reversed(entry), @@ -513,9 +501,40 @@ pub(crate) fn patch_removes_cleanly( .status() .context("failed to run patch")?; if !status.success() { - return Ok(false); + return Ok(None); } } + Ok(Some(workdir)) +} + +/// Whether popping `entry` would lose no changes: the working tree matches +/// what applying the patch to its backups produces. `use_expected_state` +/// trusts a current recorded expected state outright (for the top patch). +pub(crate) fn patch_removes_cleanly( + state: &State, + entry: &PatchEntry, + use_expected_state: bool, + tracked: &[PathBuf], +) -> Result { + let patch = &entry.name; + if expected_state_is_current(state, patch) { + if use_expected_state { + return expected_state_matches(state, patch, tracked); + } + // A match is conclusive for any patch in the stack and saves + // re-applying it below; a mismatch still gets the full check. + if expected_state_matches(state, patch, tracked)? { + return Ok(true); + } + } + if patch_body(&state.patch_path(patch))?.is_empty() { + return Ok(tracked.is_empty()); + } + let patch_path = patch_file_for_apply(&state.patch_path(patch), entry)?; + let input = fs::read(patch_path.path())?; + let Some(workdir) = apply_to_backups(state, entry, tracked)? else { + return Ok(false); + }; let mut files: HashSet = tracked.iter().cloned().collect(); files.extend(filenames_in_text_order( diff --git a/src/commands/diff.rs b/src/commands/diff.rs index 3f0b3a7..e8767d3 100644 --- a/src/commands/diff.rs +++ b/src/commands/diff.rs @@ -1,7 +1,6 @@ use crate::commands::*; use crate::config::*; use crate::diff::*; -use crate::expected::*; use crate::patchfile::strip_arg; use crate::state::State; use anyhow::{Context, Result, bail}; @@ -46,13 +45,14 @@ pub(crate) fn cmd_diff(args: Vec) -> Result<()> { let newer_files = files_modified_by_newer_patches(&state, &patch, &tracked)?; if let Some(combine) = combine { let range = applied_range(&state, &state.applied()?, &combine, &patch)?; - emit_combined_diff(&state, &range, &files, &opts, &newer_files)?; + emit_combined_diff(&state, &range, &files, &opts)?; + } else if opts.relative { + opts.exclude = newer_files.clone(); + let patched = patched_tree(&state, &patch)?; + opts.relative_root = Some(patched.path().to_path_buf()); + emit_diff(&state, &patch, &tracked, &files, &opts, io::stdout())?; } else { - if opts.relative { - opts.exclude = newer_files.clone(); - } else { - opts.use_expected_for = newer_files.clone(); - } + opts.new_side_for = next_patch_backups(&state, &patch, &newer_files)?; emit_diff(&state, &patch, &tracked, &files, &opts, io::stdout())?; } if !newer_files.is_empty() { @@ -69,7 +69,6 @@ fn emit_combined_diff( patches: &[String], selected: &[PathBuf], opts: &DiffOpts, - use_expected_for: &[PathBuf], ) -> Result<()> { let Some(first) = patches.first() else { return Ok(()); @@ -90,20 +89,26 @@ fn emit_combined_diff( let selected: HashSet<_> = selected.iter().cloned().collect(); files.retain(|file| selected.contains(file)); } + let next_backups = next_patch_backups(state, last, &files)?; let colors = opts.color.then(DiffColors::from_env); let mut stdout = io::stdout(); for file in files { let old = state.backup_dir(first).join(&file); - let new = if use_expected_for.iter().any(|candidate| candidate == &file) { - expected_file(state, last, &file) - } else { - state.root.join(&file) + let (new, new_missing) = match next_backups.get(&file) { + Some(backup) => ( + backup.clone(), + backup.metadata().map_or(true, |m| m.len() == 0), + ), + None => { + let new = state.root.join(&file); + let missing = !new.exists(); + (new, missing) + } }; let old_empty = old .metadata() .map(|metadata| metadata.len() == 0) .unwrap_or(false); - let new_missing = !new.exists(); let old_arg = if old.exists() { old.as_path() } else { diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 3535dc8..d630727 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -23,10 +23,13 @@ pub(crate) use stack::{ cmd_delete, cmd_fold, cmd_fork, cmd_import, cmd_new, cmd_pop, cmd_push, cmd_rename, }; +use crate::apply::apply_to_backups; +use crate::expected::{expected_dir, expected_state_is_current}; use crate::state::State; use anyhow::{Context, Result, bail}; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; +use tempfile::TempDir; pub fn applied_patch(state: &State, patch: Option<&str>) -> Result { state.require_series()?; @@ -85,6 +88,69 @@ fn files_modified_by_newer_patches( Ok(modified) } +/// For each of `files` that a patch applied after `patch` changes too, the +/// backup of the first such patch: the file as `patch` left it. +fn next_patch_backups( + state: &State, + patch: &str, + files: &[PathBuf], +) -> Result> { + let mut backups = HashMap::new(); + if files.is_empty() { + return Ok(backups); + } + let files: HashSet<&PathBuf> = files.iter().collect(); + for later in newer_applied_patches(state, patch)? { + for file in state.tracked_files(&later)? { + if files.contains(&file) && !backups.contains_key(&file) { + backups.insert(file.clone(), state.backup_dir(&later).join(&file)); + } + } + if backups.len() == files.len() { + break; + } + } + Ok(backups) +} + +/// `patch`'s files as its patch file leaves them, which `diff -z` and +/// `refresh -z` compare the working tree against. +enum PatchedTree { + /// The expected state recorded for the current patch text. + Expected(PathBuf), + /// The patch applied to copies of its backups. + Scratch(TempDir), +} + +impl PatchedTree { + fn path(&self) -> &Path { + match self { + Self::Expected(path) => path, + Self::Scratch(dir) => dir.path(), + } + } +} + +fn patched_tree(state: &State, patch: &str) -> Result { + if expected_state_is_current(state, patch) { + return Ok(PatchedTree::Expected(expected_dir(state, patch))); + } + let entry = state + .entries()? + .into_iter() + .find(|entry| entry.name == patch) + .with_context(|| format!("Patch {} is not in series", state.display_patch(patch)))?; + let tracked = state.tracked_files(patch)?; + apply_to_backups(state, &entry, &tracked)? + .map(PatchedTree::Scratch) + .with_context(|| { + format!( + "Patch {} does not apply to its backup files", + state.display_patch(patch) + ) + }) +} + /// The applied patches from `first` through `last`, for `--combine`. `first` /// of `-` means the bottom of the stack. fn applied_range( diff --git a/src/commands/refresh.rs b/src/commands/refresh.rs index 80029c5..2a85b5a 100644 --- a/src/commands/refresh.rs +++ b/src/commands/refresh.rs @@ -54,6 +54,11 @@ pub(crate) fn cmd_refresh(args: Vec) -> Result<()> { let patch = applied_patch(&state, patch.as_deref())?; opts.strip = strip_for(&state, &patch, strip, "refresh")?; opts.relative = fork_name.is_some(); + let patched = match fork_name { + Some(_) => Some(patched_tree(&state, &patch)?), + None => None, + }; + opts.relative_root = patched.as_ref().map(|tree| tree.path().to_path_buf()); let tracked = state.tracked_files(&patch)?; let preserved_files = files_modified_by_newer_patches(&state, &patch, &tracked)?; if !force && !preserved_files.is_empty() { @@ -73,7 +78,16 @@ pub(crate) fn cmd_refresh(args: Vec) -> Result<()> { } create_parent_dir(&dest)?; write_patch_text(&dest, &new_text)?; - seed_fork_backup(&state, &patch, &new_patch, &new_text, opts.strip.level())?; + let patched = patched + .as_ref() + .expect("a fork diffs against the patched tree"); + seed_fork_backup( + &state, + patched.path(), + &new_patch, + &new_text, + opts.strip.level(), + )?; let before = state.patch_after(state.applied()?.last().map(String::as_str))?; state.insert_in_series( &PatchEntry { @@ -358,22 +372,19 @@ fn report_or_strip_trailing_ws_for_files( } /// Back up the files of a `refresh -z` fork: each file as the old patch left -/// it, so the fork holds only the changes made since. +/// it (in `patched`), so the fork holds only the changes made since. fn seed_fork_backup( state: &State, - old_patch: &str, + patched: &Path, new_patch: &str, fork_text: &str, strip: usize, ) -> Result<()> { for file in filenames_in_text_order(fork_text, strip) { let backup = state.backup_dir(new_patch).join(&file); - let expected = expected_file(state, old_patch, &file); - let old_backup = state.backup_dir(old_patch).join(&file); - if expected.exists() { - copy_creating_dirs(&expected, &backup)?; - } else if old_backup.metadata().is_ok_and(|m| m.len() != 0) { - copy_creating_dirs(&old_backup, &backup)?; + let old = patched.join(&file); + if old.exists() { + copy_creating_dirs(&old, &backup)?; } else { create_parent_dir(&backup)?; File::create(backup)?; diff --git a/src/diff.rs b/src/diff.rs index b72e80a..92966ad 100644 --- a/src/diff.rs +++ b/src/diff.rs @@ -1,12 +1,11 @@ use crate::color::{color_arg, escape}; use crate::config::*; -use crate::expected::*; use crate::patchfile::*; use crate::state::State; use anyhow::{Context, Result, bail}; use chrono::{DateTime, Local}; use lexopt::ValueExt; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::ffi::OsString; use std::fs; use std::io::{self, Write}; @@ -24,7 +23,12 @@ pub struct DiffOpts { pub relative: bool, pub sort: bool, pub exclude: Vec, - pub use_expected_for: Vec, + /// For `relative`, the tree holding each file as the patch leaves it; + /// a missing file there was deleted by the patch. + pub relative_root: Option, + /// The new side of files later patches change too, by file: the next + /// such patch's backup, where an empty file means the file is absent. + pub new_side_for: HashMap, pub diff_utility: Option, pub color: bool, /// Read the new side of each file from here instead of the working tree. @@ -43,7 +47,8 @@ impl Default for DiffOpts { relative: false, sort: false, exclude: Vec::new(), - use_expected_for: Vec::new(), + relative_root: None, + new_side_for: HashMap::new(), diff_utility: None, color: false, new_root: None, @@ -155,13 +160,12 @@ pub(crate) fn emit_diff( files.retain(|f| !exclude.contains(f)); } let colors = opts.color.then(DiffColors::from_env); - let deleted_files = expected_deleted(state, patch)?; // Spawning `diff` per file dominates refresh time, so run them // concurrently and then emit the results in file order. let mut jobs = Vec::new(); let mut prep_error = None; for file in files { - match prepare_diff_job(state, patch, opts, &deleted_files, file) { + match prepare_diff_job(state, patch, opts, file) { Ok(Some(job)) => jobs.push(job), Ok(None) => {} Err(err) => { @@ -227,29 +231,32 @@ fn prepare_diff_job( state: &State, patch: &str, opts: &DiffOpts, - deleted_files: &HashSet, file: PathBuf, ) -> Result> { - let expected = expected_file(state, patch, &file); - let expected_is_deleted = deleted_files.contains(&file); - let old = if opts.relative && expected.exists() { - expected.clone() - } else { - state.backup_dir(patch).join(&file) + let (old, old_empty) = match opts.relative_root.as_ref().filter(|_| opts.relative) { + Some(root) => { + let old = root.join(&file); + let empty = !old.exists(); + (old, empty) + } + None => { + let old = state.backup_dir(patch).join(&file); + let empty = old.metadata()?.len() == 0; + (old, empty) + } }; - let use_expected = opts.use_expected_for.iter().any(|f| f == &file); - let new = if use_expected && expected.exists() { - expected_file(state, patch, &file) - } else if let Some(new_root) = &opts.new_root { - new_root.join(&file) + let (new, new_missing) = if let Some(next_backup) = opts.new_side_for.get(&file) { + let missing = next_backup.metadata().map_or(true, |m| m.len() == 0); + (next_backup.clone(), missing) } else { - state.root.join(&file) + let new = match &opts.new_root { + Some(new_root) => new_root.join(&file), + None => state.root.join(&file), + }; + let missing = !new.exists(); + (new, missing) }; - if opts.relative && expected_is_deleted && !new.exists() { - return Ok(None); - } - let old_empty = old.metadata()?.len() == 0; - if old_empty && !new.exists() { + if old_empty && new_missing { return Ok(None); } let old_arg = if old_empty { @@ -257,7 +264,7 @@ fn prepare_diff_job( } else { old.as_path() }; - let new_arg = if !new.exists() { + let new_arg = if new_missing { Path::new("/dev/null") } else { new.as_path() diff --git a/src/expected.rs b/src/expected.rs index e39d86d..d0d6205 100644 --- a/src/expected.rs +++ b/src/expected.rs @@ -16,8 +16,12 @@ fn meta_dir(state: &State, patch: &str) -> PathBuf { state.pc_dir.join(".q").join(patch) } +pub(crate) fn expected_dir(state: &State, patch: &str) -> PathBuf { + meta_dir(state, patch).join("expected") +} + pub(crate) fn expected_file(state: &State, patch: &str, file: &Path) -> PathBuf { - meta_dir(state, patch).join("expected").join(file) + expected_dir(state, patch).join(file) } /// Files the patch is expected to have deleted. diff --git a/src/patchfile.rs b/src/patchfile.rs index 66277bb..786e2fb 100644 --- a/src/patchfile.rs +++ b/src/patchfile.rs @@ -126,25 +126,83 @@ pub(crate) fn filenames_in_text_order(text: &str, strip: usize) -> Vec /// The per-file sections of a patch body that touch one of `wanted`. pub(crate) fn body_for_files(body: &str, strip: usize, wanted: &HashSet) -> String { - let mut out = String::new(); - let mut block = String::new(); - let mut flush = |block: &mut String| { - if filenames_in_text_order(block, strip) - .iter() - .any(|file| wanted.contains(file)) - { - out.push_str(block); + file_sections(body) + .into_iter() + .filter(|section| { + filenames_in_text_order(section, strip) + .iter() + .any(|file| wanted.contains(file)) + }) + .collect() +} + +/// Split a patch body into one section per file. A section starts at an +/// `Index:` or `diff` line, or at the file labels when it has neither, so +/// patches written with `--no-index` split too. Unified hunks are skipped by +/// their line counts, since a removed `-- x` line reads as `--- x`. +fn file_sections(body: &str) -> Vec<&str> { + let lines: Vec<&str> = body.split_inclusive('\n').collect(); + let mut sections = Vec::new(); + let mut start = 0; + let mut offset = 0; + // Whether the current section has named its file yet. + let mut has_file = false; + // Whether it has a git `diff` line. + let mut has_diff_line = false; + // Lines left in the current unified hunk, old and new side. + let (mut old_left, mut new_left) = (0usize, 0usize); + for (i, line) in lines.iter().enumerate() { + let next = lines.get(i + 1).copied().unwrap_or(""); + if old_left > 0 || new_left > 0 { + match line.as_bytes().first() { + Some(b'-') => old_left = old_left.saturating_sub(1), + Some(b'+') => new_left = new_left.saturating_sub(1), + Some(b'\\') => {} + _ => { + old_left = old_left.saturating_sub(1); + new_left = new_left.saturating_sub(1); + } + } + offset += line.len(); + continue; } - block.clear(); - }; - for line in body.split_inclusive('\n') { - if line.starts_with("Index: ") && !block.is_empty() { - flush(&mut block); + let is_diff_line = line.starts_with("diff "); + let starts_header = line.starts_with("Index: ") || is_diff_line; + let starts_labels = (line.starts_with("--- ") && next.starts_with("+++ ")) + || (line.starts_with("*** ") + && !line.trim_end().ends_with(" ****") + && next.starts_with("--- ")); + // A git `diff` line may head a section with no labels (a rename). + if (starts_header && (has_file || has_diff_line)) || (starts_labels && has_file) { + sections.push(&body[start..offset]); + start = offset; + has_file = false; + has_diff_line = false; + } + has_diff_line |= is_diff_line; + has_file |= line.starts_with("+++ ") + || (line.starts_with("--- ") && !line.trim_end().ends_with(" ----")); + if let Some((old, new)) = unified_hunk_lengths(line) { + (old_left, new_left) = (old, new); } - block.push_str(line); + offset += line.len(); } - flush(&mut block); - out + if start < body.len() { + sections.push(&body[start..]); + } + sections +} + +/// The old and new line counts of a unified `@@ -a,b +c,d @@` hunk header. +fn unified_hunk_lengths(line: &str) -> Option<(usize, usize)> { + let mut ranges = line.strip_prefix("@@ -")?.split(' '); + let count = |range: &str| match range.split_once(',') { + Some((_, count)) => count.parse().ok(), + None => range.parse::().ok().map(|_| 1), + }; + let old = count(ranges.next()?)?; + let new = count(ranges.next()?.strip_prefix('+')?)?; + Some((old, new)) } /// The file name in a `---`/`+++`/`***` label, without timestamp or quotes. @@ -275,9 +333,42 @@ pub(crate) fn is_reversed(entry: &PatchEntry) -> bool { #[cfg(test)] mod tests { - use super::{body_of, filenames_in_text_order, header_of}; + use super::{body_for_files, body_of, file_sections, filenames_in_text_order, header_of}; + use std::collections::HashSet; use std::path::PathBuf; + #[test] + fn splits_sections_without_index_lines() { + let body = "--- a/one\n+++ b/one\n@@ -1 +1 @@\n--- x\n+++ y\n\ + --- a/two\n+++ b/two\n@@ -1 +1 @@\n-a\n+b\n\\ No newline at end of file\n"; + assert_eq!( + file_sections(body), + [ + "--- a/one\n+++ b/one\n@@ -1 +1 @@\n--- x\n+++ y\n", + "--- a/two\n+++ b/two\n@@ -1 +1 @@\n-a\n+b\n\\ No newline at end of file\n", + ] + ); + let wanted = HashSet::from([PathBuf::from("two")]); + assert_eq!( + body_for_files(body, 1, &wanted), + "--- a/two\n+++ b/two\n@@ -1 +1 @@\n-a\n+b\n\\ No newline at end of file\n" + ); + } + + #[test] + fn keeps_index_and_git_headers_with_their_section() { + let body = "Index: a/one\n===\n--- a/one\n+++ b/one\n@@ -1 +1 @@\n-a\n+b\n\ + diff --git a/two b/two\nindex 1..2\n--- a/two\n+++ b/two\n@@ -0,0 +1 @@\n+c\n\ + diff --git a/x b/y\nrename from x\nrename to y\n\ + diff --git a/z b/z\n--- a/z\n+++ b/z\n@@ -1 +0,0 @@\n-z\n"; + let sections = file_sections(body); + assert_eq!(sections.len(), 4, "{sections:?}"); + assert!(sections[0].starts_with("Index: a/one")); + assert!(sections[1].starts_with("diff --git a/two")); + assert!(sections[2].starts_with("diff --git a/x")); + assert!(sections[3].starts_with("diff --git a/z")); + } + #[test] fn extracts_filenames_using_strip_level() { let text = "--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -1 +1 @@\n-a\n+b\n"; diff --git a/tests/stack.rs b/tests/stack.rs index 4370ae4..707eb7c 100644 --- a/tests/stack.rs +++ b/tests/stack.rs @@ -792,3 +792,132 @@ fn import_rejects_paths_without_a_file_name() { .failure() .stderr(predicate::str::contains("panicked").not()); } + +/// Two patches over `file_a`..`file_c` where p2 also changes `file_b`, built +/// with `-p ab --no-index` like a stack that keeps no `Index:` lines. +fn shadowed_stack_without_index() -> tempfile::TempDir { + let dir = tempdir().unwrap(); + for name in ["file_a", "file_b", "file_c"] { + fs::write(dir.path().join(name), format!("base {name}\n")).unwrap(); + } + q(dir.path()).args(["new", "p1.diff"]).assert().success(); + q(dir.path()) + .args(["add", "file_a", "file_b", "file_c"]) + .assert() + .success(); + for name in ["file_a", "file_b", "file_c"] { + fs::write(dir.path().join(name), format!("p1 {name}\n")).unwrap(); + } + q(dir.path()) + .args(["refresh", "-p", "ab", "--no-index", "--no-timestamps"]) + .assert() + .success(); + q(dir.path()).args(["new", "p2.diff"]).assert().success(); + q(dir.path()).args(["add", "file_b"]).assert().success(); + fs::write(dir.path().join("file_b"), "p2 file_b\n").unwrap(); + q(dir.path()) + .args(["refresh", "-p", "ab", "--no-index", "--no-timestamps"]) + .assert() + .success(); + dir +} + +#[test] +fn refresh_force_without_index_lines_keeps_each_file_once() { + let dir = shadowed_stack_without_index(); + fs::write(dir.path().join("file_a"), "updated p1 file_a\n").unwrap(); + q(dir.path()) + .args([ + "refresh", + "-f", + "-p", + "ab", + "--no-index", + "--no-timestamps", + "p1.diff", + ]) + .assert() + .success(); + + let patch = fs::read_to_string(dir.path().join("patches/p1.diff")).unwrap(); + let files: Vec<_> = patch + .lines() + .filter_map(|line| line.strip_prefix("+++ b/")) + .collect(); + assert_eq!(files, ["file_a", "file_b", "file_c"], "{patch}"); + assert!(patch.contains("+updated p1 file_a"), "{patch}"); + assert!(patch.contains("+p1 file_b"), "{patch}"); + assert!(!patch.contains("+p2 file_b"), "{patch}"); +} + +#[test] +fn diff_of_lower_patch_takes_shadowed_files_from_next_patch_backup() { + let dir = shadowed_stack_without_index(); + // A stack pushed without q's metadata, as by GNU quilt. + let _ = fs::remove_dir_all(dir.path().join(".pc/.q")); + + q(dir.path()) + .args([ + "diff", + "-p", + "ab", + "--no-index", + "--no-timestamps", + "-P", + "p1.diff", + ]) + .assert() + .success() + .stdout(predicate::str::contains("+p1 file_b")) + .stdout(predicate::str::contains("p2 file_b").not()); + q(dir.path()) + .args([ + "diff", + "-p", + "ab", + "--no-index", + "--no-timestamps", + "--combine", + "-", + "-P", + "p1.diff", + ]) + .assert() + .success() + .stdout(predicate::str::contains("+p1 file_b")) + .stdout(predicate::str::contains("p2 file_b").not()); +} + +#[test] +fn diff_z_ignores_expected_state_recorded_for_other_patch_text() { + let dir = tempdir().unwrap(); + fs::write(dir.path().join("file"), "base\n").unwrap(); + q(dir.path()).args(["new", "p1.diff"]).assert().success(); + q(dir.path()).args(["add", "file"]).assert().success(); + fs::write(dir.path().join("file"), "p1\n").unwrap(); + q(dir.path()) + .args(["refresh", "--no-timestamps"]) + .assert() + .success(); + let committed = fs::read_to_string(dir.path().join("patches/p1.diff")).unwrap(); + + // Refresh work in progress, then put the committed patch text back, as + // checking out the patch file from version control does. + fs::write(dir.path().join("file"), "wip\n").unwrap(); + q(dir.path()) + .args(["refresh", "--no-timestamps"]) + .assert() + .success(); + fs::write(dir.path().join("patches/p1.diff"), &committed).unwrap(); + + q(dir.path()) + .args(["diff", "-z", "--no-timestamps"]) + .assert() + .success() + .stdout(predicate::str::contains("-p1\n+wip\n")); + q(dir.path()) + .args(["pop"]) + .assert() + .failure() + .stderr(predicate::str::contains("does not remove cleanly")); +} From ebbc7f0f3d532aa05efd7423af432b4cba4fce59 Mon Sep 17 00:00:00 2001 From: jj Date: Tue, 17 Nov 2026 13:18:59 +0100 Subject: [PATCH 2/5] pop: move backups back and discard them, check expected state by stat pop restored each file by copying its backup through a userspace buffer and never removed .pc/. the stale backups kept files the patch no longer touches tracked, so a later refresh pulled upstream changes into the patch and pop reverted them. pop, delete and a failed push now rename backups into place (falling back to a copy), touch restored files like quilt pop -t, and remove .pc/ and .pc/.q/ the expected state also records dev, inode, size, mtime and ctime of the patch file and each tracked file. a file whose stat still matches and is older than the record itself (git's racy-clean rule) isn't read again, and push --refresh keeps the copies when only the patch text changed. on a 377 patch stack on macos, pop -a goes from ~2.0s to ~1.55s and push -a --refresh from ~7.2s to ~5.5s --- src/apply.rs | 90 +++++++++++++++--- src/commands/stack.rs | 3 +- src/expected.rs | 209 ++++++++++++++++++++++++++++++++++++++---- src/fsutil.rs | 12 +++ tests/stack.rs | 144 +++++++++++++++++++++++++++++ 5 files changed, 426 insertions(+), 32 deletions(-) diff --git a/src/apply.rs b/src/apply.rs index 317ff75..9e2a88b 100644 --- a/src/apply.rs +++ b/src/apply.rs @@ -434,36 +434,98 @@ fn reverse_applies(state: &State, entry: &PatchEntry) -> bool { .is_ok_and(|status| status.success()) } +/// Undo `patch` in the working tree from its backups and discard them, as +/// quilt does when a patch is popped, deleted or fails to push. pub(crate) fn restore_patch(state: &State, patch: &str, verbose: bool) -> Result<()> { let files = state.tracked_files(patch)?; - restore_patch_files(state, patch, &files, verbose) + unapply_patch_files(state, patch, &files, verbose) } -pub(crate) fn restore_patch_files( +/// Restore `files` from `patch`'s backups, moving rather than copying them, +/// then remove the backups and the recorded expected state. +pub(crate) fn unapply_patch_files( state: &State, patch: &str, files: &[PathBuf], verbose: bool, ) -> Result<()> { for file in files { - let backup = state.backup_dir(patch).join(file); - let dest = state.root.join(file); - create_parent_dir(&dest)?; - if backup.metadata()?.len() == 0 { - if verbose { - println!("Removing {}", file.display()); + restore_file(state, patch, file, verbose, true)?; + } + discard_patch_backups(state, patch) +} + +/// Remove `.pc/` and q's metadata for it. +pub(crate) fn discard_patch_backups(state: &State, patch: &str) -> Result<()> { + let meta_root = state.pc_dir.join(".q"); + for (dir, root) in [ + (state.backup_dir(patch), &state.pc_dir), + (meta_dir(state, patch), &meta_root), + ] { + match fs::remove_dir_all(&dir) { + Err(err) if err.kind() != std::io::ErrorKind::NotFound => { + return Err(err).with_context(|| format!("failed to remove {}", dir.display())); } - let _ = fs::remove_file(&dest); - } else { - if verbose { - println!("Restoring {}", file.display()); + _ => {} + } + // Patch names like `debian/foo.patch` leave `.pc/debian/` behind. + let mut parent = dir.parent(); + while let Some(p) = parent.filter(|p| p.starts_with(root) && p != root) { + if fs::remove_dir(p).is_err() { + break; } - copy_keeping_hard_links(&backup, &dest)?; + parent = p.parent(); } } Ok(()) } +/// Restore `files` from `patch`'s backups, keeping the backups. +pub(crate) fn restore_patch_files( + state: &State, + patch: &str, + files: &[PathBuf], + verbose: bool, +) -> Result<()> { + for file in files { + restore_file(state, patch, file, verbose, false)?; + } + Ok(()) +} + +/// Put `file` back the way `patch`'s backup has it. With `consume`, the +/// backup is moved into place (it is about to be discarded anyway) and the +/// file's mtime is set to now, like `quilt pop` does with `backup-files -t`. +fn restore_file( + state: &State, + patch: &str, + file: &Path, + verbose: bool, + consume: bool, +) -> Result<()> { + let backup = state.backup_dir(patch).join(file); + let dest = state.root.join(file); + create_parent_dir(&dest)?; + let metadata = backup.metadata()?; + if metadata.len() == 0 { + if verbose { + println!("Removing {}", file.display()); + } + let _ = fs::remove_file(&dest); + return Ok(()); + } + if verbose { + println!("Restoring {}", file.display()); + } + if consume && fs::rename(&backup, &dest).is_ok() { + if !has_other_hard_links(&metadata) { + filetime::set_file_mtime(&dest, filetime::FileTime::now())?; + } + return Ok(()); + } + copy_keeping_hard_links(&backup, &dest) +} + /// A scratch tree with `entry` applied to copies of its backups of /// `tracked`: the files as the patch file says it leaves them. `None` if the /// patch doesn't apply to them. @@ -517,7 +579,7 @@ pub(crate) fn patch_removes_cleanly( tracked: &[PathBuf], ) -> Result { let patch = &entry.name; - if expected_state_is_current(state, patch) { + if expected_state_is_current_for(state, patch, tracked) { if use_expected_state { return expected_state_matches(state, patch, tracked); } diff --git a/src/commands/stack.rs b/src/commands/stack.rs index 82a8b67..2cc5d2b 100644 --- a/src/commands/stack.rs +++ b/src/commands/stack.rs @@ -328,9 +328,10 @@ pub(crate) fn cmd_pop(args: Vec) -> Result<()> { "Patch {} appears to be empty, removing", state.display_patch(&patch) ); + discard_patch_backups(&state, &patch)?; } else { println!("Removing patch {}", state.display_patch(&patch)); - restore_patch_files(&state, &patch, &tracked, !quiet)?; + unapply_patch_files(&state, &patch, &tracked, !quiet)?; } if !quiet { println!(); diff --git a/src/expected.rs b/src/expected.rs index d0d6205..25d0f43 100644 --- a/src/expected.rs +++ b/src/expected.rs @@ -3,16 +3,21 @@ //! `.pc/.q//`. While the patch file and its tracked files are //! unchanged, this lets pop and diff compare against it instead of //! re-applying the patch in a scratch tree. +//! +//! Alongside the copies, `stat` records the inode, size and timestamps of the +//! patch file and of each live file. A file whose stat still matches has not +//! been written since, so most checks need no reading at all. use crate::fsutil::{copy_creating_dirs, files_match}; use crate::patchfile::patch_text; use crate::state::{State, sort_tracked}; use anyhow::Result; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::fs::{self, File}; use std::path::{Path, PathBuf}; +use std::time::SystemTime; -fn meta_dir(state: &State, patch: &str) -> PathBuf { +pub(crate) fn meta_dir(state: &State, patch: &str) -> PathBuf { state.pc_dir.join(".q").join(patch) } @@ -51,28 +56,78 @@ pub(crate) fn record_expected_state_with_text( ) -> Result<()> { let meta = meta_dir(state, patch); let expected = meta.join("expected"); - let _ = fs::remove_dir_all(&meta); - fs::create_dir_all(&expected)?; let mut tracked = tracked.to_vec(); sort_tracked(&mut tracked); + let patch_path = state.patch_path(patch); + + // Only the patch text changed (as after `push --refresh`): keep the copies. + if let Some(snapshot) = recorded_files_unchanged(state, &meta, &tracked) { + fs::write(meta.join("patch"), patch_text)?; + write_snapshot(&meta, &patch_path, &snapshot.files)?; + touch_backup_timestamp(state, patch)?; + return Ok(()); + } + + let _ = fs::remove_dir_all(&meta); + fs::create_dir_all(&expected)?; let mut deleted = String::new(); + let mut stats = HashMap::new(); for file in &tracked { let src = state.root.join(file); - if src.exists() { - copy_creating_dirs(&src, &expected.join(file))?; - } else { - deleted.push_str(&file.to_string_lossy()); - deleted.push('\n'); + match fs::metadata(&src) { + Ok(metadata) => { + copy_creating_dirs(&src, &expected.join(file))?; + if let Some(key) = stat_key(&metadata) { + stats.insert(file.clone(), key); + } + } + Err(_) => { + deleted.push_str(&file.to_string_lossy()); + deleted.push('\n'); + } } } fs::write(meta.join("deleted"), deleted)?; fs::write(meta.join("patch"), patch_text)?; fs::write(meta.join("files"), file_list(&tracked))?; + write_snapshot(&meta, &patch_path, &stats)?; + touch_backup_timestamp(state, patch)?; + Ok(()) +} + +fn touch_backup_timestamp(state: &State, patch: &str) -> Result<()> { fs::create_dir_all(state.backup_dir(patch))?; File::create(state.backup_dir(patch).join(".timestamp"))?; Ok(()) } +/// The recorded snapshot, if the recorded expected state still holds for +/// `tracked` exactly as the working tree has them now: same file list, no +/// file written or recreated since. +fn recorded_files_unchanged(state: &State, meta: &Path, tracked: &[PathBuf]) -> Option { + let recorded_files = fs::read_to_string(meta.join("files")).ok()?; + if recorded_files != file_list(tracked) { + return None; + } + let snapshot = Snapshot::load(meta)?; + let deleted: HashSet = fs::read_to_string(meta.join("deleted")) + .ok()? + .lines() + .map(PathBuf::from) + .collect(); + for file in tracked { + let live = state.root.join(file); + if deleted.contains(file) { + if live.exists() { + return None; + } + } else if !snapshot.file_unchanged(file, &live) { + return None; + } + } + Some(snapshot) +} + fn file_list(files: &[PathBuf]) -> String { files .iter() @@ -83,17 +138,33 @@ fn file_list(files: &[PathBuf]) -> String { /// Whether the recorded expected state still describes this patch: same patch /// text and same tracked files as when it was recorded. pub(crate) fn expected_state_is_current(state: &State, patch: &str) -> bool { + state + .tracked_files(patch) + .is_ok_and(|tracked| expected_state_is_current_for(state, patch, &tracked)) +} + +/// [`expected_state_is_current`] with the patch's tracked files (as +/// [`State::tracked_files`] lists them) already at hand. +pub(crate) fn expected_state_is_current_for( + state: &State, + patch: &str, + tracked: &[PathBuf], +) -> bool { let meta = meta_dir(state, patch); - let (Ok(recorded_patch), Ok(recorded_files)) = ( - fs::read_to_string(meta.join("patch")), - fs::read_to_string(meta.join("files")), - ) else { + let Ok(recorded_files) = fs::read_to_string(meta.join("files")) else { return false; }; - patch_text(&state.patch_path(patch)).is_ok_and(|text| text == recorded_patch) - && state - .tracked_files(patch) - .is_ok_and(|files| file_list(&files) == recorded_files) + if file_list(tracked) != recorded_files { + return false; + } + let patch_path = state.patch_path(patch); + if Snapshot::load(&meta).is_some_and(|snapshot| snapshot.patch_unchanged(&patch_path)) { + return true; + } + let Ok(recorded_patch) = fs::read_to_string(meta.join("patch")) else { + return false; + }; + patch_text(&patch_path).is_ok_and(|text| text == recorded_patch) } /// Whether the working tree matches `patch`'s expected state for `files`. @@ -103,6 +174,7 @@ pub(crate) fn expected_state_matches( files: &[PathBuf], ) -> Result { let deleted = expected_deleted(state, patch)?; + let snapshot = Snapshot::load(&meta_dir(state, patch)); for file in files { let live = state.root.join(file); if deleted.contains(file) { @@ -111,6 +183,12 @@ pub(crate) fn expected_state_matches( } continue; } + if snapshot + .as_ref() + .is_some_and(|snapshot| snapshot.file_unchanged(file, &live)) + { + continue; + } let expected = expected_file(state, patch, file); if !expected.exists() || !files_match(&expected, &live)? { return Ok(false); @@ -118,3 +196,100 @@ pub(crate) fn expected_state_matches( } Ok(true) } + +/// The stat keys recorded in `.pc/.q//stat`. The file's own mtime is +/// the reference for racy entries: a file whose mtime is not older than it +/// may have been rewritten within the same timestamp tick, so its stat +/// proves nothing (git's "racily clean" rule). +struct Snapshot { + patch: Option, + files: HashMap, + stamp: SystemTime, +} + +impl Snapshot { + fn load(meta: &Path) -> Option { + let path = meta.join("stat"); + let text = fs::read_to_string(&path).ok()?; + let stamp = fs::metadata(&path).ok()?.modified().ok()?; + let mut lines = text.lines(); + let patch = lines.next()?; + let patch = (patch != "-").then(|| patch.to_string()); + let files = lines + .filter_map(|line| line.split_once('\t')) + .map(|(key, file)| (PathBuf::from(file), key.to_string())) + .collect(); + Some(Self { + patch, + files, + stamp, + }) + } + + fn patch_unchanged(&self, path: &Path) -> bool { + self.patch + .as_deref() + .is_some_and(|key| self.unchanged(key, path)) + } + + fn file_unchanged(&self, file: &Path, live: &Path) -> bool { + self.files + .get(file) + .is_some_and(|key| self.unchanged(key, live)) + } + + fn unchanged(&self, key: &str, path: &Path) -> bool { + let Ok(metadata) = fs::metadata(path) else { + return false; + }; + stat_key(&metadata).as_deref() == Some(key) + && metadata + .modified() + .is_ok_and(|modified| modified < self.stamp) + } +} + +/// Write the snapshot after the files it describes have been stat'ed, so its +/// own mtime is never older than theirs. +fn write_snapshot(meta: &Path, patch_path: &Path, files: &HashMap) -> Result<()> { + let mut out = fs::metadata(patch_path) + .ok() + .and_then(|metadata| stat_key(&metadata)) + .unwrap_or_else(|| "-".to_string()); + out.push('\n'); + let mut files: Vec<_> = files.iter().collect(); + files.sort(); + for (file, key) in files { + out.push_str(key); + out.push('\t'); + out.push_str(&file.to_string_lossy()); + out.push('\n'); + } + // A fresh file, so the stamp is its creation time even when the + // contents happen to be unchanged. + let path = meta.join("stat"); + let _ = fs::remove_file(&path); + fs::write(path, out)?; + Ok(()) +} + +/// What changes whenever a file is written, replaced or re-created. +#[cfg(unix)] +fn stat_key(metadata: &fs::Metadata) -> Option { + use std::os::unix::fs::MetadataExt; + Some(format!( + "{}:{}:{}:{}.{}:{}.{}", + metadata.dev(), + metadata.ino(), + metadata.size(), + metadata.mtime(), + metadata.mtime_nsec(), + metadata.ctime(), + metadata.ctime_nsec(), + )) +} + +#[cfg(not(unix))] +fn stat_key(_metadata: &fs::Metadata) -> Option { + None +} diff --git a/src/fsutil.rs b/src/fsutil.rs index 796f1f9..86f9c5b 100644 --- a/src/fsutil.rs +++ b/src/fsutil.rs @@ -52,6 +52,18 @@ fn hard_link_count(_path: &Path) -> io::Result { Ok(1) } +/// Whether the file `metadata` describes is also reachable by another name. +#[cfg(unix)] +pub(crate) fn has_other_hard_links(metadata: &fs::Metadata) -> bool { + use std::os::unix::fs::MetadataExt; + metadata.nlink() > 1 +} + +#[cfg(not(unix))] +pub(crate) fn has_other_hard_links(_metadata: &fs::Metadata) -> bool { + false +} + pub(crate) fn copy_preserving_times(src: &Path, dst: &Path) -> Result<()> { fs::copy(src, dst)?; if let Ok(metadata) = fs::metadata(src) { diff --git a/tests/stack.rs b/tests/stack.rs index 707eb7c..92e306b 100644 --- a/tests/stack.rs +++ b/tests/stack.rs @@ -921,3 +921,147 @@ fn diff_z_ignores_expected_state_recorded_for_other_patch_text() { .failure() .stderr(predicate::str::contains("does not remove cleanly")); } + +/// One patch changing `hello.txt` from "old" to "new", refreshed and applied. +fn applied_hello_patch() -> tempfile::TempDir { + let dir = tempdir().unwrap(); + fs::write(dir.path().join("hello.txt"), "old\n").unwrap(); + q(dir.path()) + .args(["new", "change.diff"]) + .assert() + .success(); + q(dir.path()).args(["add", "hello.txt"]).assert().success(); + fs::write(dir.path().join("hello.txt"), "new\n").unwrap(); + q(dir.path()).args(["refresh"]).assert().success(); + dir +} + +#[test] +fn pop_notices_same_size_edits_made_right_after_recording() { + // Right after refresh and after push: an edit within the same timestamp + // tick that keeps the size must not pass for the recorded state. + let dir = applied_hello_patch(); + fs::write(dir.path().join("hello.txt"), "NEW\n").unwrap(); + q(dir.path()) + .args(["pop"]) + .assert() + .failure() + .stderr(predicate::str::contains("does not remove cleanly")); + + fs::write(dir.path().join("hello.txt"), "new\n").unwrap(); + q(dir.path()).args(["pop"]).assert().success(); + q(dir.path()).args(["push"]).assert().success(); + fs::write(dir.path().join("hello.txt"), "NEW\n").unwrap(); + q(dir.path()) + .args(["pop"]) + .assert() + .failure() + .stderr(predicate::str::contains("does not remove cleanly")); +} + +#[test] +fn pop_discards_backups() { + let dir = tempdir().unwrap(); + fs::write(dir.path().join("a"), "a\n").unwrap(); + fs::write(dir.path().join("b"), "b\n").unwrap(); + q(dir.path()).args(["new", "p.diff"]).assert().success(); + q(dir.path()).args(["add", "a", "b"]).assert().success(); + fs::write(dir.path().join("a"), "A\n").unwrap(); + fs::write(dir.path().join("b"), "B\n").unwrap(); + q(dir.path()) + .args(["refresh", "--no-timestamps"]) + .assert() + .success(); + q(dir.path()).args(["pop"]).assert().success(); + assert!(!dir.path().join(".pc/p.diff").exists()); + assert!(!dir.path().join(".pc/.q/p.diff").exists()); + + // Drop b from the patch, and let b change upstream meanwhile. + let patch = fs::read_to_string(dir.path().join("patches/p.diff")).unwrap(); + let b_section = patch.match_indices("Index: ").nth(1).unwrap().0; + let a_only = &patch[..b_section]; + assert!(a_only.contains("+A") && !a_only.contains("+B")); + fs::write(dir.path().join("patches/p.diff"), a_only).unwrap(); + fs::write(dir.path().join("b"), "upstream\n").unwrap(); + + q(dir.path()).args(["push"]).assert().success(); + q(dir.path()) + .args(["files"]) + .assert() + .success() + .stdout("a\n"); + q(dir.path()).args(["pop"]).assert().success(); + assert_eq!(fs::read_to_string(dir.path().join("a")).unwrap(), "a\n"); + assert_eq!( + fs::read_to_string(dir.path().join("b")).unwrap(), + "upstream\n" + ); +} + +#[test] +fn pop_gives_restored_files_a_fresh_mtime() { + let dir = applied_hello_patch(); + let hello = dir.path().join("hello.txt"); + let old = filetime::FileTime::from_unix_time(1_000_000_000, 0); + // Age the backup, as a clone or a long-lived backup would be. + filetime::set_file_mtime(dir.path().join(".pc/change.diff/hello.txt"), old).unwrap(); + q(dir.path()).args(["pop"]).assert().success(); + assert_eq!(fs::read_to_string(&hello).unwrap(), "old\n"); + let mtime = filetime::FileTime::from_last_modification_time(&fs::metadata(&hello).unwrap()); + assert!(mtime > old, "restored file kept the backup's old mtime"); +} + +#[test] +fn push_refresh_rewrites_patch_and_still_pops_cleanly() { + let dir = tempdir().unwrap(); + fs::write(dir.path().join("hello.txt"), "old\n").unwrap(); + fs::create_dir(dir.path().join("patches")).unwrap(); + // No Index: line, so refreshing rewrites the patch text. + fs::write( + dir.path().join("patches/change.diff"), + "--- a/hello.txt\n+++ b/hello.txt\n@@ -1 +1 @@\n-old\n+new\n", + ) + .unwrap(); + fs::write(dir.path().join("patches/series"), "change.diff\n").unwrap(); + + q(dir.path()) + .args(["push", "--refresh"]) + .assert() + .success() + .stdout(predicate::str::contains("Refreshed patch")); + let patch = fs::read_to_string(dir.path().join("patches/change.diff")).unwrap(); + assert!(patch.starts_with("Index: ")); + let recorded = fs::read_to_string(dir.path().join(".pc/.q/change.diff/patch")).unwrap(); + assert_eq!(recorded, patch); + + fs::write(dir.path().join("hello.txt"), "NEW\n").unwrap(); + q(dir.path()) + .args(["pop"]) + .assert() + .failure() + .stderr(predicate::str::contains("does not remove cleanly")); + fs::write(dir.path().join("hello.txt"), "new\n").unwrap(); + q(dir.path()).args(["pop"]).assert().success(); + assert_eq!( + fs::read_to_string(dir.path().join("hello.txt")).unwrap(), + "old\n" + ); +} + +#[test] +fn pop_removes_backup_directories_of_nested_patch_names() { + let dir = tempdir().unwrap(); + fs::write(dir.path().join("a"), "a\n").unwrap(); + q(dir.path()) + .args(["new", "sub/dir/s.diff"]) + .assert() + .success(); + q(dir.path()).args(["add", "a"]).assert().success(); + fs::write(dir.path().join("a"), "A\n").unwrap(); + q(dir.path()).args(["refresh"]).assert().success(); + assert!(dir.path().join(".pc/.q/sub/dir/s.diff").exists()); + q(dir.path()).args(["pop"]).assert().success(); + assert!(!dir.path().join(".pc/sub").exists()); + assert!(!dir.path().join(".pc/.q/sub").exists()); + assert!(dir.path().join(".pc/.version").exists()); +} From 04d68deae3518fbec0e33195ef154784ce2c2d19 Mon Sep 17 00:00:00 2001 From: jj Date: Tue, 17 Nov 2026 13:26:04 +0100 Subject: [PATCH 3/5] readme: refresh benchmark numbers re-run with tools/benchmark.sh on the same 9950X --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 3285323..0d4581a 100644 --- a/README.md +++ b/README.md @@ -36,12 +36,12 @@ Ryzen 9 9950X; `tools/benchmark.sh` reproduces it. | Command | q | quilt | Speedup | | --- | ---: | ---: | ---: | -| `push -a` | 21.0 ms | 501.8 ms | 24x | -| `pop -a` | 22.9 ms | 1.762 s | 77x | -| `refresh` | 2.6 ms | 43.5 ms | 17x | -| `push -a --refresh` | 76.3 ms | 3.815 s | 50x | -| `pop -a --refresh` | 61.7 ms | 5.239 s | 85x | -| `fold` | 1.7 ms | 8.1 ms | 5x | +| `push -a` | 20.8 ms | 492.6 ms | 24x | +| `pop -a` | 20.7 ms | 1.766 s | 85x | +| `refresh` | 2.4 ms | 43.5 ms | 18x | +| `push -a --refresh` | 76.4 ms | 3.869 s | 51x | +| `pop -a --refresh` | 60.0 ms | 5.086 s | 85x | +| `fold` | 1.9 ms | 8.3 ms | 4x | How much faster q is on your patches depends on how many patches and files you have and how large they are. From b1e462a50e02e6457f12e9193998563fa33920b2 Mon Sep 17 00:00:00 2001 From: jj Date: Tue, 17 Nov 2026 13:35:38 +0100 Subject: [PATCH 4/5] tests: keep q-only pop checks out of the quilt compat run the compat job runs the stack tests against gnu quilt, which keeps no .pc/.q metadata and leaves empty .pc/ behind for nested patch names. drop the .pc/.q asserts, and skip the nested backup directory test there since removing those directories is q's own tidying --- tests/stack.rs | 4 +--- tools/run-compat-tests.sh | 1 + 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/tests/stack.rs b/tests/stack.rs index 92e306b..970053a 100644 --- a/tests/stack.rs +++ b/tests/stack.rs @@ -1031,8 +1031,6 @@ fn push_refresh_rewrites_patch_and_still_pops_cleanly() { .stdout(predicate::str::contains("Refreshed patch")); let patch = fs::read_to_string(dir.path().join("patches/change.diff")).unwrap(); assert!(patch.starts_with("Index: ")); - let recorded = fs::read_to_string(dir.path().join(".pc/.q/change.diff/patch")).unwrap(); - assert_eq!(recorded, patch); fs::write(dir.path().join("hello.txt"), "NEW\n").unwrap(); q(dir.path()) @@ -1059,7 +1057,7 @@ fn pop_removes_backup_directories_of_nested_patch_names() { q(dir.path()).args(["add", "a"]).assert().success(); fs::write(dir.path().join("a"), "A\n").unwrap(); q(dir.path()).args(["refresh"]).assert().success(); - assert!(dir.path().join(".pc/.q/sub/dir/s.diff").exists()); + assert!(dir.path().join(".pc/sub/dir/s.diff").exists()); q(dir.path()).args(["pop"]).assert().success(); assert!(!dir.path().join(".pc/sub").exists()); assert!(!dir.path().join(".pc/.q/sub").exists()); diff --git a/tools/run-compat-tests.sh b/tools/run-compat-tests.sh index af78d39..7250d9c 100755 --- a/tools/run-compat-tests.sh +++ b/tools/run-compat-tests.sh @@ -51,5 +51,6 @@ run_test stack \ --skip patch_basename_match_must_be_unambiguous \ --skip patch_environment_options_are_honored \ --skip pop_accepts_unique_patch_basename \ + --skip pop_removes_backup_directories_of_nested_patch_names \ --skip push_and_pop_empty_patch_file \ --skip push_applies_missing_patch_file_as_empty_patch From b6cfb94698b07c1483af11607e7ed13bd0f13e69 Mon Sep 17 00:00:00 2001 From: jj Date: Tue, 17 Nov 2026 13:39:35 +0100 Subject: [PATCH 5/5] .github/clone-upstream-quilt: clone over git:// savannah's https frontend keeps returning 502 while its git:// endpoint still works --- .github/actions/clone-upstream-quilt/action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/actions/clone-upstream-quilt/action.yml b/.github/actions/clone-upstream-quilt/action.yml index 5edbe3c..bea0ec3 100644 --- a/.github/actions/clone-upstream-quilt/action.yml +++ b/.github/actions/clone-upstream-quilt/action.yml @@ -18,4 +18,4 @@ runs: dest="${dest/#\~/$HOME}" rm -rf "$dest" mkdir -p "$(dirname "$dest")" - git clone --depth 1 https://git.savannah.nongnu.org/git/quilt.git "$dest" + git clone --depth 1 git://git.savannah.nongnu.org/quilt.git "$dest"