Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/actions/clone-upstream-quilt/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
151 changes: 116 additions & 35 deletions src/apply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -434,64 +434,114 @@ 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/<patch>` 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(())
}

/// 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(
/// Restore `files` from `patch`'s backups, keeping the backups.
pub(crate) fn restore_patch_files(
state: &State,
entry: &PatchEntry,
use_expected_state: bool,
tracked: &[PathBuf],
) -> Result<bool> {
let patch = &entry.name;
if expected_state_is_current(state, patch) {
if use_expected_state {
return expected_state_matches(state, patch, tracked);
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());
}
// 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 _ = 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.
pub(crate) fn apply_to_backups(
state: &State,
entry: &PatchEntry,
tracked: &[PathBuf],
) -> Result<Option<TempDir>> {
let patch = &entry.name;
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),
Expand All @@ -513,9 +563,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<bool> {
let patch = &entry.name;
if expected_state_is_current_for(state, patch, tracked) {
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<PathBuf> = tracked.iter().cloned().collect();
files.extend(filenames_in_text_order(
Expand Down
31 changes: 18 additions & 13 deletions src/commands/diff.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -46,13 +45,14 @@ pub(crate) fn cmd_diff(args: Vec<OsString>) -> 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() {
Expand All @@ -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(());
Expand All @@ -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 {
Expand Down
68 changes: 67 additions & 1 deletion src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> {
state.require_series()?;
Expand Down Expand Up @@ -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<HashMap<PathBuf, PathBuf>> {
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<PatchedTree> {
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(
Expand Down
Loading
Loading