From 6f2125aac7aa6acea68138d987e27400f02ed61e Mon Sep 17 00:00:00 2001 From: Pekka Enberg Date: Tue, 3 Nov 2026 10:57:49 +0200 Subject: [PATCH 1/8] Move fsdiff's git into the fsfork library So that fsfork can compare a fork with its base too, for listing forks, by the same rules fsdiff does. --- cmd/fsdiff/fsdiff.rs | 4 +--- fsfork/fsfork.rs | 1 + {cmd/fsdiff => fsfork}/git.rs | 20 ++++++++++---------- 3 files changed, 12 insertions(+), 13 deletions(-) rename {cmd/fsdiff => fsfork}/git.rs (89%) diff --git a/cmd/fsdiff/fsdiff.rs b/cmd/fsdiff/fsdiff.rs index e8eb881..a6333d4 100644 --- a/cmd/fsdiff/fsdiff.rs +++ b/cmd/fsdiff/fsdiff.rs @@ -1,8 +1,6 @@ //! `fsdiff` shows what changed in a fork since it was made, as a patch: the //! difference between the fork and its base, which `fsfork` made next to it. -mod git; - use std::{ io, path::{Path, PathBuf}, @@ -10,7 +8,7 @@ use std::{ }; use argh::FromArgs; -use fsfork::{at, message}; +use fsfork::{at, git, message}; /// How to give the arguments, as in the man page, a line for each form. const USAGE: &str = "fsdiff [--stat] [fork]\nfsdiff [--stat] old new"; diff --git a/fsfork/fsfork.rs b/fsfork/fsfork.rs index 748d01d..3f23034 100644 --- a/fsfork/fsfork.rs +++ b/fsfork/fsfork.rs @@ -4,6 +4,7 @@ #[cfg(target_os = "macos")] mod darwin; +pub mod git; mod ignored; #[cfg(target_os = "linux")] mod linux; diff --git a/cmd/fsdiff/git.rs b/fsfork/git.rs similarity index 89% rename from cmd/fsdiff/git.rs rename to fsfork/git.rs index 4cc73d0..50f3d6e 100644 --- a/cmd/fsdiff/git.rs +++ b/fsfork/git.rs @@ -1,11 +1,11 @@ -//! Git, as `fsdiff` uses it: to record two directories as trees, and to show -//! the difference between them. +//! Git, as `fsdiff` and `fsfork -l` use it: to record two directories as +//! trees, and to show the difference between them. //! //! Git never uses a repository in either directory, whose configuration could //! make it run any command, as the command that changed the fork could have -//! changed it. The trees are recorded in a repository of `fsdiff`'s own, made -//! in the temporary directory and removed after, by git with no configuration -//! but its defaults. +//! changed it. The trees are recorded in a repository of the command's own, +//! made in the temporary directory and removed after, by git with no +//! configuration but its defaults. use std::{ env, fs, io, @@ -14,9 +14,9 @@ use std::{ process::{self, Command, ExitStatus}, }; -use fsfork::message::shown; +use crate::message::{self, shown}; -/// The signals from the terminal, which `fsdiff` ignores and git does not. +/// The signals from the terminal, which the caller ignores and git does not. pub const SIGNALS: [i32; 3] = [libc::SIGINT, libc::SIGQUIT, libc::SIGHUP]; /// The variables that would point git at another repository than the one it @@ -30,7 +30,7 @@ const REPOSITORY: &[&str] = &[ "GIT_COMMON_DIR", ]; -/// A repository of `fsdiff`'s own, removed when dropped. +/// A repository of the command's own, removed when dropped. pub struct Repo { dir: PathBuf, } @@ -41,7 +41,7 @@ impl Repo { let tmp = env::temp_dir(); let mut n = 0; let dir = loop { - let dir = tmp.join(format!("fsdiff.{}.{n}", process::id())); + let dir = tmp.join(format!("{}.{}.{n}", message::prog(), process::id())); match fs::create_dir(&dir) { Ok(()) => break dir, Err(e) if e.kind() == io::ErrorKind::AlreadyExists => n += 1, @@ -160,7 +160,7 @@ fn bare() -> Command { git } -/// Runs `command`, with the terminal's signals, which `fsdiff` ignores, as +/// Runs `command`, with the terminal's signals, which the caller ignores, as /// they are by default, and waits for it to exit. fn status(command: &mut Command) -> io::Result { unsafe { From c4deeb2d0a2f00401666df46b88ac1960e3db790 Mon Sep 17 00:00:00 2001 From: Pekka Enberg Date: Tue, 3 Nov 2026 11:01:40 +0200 Subject: [PATCH 2/8] fsfork: List a directory's forks, and what is in each, with -l fsfork -l lists the forks next to the directory, each with how long it has been left alone and whether it is unchanged, applied, or has changes the directory does not, so that those done with can be told from those not, and removed. Bases left over from forks removed without them are listed too. --- README.md | 11 ++- cmd/fsfork/fsfork.1 | 56 +++++++++++- cmd/fsfork/fsfork.rs | 44 +++++++++- cmd/fsfork/list.rs | 170 +++++++++++++++++++++++++++++++++++++ cmd/fsfork/tests/fsfork.rs | 91 +++++++++++++++++++- fsfork/fsfork.rs | 66 +++++++++++++- fsfork/git.rs | 26 +++++- 7 files changed, 452 insertions(+), 12 deletions(-) create mode 100644 cmd/fsfork/list.rs diff --git a/README.md b/README.md index 99aabb6..73ce08b 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,16 @@ rm -rf ../turso.1 ../.turso.1.base Meanwhile, you can keep working in `~/src/turso`, and run more forks side by side: `turso.2`, `turso.3`, and so on, or named ones, `turso.swebench` with -`-n swebench`. `ls -d ../turso.*` lists them. +`-n swebench`. `fsfork -l` lists them, with what is in each, so that you can +tell which to remove: + +``` +$ fsfork -l +../turso.1 4 days ago unchanged +../turso.3 1 day ago 15 files changed, 6 applied +../.turso.2.base 2 hours ago base left over, with no fork +../turso.swebench 9 minutes ago applied +``` Each command has a man page: [`fsfork.1`](cmd/fsfork/fsfork.1), [`confine.1`](cmd/confine/confine.1), and [`fsdiff.1`](cmd/fsdiff/fsdiff.1) diff --git a/cmd/fsfork/fsfork.1 b/cmd/fsfork/fsfork.1 index 732f7c4..a7577a1 100644 --- a/cmd/fsfork/fsfork.1 +++ b/cmd/fsfork/fsfork.1 @@ -9,6 +9,9 @@ fsfork \- fork a directory: make a copy-on-write clone of it .IR name ] .RI [ dir .RI [ fork ]] +.br +.B fsfork \-l +.RI [ dir ] .SH DESCRIPTION .B fsfork makes a copy-on-write clone of @@ -86,12 +89,49 @@ changes in the directory meanwhile. .PP .B fsfork keeps no other record of its forks: a fork is a directory, and -.BR ls (1) -lists them, .BR rm (1) -removes them. +removes it. Remove a fork's base with it, or its number stays taken. .PP +With +.BR \-l , +it forks nothing, and lists the forks of +.IR dir , +or of the working directory, that are next to it: each +.I . +with a base, and each base left over from a fork removed without it. +A line for each gives its path, as it would be typed from the working +directory; how long it has been left alone, since a file in it last changed, +or since it was made, if none has; and what is in it: +.TP +.B unchanged +Nothing changed in it, as +.BR fsdiff (1) +would say. +.TP +.B applied +Something changed in it, and +.I dir +has every file that changed as it is in the fork: the changes were applied. +.TP +.IB n " files changed" "\fR, \fPm applied" +.I n +files changed in it, of which +.IR dir , +if +.I m +is given, has +.I m +as they are in the fork. +.TP +.B base left over, with no fork +The fork is gone, and its base is not. +.PP +Those left alone longest come first. +Forks made elsewhere, with +.I fork +given, are not listed. +.PP .B fsfork goes by .I .gitignore @@ -121,6 +161,11 @@ It cannot be given with .IR fork , which says where the fork goes. .TP +.BR \-l ", " \-\-list +List the forks of the directory, rather than fork it. +It cannot be given with the other options or with +.IR fork . +.TP .B \-\-no\-ignore Fork what is ignored too, so that builds in the fork start warm. Making it takes longer if what is ignored holds many files. @@ -132,6 +177,9 @@ Print the fork's path, even on a terminal, rather than start a shell there. made neither the fork nor the base. On a terminal, the status of the shell, or 1, having made neither, if the shell cannot be run. +With +.BR \-l , +0 if every fork was listed with what is in it, and 1 otherwise. .SH EXAMPLES Fork the working directory, and work in the fork in a shell of its own: .PP @@ -172,7 +220,7 @@ and remove one: .PP .RS .nf -.B ls \-d turso.* +.B fsfork \-l turso .B rm \-rf turso.1 .turso.1.base .fi .RE diff --git a/cmd/fsfork/fsfork.rs b/cmd/fsfork/fsfork.rs index 63bfe67..32ce082 100644 --- a/cmd/fsfork/fsfork.rs +++ b/cmd/fsfork/fsfork.rs @@ -1,6 +1,9 @@ //! `fsfork` forks a directory: it makes a copy-on-write clone of it, the //! fork, and another, the base, which keeps what the directory was when it -//! was forked, for `fsdiff` to compare the fork with. +//! was forked, for `fsdiff` to compare the fork with. With `-l`, it lists +//! the forks of a directory instead. + +mod list; use std::{ env, @@ -14,13 +17,18 @@ use std::{ use argh::FromArgs; use fsfork::{Contents, message}; -/// How to give the arguments, as in the man page. -const USAGE: &str = "fsfork [--no-ignore] [--print] [-n name] [dir [fork]]"; +/// How to give the arguments, as in the man page, a line for each form. +const USAGE: &str = "fsfork [--no-ignore] [--print] [-n name] [dir [fork]]\nfsfork -l [dir]"; /// Fork a directory: make a copy-on-write clone of it, and start a shell there /// or, if not on a terminal, print where it is. #[derive(FromArgs)] struct Args { + /// list the forks of the directory, with how long each has been left + /// alone and what changed in it, rather than fork it + #[argh(switch, short = 'l')] + list: bool, + /// print where the fork is, rather than start a shell there #[argh(switch)] print: bool, @@ -46,6 +54,9 @@ fn main() -> ExitCode { Ok(args) => args, Err(code) => return code, }; + if args.list { + return list(args); + } // A shell needs both: with stdout captured, as in `cd $(fsfork)`, the // path is wanted, and with stdin not a terminal, a shell would run what // it reads from there as commands. @@ -72,6 +83,33 @@ fn main() -> ExitCode { } } +/// Lists the forks of the directory `args` give. +fn list(args: Args) -> ExitCode { + let conflict = if args.print { + Some("-l cannot be given with --print") + } else if args.no_ignore { + Some("-l cannot be given with --no-ignore") + } else if args.name.is_some() { + Some("-l cannot be given with -n") + } else if args.paths.len() > 1 { + Some("too many arguments") + } else { + None + }; + if let Some(problem) = conflict { + return message::usage_error(problem, USAGE, 1); + } + let dir = args.paths.first().map_or(Path::new("."), PathBuf::as_path); + match list::list(dir) { + Ok(true) => ExitCode::SUCCESS, + Ok(false) => ExitCode::FAILURE, + Err(e) => { + message::say(message::describe(&e)); + ExitCode::FAILURE + } + } +} + /// Prints where `fork` is. fn print(fork: PathBuf) -> io::Result<()> { let mut line = fork.into_os_string().into_vec(); diff --git a/cmd/fsfork/list.rs b/cmd/fsfork/list.rs new file mode 100644 index 0000000..2d73e12 --- /dev/null +++ b/cmd/fsfork/list.rs @@ -0,0 +1,170 @@ +//! `fsfork -l`: lists the forks of a directory, with how long each has been +//! left alone and what changed in it, so that those done with can be told +//! from those not. + +use std::{ + fs, + io::{self, Write}, + os::unix::fs::PermissionsExt, + path::{Path, PathBuf}, + time::{Duration, SystemTime}, +}; + +use fsfork::{Found, git, message}; + +/// Lists the forks of `dir`, those left alone longest first, and returns +/// whether all could be looked into. +pub fn list(dir: &Path) -> io::Result { + let found = fsfork::forks(dir)?; + if found.is_empty() { + return Ok(true); + } + let dir = dir.canonicalize()?; + // The terminal's signals reach git too, which exits; `fsfork` outlives + // it to remove its repository. + for signal in git::SIGNALS { + unsafe { libc::signal(signal, libc::SIG_IGN) }; + } + let repo = git::Repo::new()?; + let now = SystemTime::now(); + let mut all = true; + let mut rows = Vec::new(); + for fork in &found { + let (state, touched) = match state(&repo, &dir, fork) { + Ok(state) => state, + Err(e) => { + message::say(message::describe(&e)); + all = false; + ("cannot be compared with its base".to_string(), fork.made) + } + }; + let path = if fork.left_over { + &fork.base + } else { + &fork.fork + }; + rows.push(( + touched, + [ + message::shown(path).display().to_string(), + age(now.duration_since(touched).unwrap_or_default()), + state, + ], + )); + } + // Those left alone longest, the likeliest to be done with, first. + rows.sort_by_key(|(touched, _)| *touched); + let rows: Vec<_> = rows.into_iter().map(|(_, row)| row).collect(); + let path_width = rows.iter().map(|row| row[0].len()).max().unwrap_or(0); + let age_width = rows.iter().map(|row| row[1].len()).max().unwrap_or(0); + let mut out = io::stdout().lock(); + for [path, age, state] in rows { + writeln!(out, "{path:path_width$} {age:age_width$} {state}")?; + } + out.flush()?; + Ok(all) +} + +/// What is in `fork`, of `dir`: whether anything changed in it since it was +/// made, and if so, whether `dir` has those changes now; and when it was last +/// changed, or made, if it was not. +fn state(repo: &git::Repo, dir: &Path, fork: &Found) -> io::Result<(String, SystemTime)> { + if fork.left_over { + return Ok(("base left over, with no fork".to_string(), fork.made)); + } + let (before, after) = repo.record(&fork.base, &fork.fork)?; + let changed = repo.changed(&before, &after)?; + if changed.is_empty() { + return Ok(("unchanged".to_string(), fork.made)); + } + let touched = changed + .iter() + .filter_map(|path| modified(&fork.fork, path)) + .fold(fork.made, SystemTime::max); + let applied = changed + .iter() + .filter(|path| same(&fork.fork.join(path), &dir.join(path))) + .count(); + let files = match changed.len() { + 1 => "1 file changed".to_string(), + n => format!("{n} files changed"), + }; + let state = match applied { + 0 => files, + n if n == changed.len() => "applied".to_string(), + n => format!("{files}, {n} applied"), + }; + Ok((state, touched)) +} + +/// When `path` in `fork` was last changed, or if it is gone, the directory +/// it was in, which changed when it went. +fn modified(fork: &Path, path: &Path) -> Option { + path.ancestors() + .map(|path| fork.join(path)) + .find_map(|path| fs::symlink_metadata(path).ok()) + .and_then(|meta| meta.modified().ok()) +} + +/// Whether `a` and `b` are the same as git sees them: both missing, links to +/// the same place, or files with the same contents, both executable or +/// neither. +fn same(a: &Path, b: &Path) -> bool { + let (a_meta, b_meta) = (fs::symlink_metadata(a), fs::symlink_metadata(b)); + let (a_meta, b_meta) = match (a_meta, b_meta) { + (Err(a), Err(b)) => { + return a.kind() == io::ErrorKind::NotFound && b.kind() == io::ErrorKind::NotFound; + } + (Ok(a), Ok(b)) => (a, b), + _ => return false, + }; + let (a_type, b_type) = (a_meta.file_type(), b_meta.file_type()); + if a_type.is_symlink() && b_type.is_symlink() { + return target(a).is_some_and(|a| target(b).as_ref() == Some(&a)); + } + if !(a_type.is_file() && b_type.is_file()) { + return false; + } + let executable = |mode: u32| mode & 0o111 != 0; + executable(a_meta.permissions().mode()) == executable(b_meta.permissions().mode()) + && a_meta.len() == b_meta.len() + && fs::read(a).is_ok_and(|a| fs::read(b).is_ok_and(|b| a == b)) +} + +fn target(link: &Path) -> Option { + fs::read_link(link).ok() +} + +/// How long ago something was, `ago` since, roughly, as in "3 days ago". +fn age(ago: Duration) -> String { + let secs = ago.as_secs(); + let (n, unit) = match secs { + 0..60 => return "just now".to_string(), + 60..3600 => (secs / 60, "minute"), + 3600..86400 => (secs / 3600, "hour"), + 86400..1209600 => (secs / 86400, "day"), + 1209600..5184000 => (secs / 604800, "week"), + 5184000..63072000 => (secs / 2592000, "month"), + _ => (secs / 31536000, "year"), + }; + let s = if n == 1 { "" } else { "s" }; + format!("{n} {unit}{s} ago") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn says_how_long_ago_roughly() { + let ago = |secs| age(Duration::from_secs(secs)); + assert_eq!(ago(5), "just now"); + assert_eq!(ago(60), "1 minute ago"); + assert_eq!(ago(3599), "59 minutes ago"); + assert_eq!(ago(7200), "2 hours ago"); + assert_eq!(ago(86400 * 3), "3 days ago"); + assert_eq!(ago(86400 * 14), "2 weeks ago"); + assert_eq!(ago(86400 * 90), "3 months ago"); + assert_eq!(ago(86400 * 800), "2 years ago"); + } +} diff --git a/cmd/fsfork/tests/fsfork.rs b/cmd/fsfork/tests/fsfork.rs index 4f7f45c..9c4a6a8 100644 --- a/cmd/fsfork/tests/fsfork.rs +++ b/cmd/fsfork/tests/fsfork.rs @@ -508,6 +508,94 @@ fn fails_for_what_is_not_a_directory() { assert_fails(&fsfork(&world.dir, &["a", "b", "c"]), "too many arguments"); } +#[test] +fn lists_the_forks_with_what_changed_in_each() { + let world = World::new(); + let dir = world.project(); + write(&dir, "b", "x\n"); + let fork = |args: &[&str]| { + let out = fsfork(&dir, args); + assert!(out.status.success(), "{}", stderr(&out)); + PathBuf::from(stdout(&out).trim_end()) + }; + let unchanged = fork(&[]); + let changed = fork(&[]); + write(&changed, "a", "two\n"); + write(&changed, "c", "new\n"); + fs::remove_file(changed.join("b")).unwrap(); + let applied = fork(&["-n", "applied"]); + write(&applied, "a", "three\n"); + let partly = fork(&[]); + write(&partly, "a", "three\n"); + write(&partly, "c", "other\n"); + let removed = fork(&[]); + fs::remove_dir_all(&removed).unwrap(); + write(&dir, "a", "three\n"); + // Named like a fork, but with no base, it is not one. + fs::create_dir(world.path("project.old")).unwrap(); + assert!(unchanged.ends_with("project.1") && removed.ends_with("project.4")); + + for (cwd, args, prefix) in [ + (&dir, vec!["-l"], "../"), + (&world.dir, vec!["-l", "project"], ""), + ] { + let out = fsfork(cwd, &args); + assert!(out.status.success(), "{}", stderr(&out)); + assert_eq!(stderr(&out), ""); + let listed = stdout(&out); + let mut lines: Vec<(&str, &str)> = listed + .lines() + .map(|line| { + let (path, rest) = line.split_once(" ").unwrap(); + let state = rest.trim_start().split_once(" ").unwrap().1.trim_start(); + (path, state) + }) + .collect(); + lines.sort(); + let at = |name: &str| format!("{prefix}{name}"); + let expected = [ + (at(".project.4.base"), "base left over, with no fork"), + (at("project.1"), "unchanged"), + (at("project.2"), "3 files changed"), + (at("project.3"), "2 files changed, 1 applied"), + (at("project.applied"), "applied"), + ]; + let expected: Vec<(&str, &str)> = expected.iter().map(|(p, s)| (p.as_str(), *s)).collect(); + assert_eq!(lines, expected, "{listed}"); + assert!(listed.contains("just now"), "{listed}"); + } +} + +#[test] +fn lists_nothing_if_there_are_no_forks() { + let world = World::new(); + let dir = world.project(); + let out = fsfork(&dir, &["-l"]); + assert!(out.status.success(), "{}", stderr(&out)); + assert_eq!(stdout(&out), ""); + assert_fails( + &fsfork(&world.dir, &["-l", "missing"]), + "missing: no such file", + ); +} + +#[test] +fn lists_but_forks_nothing_and_takes_no_options_for_forking() { + let world = World::new(); + let dir = world.project(); + for args in [ + &["-l", "--print"][..], + &["-l", "--no-ignore"], + &["-l", "-n", "x"], + &["-l", ".", "../x"], + ] { + let out = fsfork(&dir, args); + assert_fails(&out, "usage: fsfork"); + } + assert!(!world.path("project.1").exists()); + assert!(!world.path("x").exists()); +} + /// A test's world: a directory to make projects and forks in. struct World { dir: PathBuf, @@ -696,7 +784,8 @@ fn assert_fails(out: &Output, message: &str) { fn says_what_is_wrong_with_the_arguments_and_how_to_give_them() { let world = World::new(); let dir = world.project(); - let usage = "usage: fsfork [--no-ignore] [--print] [-n name] [dir [fork]]\n"; + let usage = "usage: fsfork [--no-ignore] [--print] [-n name] [dir [fork]]\n \ + fsfork -l [dir]\n"; let out = fsfork(&dir, &["--bogus"]); assert_eq!(out.status.code(), Some(1)); assert_eq!( diff --git a/fsfork/fsfork.rs b/fsfork/fsfork.rs index 3f23034..af4cd37 100644 --- a/fsfork/fsfork.rs +++ b/fsfork/fsfork.rs @@ -21,8 +21,9 @@ compile_error!("fsfork runs only on macOS and Linux for now"); use std::{ ffi::{OsStr, OsString}, fs, io, - os::unix::ffi::OsStrExt, + os::unix::{ffi::OsStrExt, fs::MetadataExt}, path::{self, Path, PathBuf}, + time::{Duration, SystemTime}, }; use ignored::Ignored; @@ -91,6 +92,69 @@ pub fn remove(fork: &Path) -> io::Result<()> { removed.and(base_removed) } +/// A fork of a directory, next to it, or what is left of one. +pub struct Found { + /// Where the fork is, or was. + pub fork: PathBuf, + /// Where its base is. + pub base: PathBuf, + /// Whether only the base is left, the fork having been removed without + /// it. + pub left_over: bool, + /// When it was made, roughly: when its base last changed. + pub made: SystemTime, +} + +/// The forks of `dir` next to it, `.` with a base, and the bases +/// left over from forks removed without them, oldest first. Forks made +/// elsewhere, with a path given, are not found. +/// +/// When each was made is when its base last changed, which it never does once +/// made, but for attributes the system may add to it later. +pub fn forks(dir: &Path) -> io::Result> { + let dir = directory(dir)?; + let (Some(parent), Some(name)) = (dir.parent(), dir.file_name()) else { + return Ok(Vec::new()); + }; + let mut prefix = name.as_bytes().to_vec(); + prefix.push(b'.'); + let mut found = Vec::new(); + for entry in fs::read_dir(parent).map_err(|e| at(parent, e))? { + let entry = entry.map_err(|e| at(parent, e))?; + let entry_name = entry.file_name(); + let entry_name = entry_name.as_bytes(); + // A fork is found by its base, `...base`, which every + // fork has, and a directory merely named like one does not. + let Some(fork_name) = entry_name + .strip_prefix(b".") + .and_then(|name| name.strip_suffix(b".base")) + .filter(|name| name.len() > prefix.len() && name.starts_with(&prefix)) + else { + continue; + }; + let base = entry.path(); + let meta = base.symlink_metadata().map_err(|e| at(&base, e))?; + if !meta.is_dir() { + continue; + } + let fork = parent.join(OsStr::from_bytes(fork_name)); + let fork_is_dir = fork.symlink_metadata().is_ok_and(|m| m.is_dir()); + let made = SystemTime::UNIX_EPOCH + + Duration::new( + u64::try_from(meta.ctime()).unwrap_or(0), + u32::try_from(meta.ctime_nsec()).unwrap_or(0), + ); + found.push(Found { + left_over: !fork_is_dir, + fork, + base, + made, + }); + } + found.sort_by(|a, b| a.made.cmp(&b.made).then_with(|| a.fork.cmp(&b.fork))); + Ok(found) +} + /// The base of `fork`: `..base` next to it. pub fn base_of(fork: &Path) -> PathBuf { let mut name = OsString::from("."); diff --git a/fsfork/git.rs b/fsfork/git.rs index 50f3d6e..bd016cb 100644 --- a/fsfork/git.rs +++ b/fsfork/git.rs @@ -8,8 +8,10 @@ //! configuration but its defaults. use std::{ - env, fs, io, - os::unix::process::CommandExt, + env, + ffi::OsStr, + fs, io, + os::unix::{ffi::OsStrExt, process::CommandExt}, path::{Path, PathBuf}, process::{self, Command, ExitStatus}, }; @@ -100,6 +102,26 @@ impl Repo { } } + /// The paths that differ between the trees `before` and `after`, as in + /// `diff` but by git with no configuration but its defaults, a rename + /// being both of its paths. + pub fn changed(&self, before: &str, after: &str) -> io::Result> { + let listed = self + .git() + .args(["diff", "--name-only", "--no-renames", "-z", before, after]) + .stderr(process::Stdio::inherit()) + .output()?; + if !listed.status.success() { + return Err(io::Error::other("git could not compare the trees")); + } + Ok(listed + .stdout + .split(|&b| b == 0) + .filter(|path| !path.is_empty()) + .map(|path| PathBuf::from(OsStr::from_bytes(path))) + .collect()) + } + /// Records the files in `tree` that git does not ignore as a tree, /// keeping the index in `index`, and returns the tree's ID. fn snapshot(&self, tree: &Path, index: &Path) -> io::Result { From bbb0a310338db4844ffe449fd15dc9ee546da2c7 Mon Sep 17 00:00:00 2001 From: Pekka Enberg Date: Tue, 3 Nov 2026 11:24:44 +0200 Subject: [PATCH 3/8] fsfork -l: Call a fork applied if the directory has its changes A fork was applied only while the directory had every file it changed just as the fork does, so it stopped being applied once the directory changed one of them again. Now it is applied if the patch fsdiff shows for it would undo in the directory, as it would once applied there, whatever changed after. --- cmd/fsfork/forks.rs | 222 +++++++++++++++++++++++++++++++++++++ cmd/fsfork/fsfork.1 | 13 ++- cmd/fsfork/fsfork.rs | 4 +- cmd/fsfork/list.rs | 170 ---------------------------- cmd/fsfork/tests/fsfork.rs | 25 +++++ fsfork/git.rs | 36 ++++++ 6 files changed, 294 insertions(+), 176 deletions(-) create mode 100644 cmd/fsfork/forks.rs delete mode 100644 cmd/fsfork/list.rs diff --git a/cmd/fsfork/forks.rs b/cmd/fsfork/forks.rs new file mode 100644 index 0000000..ab0de63 --- /dev/null +++ b/cmd/fsfork/forks.rs @@ -0,0 +1,222 @@ +//! The forks of a directory, as `fsfork -l` lists them: with how long each +//! has been left alone and what changed in it, so that those done with can +//! be told from those not. + +use std::{ + fmt, fs, + io::{self, Write}, + path::Path, + time::{Duration, SystemTime}, +}; + +use fsfork::{Found, git, message}; + +/// A fork, looked into. +struct Looked { + found: Found, + state: State, + /// When it was last changed, or made, if it was not. + touched: SystemTime, +} + +/// What is in a fork. +enum State { + /// Nothing changed in it. + Unchanged, + /// Something did, and the directory has it all now. + Applied, + /// `files` changed in it, of which the directory has `applied` now. + Changed { files: usize, applied: usize }, + /// The fork is gone, and its base is not. + LeftOver, + /// It could not be compared with its base. + Unknown, +} + +impl fmt::Display for State { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + State::Unchanged => f.write_str("unchanged"), + State::Applied => f.write_str("applied"), + State::Changed { files, applied } => { + let s = if *files == 1 { "" } else { "s" }; + write!(f, "{files} file{s} changed")?; + if *applied > 0 { + write!(f, ", {applied} applied")?; + } + Ok(()) + } + State::LeftOver => f.write_str("base left over, with no fork"), + State::Unknown => f.write_str("cannot be compared with its base"), + } + } +} + +impl Looked { + /// Where it is: the fork, or if only its base is left, the base. + fn path(&self) -> &Path { + match self.state { + State::LeftOver => &self.found.base, + _ => &self.found.fork, + } + } +} + +/// Lists the forks of `dir`, those left alone longest first, and returns +/// whether all could be looked into. +pub fn list(dir: &Path) -> io::Result { + let (forks, all) = look(dir)?; + let now = SystemTime::now(); + let rows: Vec<_> = forks + .iter() + .map(|fork| row(fork, now, &fork.state)) + .collect(); + print(&rows)?; + Ok(all) +} + +/// Looks into the forks of `dir`, and returns them, those left alone longest +/// first, and whether all could be looked into, having said why not. +fn look(dir: &Path) -> io::Result<(Vec, bool)> { + let found = fsfork::forks(dir)?; + if found.is_empty() { + return Ok((Vec::new(), true)); + } + let dir = dir.canonicalize()?; + // The terminal's signals reach git too, which exits; `fsfork` outlives + // it to remove its repository. + for signal in git::SIGNALS { + unsafe { libc::signal(signal, libc::SIG_IGN) }; + } + let repo = git::Repo::new()?; + let mut all = true; + let mut forks: Vec = found + .into_iter() + .map(|found| match state(&repo, &dir, &found) { + Ok((state, touched)) => Looked { + found, + state, + touched, + }, + Err(e) => { + message::say(message::describe(&e)); + all = false; + let touched = found.made; + Looked { + found, + state: State::Unknown, + touched, + } + } + }) + .collect(); + // Those left alone longest, the likeliest to be done with, first. + forks.sort_by_key(|fork| fork.touched); + Ok((forks, all)) +} + +/// What is in `fork`, of `dir`, and when it was last changed, or made, if it +/// was not. +fn state(repo: &git::Repo, dir: &Path, fork: &Found) -> io::Result<(State, SystemTime)> { + if fork.left_over { + return Ok((State::LeftOver, fork.made)); + } + let (before, after) = repo.record(&fork.base, &fork.fork)?; + let changed = repo.changed(&before, &after)?; + // A new directory at the top, such as for a build, changes the fork's + // own time. + let made = modified(&fork.fork, Path::new("")).map_or(fork.made, |t| t.max(fork.made)); + if changed.is_empty() { + return Ok((State::Unchanged, made)); + } + let touched = changed + .iter() + .filter_map(|path| modified(&fork.fork, path)) + .fold(made, SystemTime::max); + if repo.applied(&before, &after, None, dir)? { + return Ok((State::Applied, touched)); + } + let mut applied = 0; + for path in &changed { + if repo.applied(&before, &after, Some(path), dir)? { + applied += 1; + } + } + let files = changed.len(); + Ok((State::Changed { files, applied }, touched)) +} + +/// When `path` in `fork` was last changed, or if it is gone, the directory +/// it was in, which changed when it went. +fn modified(fork: &Path, path: &Path) -> Option { + path.ancestors() + .map(|path| fork.join(path)) + .find_map(|path| fs::symlink_metadata(path).ok()) + .and_then(|meta| meta.modified().ok()) +} + +/// The columns of `fork`'s line, as of `now`, saying `what` of it. +fn row(fork: &Looked, now: SystemTime, what: &dyn fmt::Display) -> [String; 3] { + [ + message::shown(fork.path()).display().to_string(), + age(now.duration_since(fork.touched).unwrap_or_default()), + what.to_string(), + ] +} + +/// Prints `rows` on stdout, in columns as wide as the widest of each. +fn print(rows: &[[String; N]]) -> io::Result<()> { + let mut widths = [0; N]; + for row in rows { + for (width, column) in widths.iter_mut().zip(row) { + *width = (*width).max(column.chars().count()); + } + } + let mut out = io::stdout().lock(); + for row in rows { + let mut line = String::new(); + for (i, (column, width)) in row.iter().zip(widths).enumerate() { + if i + 1 == N { + line.push_str(column); + } else { + line.push_str(&format!("{column:width$} ")); + } + } + writeln!(out, "{line}")?; + } + out.flush() +} + +/// How long ago something was, `ago` since, roughly, as in "3 days ago". +fn age(ago: Duration) -> String { + let secs = ago.as_secs(); + let (n, unit) = match secs { + 0..60 => return "just now".to_string(), + 60..3600 => (secs / 60, "minute"), + 3600..86400 => (secs / 3600, "hour"), + 86400..1209600 => (secs / 86400, "day"), + 1209600..5184000 => (secs / 604800, "week"), + 5184000..63072000 => (secs / 2592000, "month"), + _ => (secs / 31536000, "year"), + }; + let s = if n == 1 { "" } else { "s" }; + format!("{n} {unit}{s} ago") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn says_how_long_ago_roughly() { + let ago = |secs| age(Duration::from_secs(secs)); + assert_eq!(ago(5), "just now"); + assert_eq!(ago(60), "1 minute ago"); + assert_eq!(ago(3599), "59 minutes ago"); + assert_eq!(ago(7200), "2 hours ago"); + assert_eq!(ago(86400 * 3), "3 days ago"); + assert_eq!(ago(86400 * 14), "2 weeks ago"); + assert_eq!(ago(86400 * 90), "3 months ago"); + assert_eq!(ago(86400 * 800), "2 years ago"); + } +} diff --git a/cmd/fsfork/fsfork.1 b/cmd/fsfork/fsfork.1 index a7577a1..4cfb68f 100644 --- a/cmd/fsfork/fsfork.1 +++ b/cmd/fsfork/fsfork.1 @@ -112,7 +112,13 @@ would say. .B applied Something changed in it, and .I dir -has every file that changed as it is in the fork: the changes were applied. +has the changes: the patch +.BR fsdiff (1) +shows would undo in +.IR dir , +as it would once applied there, even if +.I dir +changed after. .TP .IB n " files changed" "\fR, \fPm applied" .I n @@ -120,9 +126,8 @@ files changed in it, of which .IR dir , if .I m -is given, has -.I m -as they are in the fork. +is given, has the changes to +.IR m . .TP .B base left over, with no fork The fork is gone, and its base is not. diff --git a/cmd/fsfork/fsfork.rs b/cmd/fsfork/fsfork.rs index 32ce082..c8af5b5 100644 --- a/cmd/fsfork/fsfork.rs +++ b/cmd/fsfork/fsfork.rs @@ -3,7 +3,7 @@ //! was forked, for `fsdiff` to compare the fork with. With `-l`, it lists //! the forks of a directory instead. -mod list; +mod forks; use std::{ env, @@ -100,7 +100,7 @@ fn list(args: Args) -> ExitCode { return message::usage_error(problem, USAGE, 1); } let dir = args.paths.first().map_or(Path::new("."), PathBuf::as_path); - match list::list(dir) { + match forks::list(dir) { Ok(true) => ExitCode::SUCCESS, Ok(false) => ExitCode::FAILURE, Err(e) => { diff --git a/cmd/fsfork/list.rs b/cmd/fsfork/list.rs deleted file mode 100644 index 2d73e12..0000000 --- a/cmd/fsfork/list.rs +++ /dev/null @@ -1,170 +0,0 @@ -//! `fsfork -l`: lists the forks of a directory, with how long each has been -//! left alone and what changed in it, so that those done with can be told -//! from those not. - -use std::{ - fs, - io::{self, Write}, - os::unix::fs::PermissionsExt, - path::{Path, PathBuf}, - time::{Duration, SystemTime}, -}; - -use fsfork::{Found, git, message}; - -/// Lists the forks of `dir`, those left alone longest first, and returns -/// whether all could be looked into. -pub fn list(dir: &Path) -> io::Result { - let found = fsfork::forks(dir)?; - if found.is_empty() { - return Ok(true); - } - let dir = dir.canonicalize()?; - // The terminal's signals reach git too, which exits; `fsfork` outlives - // it to remove its repository. - for signal in git::SIGNALS { - unsafe { libc::signal(signal, libc::SIG_IGN) }; - } - let repo = git::Repo::new()?; - let now = SystemTime::now(); - let mut all = true; - let mut rows = Vec::new(); - for fork in &found { - let (state, touched) = match state(&repo, &dir, fork) { - Ok(state) => state, - Err(e) => { - message::say(message::describe(&e)); - all = false; - ("cannot be compared with its base".to_string(), fork.made) - } - }; - let path = if fork.left_over { - &fork.base - } else { - &fork.fork - }; - rows.push(( - touched, - [ - message::shown(path).display().to_string(), - age(now.duration_since(touched).unwrap_or_default()), - state, - ], - )); - } - // Those left alone longest, the likeliest to be done with, first. - rows.sort_by_key(|(touched, _)| *touched); - let rows: Vec<_> = rows.into_iter().map(|(_, row)| row).collect(); - let path_width = rows.iter().map(|row| row[0].len()).max().unwrap_or(0); - let age_width = rows.iter().map(|row| row[1].len()).max().unwrap_or(0); - let mut out = io::stdout().lock(); - for [path, age, state] in rows { - writeln!(out, "{path:path_width$} {age:age_width$} {state}")?; - } - out.flush()?; - Ok(all) -} - -/// What is in `fork`, of `dir`: whether anything changed in it since it was -/// made, and if so, whether `dir` has those changes now; and when it was last -/// changed, or made, if it was not. -fn state(repo: &git::Repo, dir: &Path, fork: &Found) -> io::Result<(String, SystemTime)> { - if fork.left_over { - return Ok(("base left over, with no fork".to_string(), fork.made)); - } - let (before, after) = repo.record(&fork.base, &fork.fork)?; - let changed = repo.changed(&before, &after)?; - if changed.is_empty() { - return Ok(("unchanged".to_string(), fork.made)); - } - let touched = changed - .iter() - .filter_map(|path| modified(&fork.fork, path)) - .fold(fork.made, SystemTime::max); - let applied = changed - .iter() - .filter(|path| same(&fork.fork.join(path), &dir.join(path))) - .count(); - let files = match changed.len() { - 1 => "1 file changed".to_string(), - n => format!("{n} files changed"), - }; - let state = match applied { - 0 => files, - n if n == changed.len() => "applied".to_string(), - n => format!("{files}, {n} applied"), - }; - Ok((state, touched)) -} - -/// When `path` in `fork` was last changed, or if it is gone, the directory -/// it was in, which changed when it went. -fn modified(fork: &Path, path: &Path) -> Option { - path.ancestors() - .map(|path| fork.join(path)) - .find_map(|path| fs::symlink_metadata(path).ok()) - .and_then(|meta| meta.modified().ok()) -} - -/// Whether `a` and `b` are the same as git sees them: both missing, links to -/// the same place, or files with the same contents, both executable or -/// neither. -fn same(a: &Path, b: &Path) -> bool { - let (a_meta, b_meta) = (fs::symlink_metadata(a), fs::symlink_metadata(b)); - let (a_meta, b_meta) = match (a_meta, b_meta) { - (Err(a), Err(b)) => { - return a.kind() == io::ErrorKind::NotFound && b.kind() == io::ErrorKind::NotFound; - } - (Ok(a), Ok(b)) => (a, b), - _ => return false, - }; - let (a_type, b_type) = (a_meta.file_type(), b_meta.file_type()); - if a_type.is_symlink() && b_type.is_symlink() { - return target(a).is_some_and(|a| target(b).as_ref() == Some(&a)); - } - if !(a_type.is_file() && b_type.is_file()) { - return false; - } - let executable = |mode: u32| mode & 0o111 != 0; - executable(a_meta.permissions().mode()) == executable(b_meta.permissions().mode()) - && a_meta.len() == b_meta.len() - && fs::read(a).is_ok_and(|a| fs::read(b).is_ok_and(|b| a == b)) -} - -fn target(link: &Path) -> Option { - fs::read_link(link).ok() -} - -/// How long ago something was, `ago` since, roughly, as in "3 days ago". -fn age(ago: Duration) -> String { - let secs = ago.as_secs(); - let (n, unit) = match secs { - 0..60 => return "just now".to_string(), - 60..3600 => (secs / 60, "minute"), - 3600..86400 => (secs / 3600, "hour"), - 86400..1209600 => (secs / 86400, "day"), - 1209600..5184000 => (secs / 604800, "week"), - 5184000..63072000 => (secs / 2592000, "month"), - _ => (secs / 31536000, "year"), - }; - let s = if n == 1 { "" } else { "s" }; - format!("{n} {unit}{s} ago") -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn says_how_long_ago_roughly() { - let ago = |secs| age(Duration::from_secs(secs)); - assert_eq!(ago(5), "just now"); - assert_eq!(ago(60), "1 minute ago"); - assert_eq!(ago(3599), "59 minutes ago"); - assert_eq!(ago(7200), "2 hours ago"); - assert_eq!(ago(86400 * 3), "3 days ago"); - assert_eq!(ago(86400 * 14), "2 weeks ago"); - assert_eq!(ago(86400 * 90), "3 months ago"); - assert_eq!(ago(86400 * 800), "2 years ago"); - } -} diff --git a/cmd/fsfork/tests/fsfork.rs b/cmd/fsfork/tests/fsfork.rs index 9c4a6a8..b241869 100644 --- a/cmd/fsfork/tests/fsfork.rs +++ b/cmd/fsfork/tests/fsfork.rs @@ -566,6 +566,31 @@ fn lists_the_forks_with_what_changed_in_each() { } } +#[test] +fn a_fork_is_applied_if_the_directory_has_its_changes_even_after_more() { + let world = World::new(); + let dir = world.project(); + let lines = |second: &str, last: &str| format!("1\n{second}\n3\n4\n5\n6\n7\n{last}\n"); + write(&dir, "lines", &lines("2", "8")); + let out = fsfork(&dir, &[]); + let fork = PathBuf::from(stdout(&out).trim_end()); + write(&fork, "lines", &lines("two", "8")); + let state = || { + let out = fsfork(&dir, &["-l"]); + assert!(out.status.success(), "{}", stderr(&out)); + stdout(&out) + .trim_end() + .rsplit(" ") + .next() + .unwrap() + .to_string() + }; + write(&dir, "lines", &lines("2", "eight")); + assert_eq!(state(), "1 file changed"); + write(&dir, "lines", &lines("two", "eight")); + assert_eq!(state(), "applied"); +} + #[test] fn lists_nothing_if_there_are_no_forks() { let world = World::new(); diff --git a/fsfork/git.rs b/fsfork/git.rs index bd016cb..985dda7 100644 --- a/fsfork/git.rs +++ b/fsfork/git.rs @@ -122,6 +122,42 @@ impl Repo { .collect()) } + /// Whether `dir` has the changes between the trees `before` and `after`, + /// or with `path`, those to it only: whether they could be undone in + /// `dir`, as they could if they were applied to it, even if it changed + /// after. + pub fn applied( + &self, + before: &str, + after: &str, + path: Option<&Path>, + dir: &Path, + ) -> io::Result { + let mut diff = self.git(); + diff.args(["--literal-pathspecs", "diff", "--binary", "--no-renames"]) + .args([before, after]); + if let Some(path) = path { + diff.arg("--").arg(path); + } + let patch = diff.stderr(process::Stdio::inherit()).output()?; + if !patch.status.success() { + return Err(io::Error::other("git could not compare the trees")); + } + let file = self.dir.join("patch"); + fs::write(&file, &patch.stdout)?; + let undone = status( + self.git() + .arg("--work-tree") + .arg(dir) + .args(["apply", "--reverse", "--check"]) + .arg(&file) + .current_dir(dir) + .stdout(process::Stdio::null()) + .stderr(process::Stdio::null()), + )?; + Ok(undone.success()) + } + /// Records the files in `tree` that git does not ignore as a tree, /// keeping the index in `index`, and returns the tree's ID. fn snapshot(&self, tree: &Path, index: &Path) -> io::Result { From 06527c0eb484921e29fcdb545c6e3de82c54f732 Mon Sep 17 00:00:00 2001 From: Pekka Enberg Date: Tue, 3 Nov 2026 11:27:34 +0200 Subject: [PATCH 4/8] fsfork: Remove the forks done with, with --prune fsfork --prune removes the forks of the directory that fsfork -l lists as unchanged or applied, with their bases, and the bases left over, so that forks need not pile up next to it. It keeps any changed in the last hour, as one just made may have a command starting in it, and one just applied may have more to come; any the working directory is in; and any with changes the directory does not have. It says which it removed and which it kept, and why. --- README.md | 4 ++ cmd/fsfork/forks.rs | 75 +++++++++++++++++++++++++++++++++++++- cmd/fsfork/fsfork.1 | 43 +++++++++++++++++++++- cmd/fsfork/fsfork.rs | 42 ++++++++++++++------- cmd/fsfork/tests/fsfork.rs | 73 ++++++++++++++++++++++++++++++++++++- 5 files changed, 219 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 73ce08b..5b078d2 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,10 @@ $ fsfork -l ../turso.swebench 9 minutes ago applied ``` +`fsfork --prune` removes those done with: the forks that are unchanged or +applied, with their bases, and the bases left over, once each has been left +alone for an hour. It keeps the others, and says why. + Each command has a man page: [`fsfork.1`](cmd/fsfork/fsfork.1), [`confine.1`](cmd/confine/confine.1), and [`fsdiff.1`](cmd/fsdiff/fsdiff.1) (`man ./cmd/fsfork/fsfork.1`). diff --git a/cmd/fsfork/forks.rs b/cmd/fsfork/forks.rs index ab0de63..add3157 100644 --- a/cmd/fsfork/forks.rs +++ b/cmd/fsfork/forks.rs @@ -1,9 +1,9 @@ //! The forks of a directory, as `fsfork -l` lists them: with how long each //! has been left alone and what changed in it, so that those done with can -//! be told from those not. +//! be told from those not; and as `fsfork --prune` removes those done with. use std::{ - fmt, fs, + env, fmt, fs, io::{self, Write}, path::Path, time::{Duration, SystemTime}, @@ -75,6 +75,77 @@ pub fn list(dir: &Path) -> io::Result { Ok(all) } +/// How long a fork must be left alone for `prune` to remove it: one just +/// made, with nothing changed in it yet, may have a command starting there, +/// and one just applied may have more to come. +const LEFT_ALONE: Duration = Duration::from_secs(60 * 60); + +/// How long a fork must be left alone for `prune` to remove it: `LEFT_ALONE`, +/// or in a debug build, for tests, which cannot make a fork older, as many +/// seconds as `FSFORK_TEST_LEFT_ALONE` says. +fn left_alone() -> Duration { + #[cfg(debug_assertions)] + if let Some(secs) = env::var("FSFORK_TEST_LEFT_ALONE") + .ok() + .and_then(|secs| secs.parse().ok()) + { + return Duration::from_secs(secs); + } + LEFT_ALONE +} + +/// Removes the forks of `dir` that are unchanged or applied and were left +/// alone long enough, and the bases left over from forks removed without +/// them, saying which it removed and which it kept, and why; and returns +/// whether all could be looked into and removed. +pub fn prune(dir: &Path) -> io::Result { + let (forks, mut all) = look(dir)?; + let now = SystemTime::now(); + let cwd = env::current_dir().and_then(|cwd| cwd.canonicalize()).ok(); + let long_enough = left_alone(); + let mut rows = Vec::new(); + for fork in &forks { + let done = matches!( + fork.state, + State::Unchanged | State::Applied | State::LeftOver + ); + let left_alone = now.duration_since(fork.touched).unwrap_or_default() >= long_enough; + let here = cwd.as_ref().is_some_and(|cwd| cwd.starts_with(fork.path())); + let kept_because = if !done { + None + } else if !left_alone { + Some("but left alone less than an hour") + } else if here { + Some("but the working directory is in it") + } else if let Err(e) = remove(fork) { + message::say(message::describe(&e)); + all = false; + Some("but cannot be removed") + } else { + let [path, age, state] = row(fork, now, &fork.state); + rows.push(["removed".to_string(), path, age, state]); + continue; + }; + let [path, age, state] = match kept_because { + Some(why) => row(fork, now, &format!("{}, {why}", fork.state)), + None => row(fork, now, &fork.state), + }; + rows.push(["kept".to_string(), path, age, state]); + } + print(&rows)?; + Ok(all) +} + +/// Removes `fork`, and its base. +fn remove(fork: &Looked) -> io::Result<()> { + match fork.state { + State::LeftOver => { + fs::remove_dir_all(&fork.found.base).map_err(|e| fsfork::at(&fork.found.base, e)) + } + _ => fsfork::remove(&fork.found.fork), + } +} + /// Looks into the forks of `dir`, and returns them, those left alone longest /// first, and whether all could be looked into, having said why not. fn look(dir: &Path) -> io::Result<(Vec, bool)> { diff --git a/cmd/fsfork/fsfork.1 b/cmd/fsfork/fsfork.1 index 4cfb68f..08a0603 100644 --- a/cmd/fsfork/fsfork.1 +++ b/cmd/fsfork/fsfork.1 @@ -12,6 +12,9 @@ fsfork \- fork a directory: make a copy-on-write clone of it .br .B fsfork \-l .RI [ dir ] +.br +.B fsfork \-\-prune +.RI [ dir ] .SH DESCRIPTION .B fsfork makes a copy-on-write clone of @@ -137,6 +140,30 @@ Forks made elsewhere, with .I fork given, are not listed. .PP +With +.BR \-\-prune , +it forks nothing, and removes the forks of +.I dir +that +.B \-l +would list as +.BR unchanged " or " applied , +with their bases, and the bases left over, if each has been left alone for +an hour: one just made may have a command starting in it, and one just +applied may have more to come. +It keeps the others, and any the working directory is in. +A line for each says +.B removed +or +.BR kept , +and then what +.B \-l +would, with why it was kept, if it would have been removed otherwise. +.B \-l +shows what +.B \-\-prune +would remove: it asks nothing. +.PP .B fsfork goes by .I .gitignore @@ -171,6 +198,11 @@ List the forks of the directory, rather than fork it. It cannot be given with the other options or with .IR fork . .TP +.B \-\-prune +Remove the forks of the directory done with, rather than fork it. +It cannot be given with the other options or with +.IR fork . +.TP .B \-\-no\-ignore Fork what is ignored too, so that builds in the fork start warm. Making it takes longer if what is ignored holds many files. @@ -184,7 +216,10 @@ On a terminal, the status of the shell, or 1, having made neither, if the shell cannot be run. With .BR \-l , -0 if every fork was listed with what is in it, and 1 otherwise. +0 if every fork was listed with what is in it, and 1 otherwise; with +.BR \-\-prune , +0 if every fork was looked into, and each done with removed, and 1 +otherwise. .SH EXAMPLES Fork the working directory, and work in the fork in a shell of its own: .PP @@ -230,6 +265,12 @@ and remove one: .fi .RE .PP +Remove the forks of the working directory that are done with: +.PP +.RS +.B fsfork \-\-prune +.RE +.PP Fork the working directory with its build output, and go there: .PP .RS diff --git a/cmd/fsfork/fsfork.rs b/cmd/fsfork/fsfork.rs index c8af5b5..0796e10 100644 --- a/cmd/fsfork/fsfork.rs +++ b/cmd/fsfork/fsfork.rs @@ -1,7 +1,8 @@ //! `fsfork` forks a directory: it makes a copy-on-write clone of it, the //! fork, and another, the base, which keeps what the directory was when it //! was forked, for `fsdiff` to compare the fork with. With `-l`, it lists -//! the forks of a directory instead. +//! the forks of a directory instead, and with `--prune`, removes those done +//! with. mod forks; @@ -18,7 +19,8 @@ use argh::FromArgs; use fsfork::{Contents, message}; /// How to give the arguments, as in the man page, a line for each form. -const USAGE: &str = "fsfork [--no-ignore] [--print] [-n name] [dir [fork]]\nfsfork -l [dir]"; +const USAGE: &str = + "fsfork [--no-ignore] [--print] [-n name] [dir [fork]]\nfsfork -l [dir]\nfsfork --prune [dir]"; /// Fork a directory: make a copy-on-write clone of it, and start a shell there /// or, if not on a terminal, print where it is. @@ -29,6 +31,12 @@ struct Args { #[argh(switch, short = 'l')] list: bool, + /// remove the forks of the directory that are unchanged or applied, and + /// the bases left over from forks removed without them, rather than fork + /// it + #[argh(switch)] + prune: bool, + /// print where the fork is, rather than start a shell there #[argh(switch)] print: bool, @@ -54,8 +62,8 @@ fn main() -> ExitCode { Ok(args) => args, Err(code) => return code, }; - if args.list { - return list(args); + if args.list || args.prune { + return list_or_prune(args); } // A shell needs both: with stdout captured, as in `cd $(fsfork)`, the // path is wanted, and with stdin not a terminal, a shell would run what @@ -83,24 +91,32 @@ fn main() -> ExitCode { } } -/// Lists the forks of the directory `args` give. -fn list(args: Args) -> ExitCode { - let conflict = if args.print { - Some("-l cannot be given with --print") +/// Lists or prunes the forks of the directory `args` give, as they ask. +fn list_or_prune(args: Args) -> ExitCode { + let option = if args.list { "-l" } else { "--prune" }; + let conflict = if args.list && args.prune { + Some("-l cannot be given with --prune".to_string()) + } else if args.print { + Some(format!("{option} cannot be given with --print")) } else if args.no_ignore { - Some("-l cannot be given with --no-ignore") + Some(format!("{option} cannot be given with --no-ignore")) } else if args.name.is_some() { - Some("-l cannot be given with -n") + Some(format!("{option} cannot be given with -n")) } else if args.paths.len() > 1 { - Some("too many arguments") + Some("too many arguments".to_string()) } else { None }; if let Some(problem) = conflict { - return message::usage_error(problem, USAGE, 1); + return message::usage_error(&problem, USAGE, 1); } let dir = args.paths.first().map_or(Path::new("."), PathBuf::as_path); - match forks::list(dir) { + let done = if args.list { + forks::list(dir) + } else { + forks::prune(dir) + }; + match done { Ok(true) => ExitCode::SUCCESS, Ok(false) => ExitCode::FAILURE, Err(e) => { diff --git a/cmd/fsfork/tests/fsfork.rs b/cmd/fsfork/tests/fsfork.rs index b241869..9ca169d 100644 --- a/cmd/fsfork/tests/fsfork.rs +++ b/cmd/fsfork/tests/fsfork.rs @@ -591,6 +591,70 @@ fn a_fork_is_applied_if_the_directory_has_its_changes_even_after_more() { assert_eq!(state(), "applied"); } +#[test] +fn prunes_the_forks_done_with_and_keeps_the_others() { + let world = World::new(); + let dir = world.project(); + let fork = || PathBuf::from(stdout(&fsfork(&dir, &[])).trim_end()); + let unchanged = fork(); + let changed = fork(); + write(&changed, "a", "two\n"); + let applied = fork(); + write(&applied, "b", "new\n"); + write(&dir, "b", "new\n"); + let removed = fork(); + fs::remove_dir_all(&removed).unwrap(); + let working = fork(); + + // Just made, they may have a command starting in them: none goes. + let out = fsfork(&dir, &["--prune"]); + assert!(out.status.success(), "{}", stderr(&out)); + for path in [&unchanged, &changed, &applied, &working] { + assert!(path.is_dir()); + } + assert!(stdout(&out).contains("unchanged, but left alone less than an hour")); + + let out = Command::new(env!("CARGO_BIN_EXE_fsfork")) + .args(["--prune", "../project"]) + .current_dir(&working) + .env("FSFORK_TEST_LEFT_ALONE", "0") + .output() + .unwrap(); + assert!(out.status.success(), "{}", stderr(&out)); + let mut lines: Vec> = stdout(&out) + .lines() + .map(|line| { + let mut columns = line.split(" ").filter(|c| !c.is_empty()); + let (done, path) = (columns.next().unwrap(), columns.next().unwrap()); + let state = columns.last().unwrap().trim(); + vec![done.trim().into(), path.trim().into(), state.into()] + }) + .collect(); + lines.sort_by(|a, b| a[1].cmp(&b[1])); + let expected = [ + ["kept", ".", "unchanged, but the working directory is in it"], + [ + "removed", + "../.project.4.base", + "base left over, with no fork", + ], + ["removed", "../project.1", "unchanged"], + ["kept", "../project.2", "1 file changed"], + ["removed", "../project.3", "applied"], + ]; + let expected: Vec> = expected + .iter() + .map(|row| row.iter().map(|c| c.to_string()).collect()) + .collect(); + assert_eq!(lines, expected, "{}", stdout(&out)); + assert!(!unchanged.exists() && !world.path(".project.1.base").exists()); + assert!(!applied.exists() && !world.path(".project.3.base").exists()); + assert!(!world.path(".project.4.base").exists()); + assert!(changed.is_dir() && world.path(".project.2.base").is_dir()); + assert!(working.is_dir() && world.path(".project.5.base").is_dir()); + assert_eq!(read(&dir, "a"), "one\n"); +} + #[test] fn lists_nothing_if_there_are_no_forks() { let world = World::new(); @@ -605,7 +669,7 @@ fn lists_nothing_if_there_are_no_forks() { } #[test] -fn lists_but_forks_nothing_and_takes_no_options_for_forking() { +fn lists_and_prunes_but_forks_nothing_and_take_no_options_for_forking() { let world = World::new(); let dir = world.project(); for args in [ @@ -613,6 +677,10 @@ fn lists_but_forks_nothing_and_takes_no_options_for_forking() { &["-l", "--no-ignore"], &["-l", "-n", "x"], &["-l", ".", "../x"], + &["--prune", "--print"], + &["--prune", "-n", "x"], + &["--prune", ".", "../x"], + &["-l", "--prune"], ] { let out = fsfork(&dir, args); assert_fails(&out, "usage: fsfork"); @@ -810,7 +878,8 @@ fn says_what_is_wrong_with_the_arguments_and_how_to_give_them() { let world = World::new(); let dir = world.project(); let usage = "usage: fsfork [--no-ignore] [--print] [-n name] [dir [fork]]\n \ - fsfork -l [dir]\n"; + fsfork -l [dir]\n \ + fsfork --prune [dir]\n"; let out = fsfork(&dir, &["--bogus"]); assert_eq!(out.status.code(), Some(1)); assert_eq!( From 419ecd7dbdc6c5ddb50d53128db02b2ac7330fe2 Mon Sep 17 00:00:00 2001 From: Pekka Enberg Date: Tue, 3 Nov 2026 11:51:02 +0200 Subject: [PATCH 5/8] fsfork --prune: Say what it removed, and only how many it kept It said a line for each fork, removed or kept, and why, in the columns fsfork -l prints, which buried what it did among what it did not. Now it says each it removed on stdout, as "removed ../turso.1", and then how many it kept, and why, on one line: "fsfork: kept 2 changed, 3 recent". fsfork -l shows the rest. --- README.md | 2 +- cmd/fsfork/forks.rs | 102 ++++++++++++++++++++++++++----------- cmd/fsfork/fsfork.1 | 19 ++++--- cmd/fsfork/tests/fsfork.rs | 37 +++++--------- 4 files changed, 98 insertions(+), 62 deletions(-) diff --git a/README.md b/README.md index 5b078d2..f958069 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ $ fsfork -l `fsfork --prune` removes those done with: the forks that are unchanged or applied, with their bases, and the bases left over, once each has been left -alone for an hour. It keeps the others, and says why. +alone for an hour. It says what it removed, and how many it kept, and why. Each command has a man page: [`fsfork.1`](cmd/fsfork/fsfork.1), [`confine.1`](cmd/confine/confine.1), and [`fsdiff.1`](cmd/fsdiff/fsdiff.1) diff --git a/cmd/fsfork/forks.rs b/cmd/fsfork/forks.rs index add3157..0f1d2db 100644 --- a/cmd/fsfork/forks.rs +++ b/cmd/fsfork/forks.rs @@ -96,46 +96,90 @@ fn left_alone() -> Duration { /// Removes the forks of `dir` that are unchanged or applied and were left /// alone long enough, and the bases left over from forks removed without -/// them, saying which it removed and which it kept, and why; and returns -/// whether all could be looked into and removed. +/// them, saying on stdout each it removed, and on stderr how many it kept, +/// and why; and returns whether all could be looked into and removed. pub fn prune(dir: &Path) -> io::Result { let (forks, mut all) = look(dir)?; let now = SystemTime::now(); let cwd = env::current_dir().and_then(|cwd| cwd.canonicalize()).ok(); let long_enough = left_alone(); - let mut rows = Vec::new(); + let mut kept = [0; Kept::ALL.len()]; + let mut out = io::stdout().lock(); for fork in &forks { - let done = matches!( - fork.state, - State::Unchanged | State::Applied | State::LeftOver - ); - let left_alone = now.duration_since(fork.touched).unwrap_or_default() >= long_enough; - let here = cwd.as_ref().is_some_and(|cwd| cwd.starts_with(fork.path())); - let kept_because = if !done { - None - } else if !left_alone { - Some("but left alone less than an hour") - } else if here { - Some("but the working directory is in it") - } else if let Err(e) = remove(fork) { - message::say(message::describe(&e)); - all = false; - Some("but cannot be removed") - } else { - let [path, age, state] = row(fork, now, &fork.state); - rows.push(["removed".to_string(), path, age, state]); - continue; - }; - let [path, age, state] = match kept_because { - Some(why) => row(fork, now, &format!("{}, {why}", fork.state)), - None => row(fork, now, &fork.state), + let why = match fork.state { + State::Changed { .. } => Some(Kept::Changed), + State::Unknown => Some(Kept::NotCompared), + _ if now.duration_since(fork.touched).unwrap_or_default() < long_enough => { + Some(Kept::Recent) + } + _ if cwd.as_ref().is_some_and(|cwd| cwd.starts_with(fork.path())) => Some(Kept::InUse), + _ => match remove(fork) { + Ok(()) => { + let path = message::shown(fork.path()); + writeln!(out, "removed {}", path.display())?; + None + } + Err(e) => { + message::say(message::describe(&e)); + all = false; + Some(Kept::NotRemoved) + } + }, }; - rows.push(["kept".to_string(), path, age, state]); + if let Some(why) = why { + kept[why as usize] += 1; + } + } + out.flush()?; + let kept: Vec = Kept::ALL + .iter() + .zip(kept) + .filter(|(_, n)| *n > 0) + .map(|(why, n)| format!("{n} {}", why.word())) + .collect(); + if !kept.is_empty() { + message::say(format!("kept {}", kept.join(", "))); } - print(&rows)?; Ok(all) } +/// Why `prune` kept a fork. +#[derive(Clone, Copy)] +enum Kept { + /// It has changes the directory does not. + Changed, + /// It was left alone too little. + Recent, + /// The working directory is in it. + InUse, + /// It could not be compared with its base. + NotCompared, + /// Removing it failed. + NotRemoved, +} + +impl Kept { + /// Every reason, in the order they are said. + const ALL: [Kept; 5] = [ + Kept::Changed, + Kept::Recent, + Kept::InUse, + Kept::NotCompared, + Kept::NotRemoved, + ]; + + /// What is said of those kept for this reason, as in "2 changed". + fn word(self) -> &'static str { + match self { + Kept::Changed => "changed", + Kept::Recent => "recent", + Kept::InUse => "in use", + Kept::NotCompared => "not compared", + Kept::NotRemoved => "not removed", + } + } +} + /// Removes `fork`, and its base. fn remove(fork: &Looked) -> io::Result<()> { match fork.state { diff --git a/cmd/fsfork/fsfork.1 b/cmd/fsfork/fsfork.1 index 08a0603..d4035c8 100644 --- a/cmd/fsfork/fsfork.1 +++ b/cmd/fsfork/fsfork.1 @@ -152,13 +152,18 @@ with their bases, and the bases left over, if each has been left alone for an hour: one just made may have a command starting in it, and one just applied may have more to come. It keeps the others, and any the working directory is in. -A line for each says -.B removed -or -.BR kept , -and then what -.B \-l -would, with why it was kept, if it would have been removed otherwise. +It says on standard output each it removed, as +.BR "removed ../turso.1" , +and then, on standard error, how many it kept, and why, as +.BR "fsfork: kept 2 changed, 3 recent" : +.B changed +for those with changes +.I dir +does not have, +.B recent +for those left alone less than an hour, and +.B in use +for those the working directory is in. .B \-l shows what .B \-\-prune diff --git a/cmd/fsfork/tests/fsfork.rs b/cmd/fsfork/tests/fsfork.rs index 9ca169d..5243933 100644 --- a/cmd/fsfork/tests/fsfork.rs +++ b/cmd/fsfork/tests/fsfork.rs @@ -612,7 +612,8 @@ fn prunes_the_forks_done_with_and_keeps_the_others() { for path in [&unchanged, &changed, &applied, &working] { assert!(path.is_dir()); } - assert!(stdout(&out).contains("unchanged, but left alone less than an hour")); + assert_eq!(stdout(&out), ""); + assert_eq!(stderr(&out), "fsfork: kept 1 changed, 4 recent\n"); let out = Command::new(env!("CARGO_BIN_EXE_fsfork")) .args(["--prune", "../project"]) @@ -621,32 +622,18 @@ fn prunes_the_forks_done_with_and_keeps_the_others() { .output() .unwrap(); assert!(out.status.success(), "{}", stderr(&out)); - let mut lines: Vec> = stdout(&out) - .lines() - .map(|line| { - let mut columns = line.split(" ").filter(|c| !c.is_empty()); - let (done, path) = (columns.next().unwrap(), columns.next().unwrap()); - let state = columns.last().unwrap().trim(); - vec![done.trim().into(), path.trim().into(), state.into()] - }) - .collect(); - lines.sort_by(|a, b| a[1].cmp(&b[1])); - let expected = [ - ["kept", ".", "unchanged, but the working directory is in it"], + let listed = stdout(&out); + let mut removed: Vec<&str> = listed.lines().collect(); + removed.sort(); + assert_eq!( + removed, [ - "removed", - "../.project.4.base", - "base left over, with no fork", + "removed ../.project.4.base", + "removed ../project.1", + "removed ../project.3", ], - ["removed", "../project.1", "unchanged"], - ["kept", "../project.2", "1 file changed"], - ["removed", "../project.3", "applied"], - ]; - let expected: Vec> = expected - .iter() - .map(|row| row.iter().map(|c| c.to_string()).collect()) - .collect(); - assert_eq!(lines, expected, "{}", stdout(&out)); + ); + assert_eq!(stderr(&out), "fsfork: kept 1 changed, 1 in use\n"); assert!(!unchanged.exists() && !world.path(".project.1.base").exists()); assert!(!applied.exists() && !world.path(".project.3.base").exists()); assert!(!world.path(".project.4.base").exists()); From 9c1b0be57819517be3d16d7de4ea3f23ef3a3bc1 Mon Sep 17 00:00:00 2001 From: Pekka Enberg Date: Tue, 3 Nov 2026 13:39:37 +0200 Subject: [PATCH 6/8] fsfork -l: Print a header, and columns three spaces apart As docker ps does: FORK, UPDATED and STATUS, so that each column says what it is. --- README.md | 9 +++++---- cmd/fsfork/forks.rs | 15 ++++++++------- cmd/fsfork/fsfork.1 | 4 +++- cmd/fsfork/tests/fsfork.rs | 7 ++++++- 4 files changed, 22 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index f958069..bc26186 100644 --- a/README.md +++ b/README.md @@ -49,10 +49,11 @@ tell which to remove: ``` $ fsfork -l -../turso.1 4 days ago unchanged -../turso.3 1 day ago 15 files changed, 6 applied -../.turso.2.base 2 hours ago base left over, with no fork -../turso.swebench 9 minutes ago applied +FORK UPDATED STATUS +../turso.1 4 days ago unchanged +../turso.3 1 day ago 15 files changed, 6 applied +../.turso.2.base 2 hours ago base left over, with no fork +../turso.swebench 9 minutes ago applied ``` `fsfork --prune` removes those done with: the forks that are unchanged or diff --git a/cmd/fsfork/forks.rs b/cmd/fsfork/forks.rs index 0f1d2db..deea385 100644 --- a/cmd/fsfork/forks.rs +++ b/cmd/fsfork/forks.rs @@ -62,14 +62,14 @@ impl Looked { } } -/// Lists the forks of `dir`, those left alone longest first, and returns -/// whether all could be looked into. +/// Lists the forks of `dir`, under a header, those left alone longest first, +/// and returns whether all could be looked into. pub fn list(dir: &Path) -> io::Result { let (forks, all) = look(dir)?; let now = SystemTime::now(); - let rows: Vec<_> = forks - .iter() - .map(|fork| row(fork, now, &fork.state)) + let header = ["FORK", "UPDATED", "STATUS"].map(String::from); + let rows: Vec<_> = std::iter::once(header) + .chain(forks.iter().map(|fork| row(fork, now, &fork.state))) .collect(); print(&rows)?; Ok(all) @@ -279,7 +279,8 @@ fn row(fork: &Looked, now: SystemTime, what: &dyn fmt::Display) -> [String; 3] { ] } -/// Prints `rows` on stdout, in columns as wide as the widest of each. +/// Prints `rows` on stdout, in columns as wide as the widest of each, and +/// three spaces apart. fn print(rows: &[[String; N]]) -> io::Result<()> { let mut widths = [0; N]; for row in rows { @@ -294,7 +295,7 @@ fn print(rows: &[[String; N]]) -> io::Result<()> { if i + 1 == N { line.push_str(column); } else { - line.push_str(&format!("{column:width$} ")); + line.push_str(&format!("{column:width$} ")); } } writeln!(out, "{line}")?; diff --git a/cmd/fsfork/fsfork.1 b/cmd/fsfork/fsfork.1 index d4035c8..46e9227 100644 --- a/cmd/fsfork/fsfork.1 +++ b/cmd/fsfork/fsfork.1 @@ -103,7 +103,9 @@ it forks nothing, and lists the forks of or of the working directory, that are next to it: each .I . with a base, and each base left over from a fork removed without it. -A line for each gives its path, as it would be typed from the working +Under a header, +.BR "FORK UPDATED STATUS" , +a line for each gives its path, as it would be typed from the working directory; how long it has been left alone, since a file in it last changed, or since it was made, if none has; and what is in it: .TP diff --git a/cmd/fsfork/tests/fsfork.rs b/cmd/fsfork/tests/fsfork.rs index 5243933..19af2ca 100644 --- a/cmd/fsfork/tests/fsfork.rs +++ b/cmd/fsfork/tests/fsfork.rs @@ -543,8 +543,13 @@ fn lists_the_forks_with_what_changed_in_each() { assert!(out.status.success(), "{}", stderr(&out)); assert_eq!(stderr(&out), ""); let listed = stdout(&out); + let header = listed.lines().next().unwrap(); + assert!(header.starts_with("FORK "), "{listed}"); + assert!(header.contains(" UPDATED "), "{listed}"); + assert!(header.ends_with(" STATUS"), "{listed}"); let mut lines: Vec<(&str, &str)> = listed .lines() + .skip(1) .map(|line| { let (path, rest) = line.split_once(" ").unwrap(); let state = rest.trim_start().split_once(" ").unwrap().1.trim_start(); @@ -648,7 +653,7 @@ fn lists_nothing_if_there_are_no_forks() { let dir = world.project(); let out = fsfork(&dir, &["-l"]); assert!(out.status.success(), "{}", stderr(&out)); - assert_eq!(stdout(&out), ""); + assert_eq!(stdout(&out), "FORK UPDATED STATUS\n"); assert_fails( &fsfork(&world.dir, &["-l", "missing"]), "missing: no such file", From 926d74bd3000806aeee5e3d1c7ad20aa4a716d24 Mon Sep 17 00:00:00 2001 From: Pekka Enberg Date: Tue, 3 Nov 2026 13:41:14 +0200 Subject: [PATCH 7/8] fsfork -l: Say how many files a fork has changes to that are not applied "7 files changed, 2 applied" made the reader work out what is left: that the directory lacks the changes to 5. Now the status says just that, "5 files not applied", and fsdiff --stat shows them all. A base with no fork is "base only", one that cannot be compared "unknown", and fsfork --prune keeps forks as "not applied" rather than "changed". --- README.md | 4 ++-- cmd/fsfork/forks.rs | 43 +++++++++++++++++++------------------- cmd/fsfork/fsfork.1 | 25 +++++++++++++--------- cmd/fsfork/tests/fsfork.rs | 12 +++++------ 4 files changed, 44 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index bc26186..90cf88d 100644 --- a/README.md +++ b/README.md @@ -51,8 +51,8 @@ tell which to remove: $ fsfork -l FORK UPDATED STATUS ../turso.1 4 days ago unchanged -../turso.3 1 day ago 15 files changed, 6 applied -../.turso.2.base 2 hours ago base left over, with no fork +../turso.3 1 day ago 9 files not applied +../.turso.2.base 2 hours ago base only ../turso.swebench 9 minutes ago applied ``` diff --git a/cmd/fsfork/forks.rs b/cmd/fsfork/forks.rs index deea385..0dbe0ad 100644 --- a/cmd/fsfork/forks.rs +++ b/cmd/fsfork/forks.rs @@ -25,8 +25,9 @@ enum State { Unchanged, /// Something did, and the directory has it all now. Applied, - /// `files` changed in it, of which the directory has `applied` now. - Changed { files: usize, applied: usize }, + /// Something did, and the directory does not have the changes to + /// `files` of the files. + NotApplied { files: usize }, /// The fork is gone, and its base is not. LeftOver, /// It could not be compared with its base. @@ -38,16 +39,10 @@ impl fmt::Display for State { match self { State::Unchanged => f.write_str("unchanged"), State::Applied => f.write_str("applied"), - State::Changed { files, applied } => { - let s = if *files == 1 { "" } else { "s" }; - write!(f, "{files} file{s} changed")?; - if *applied > 0 { - write!(f, ", {applied} applied")?; - } - Ok(()) - } - State::LeftOver => f.write_str("base left over, with no fork"), - State::Unknown => f.write_str("cannot be compared with its base"), + State::NotApplied { files: 1 } => f.write_str("1 file not applied"), + State::NotApplied { files } => write!(f, "{files} files not applied"), + State::LeftOver => f.write_str("base only"), + State::Unknown => f.write_str("unknown"), } } } @@ -107,7 +102,7 @@ pub fn prune(dir: &Path) -> io::Result { let mut out = io::stdout().lock(); for fork in &forks { let why = match fork.state { - State::Changed { .. } => Some(Kept::Changed), + State::NotApplied { .. } => Some(Kept::NotApplied), State::Unknown => Some(Kept::NotCompared), _ if now.duration_since(fork.touched).unwrap_or_default() < long_enough => { Some(Kept::Recent) @@ -147,7 +142,7 @@ pub fn prune(dir: &Path) -> io::Result { #[derive(Clone, Copy)] enum Kept { /// It has changes the directory does not. - Changed, + NotApplied, /// It was left alone too little. Recent, /// The working directory is in it. @@ -161,17 +156,17 @@ enum Kept { impl Kept { /// Every reason, in the order they are said. const ALL: [Kept; 5] = [ - Kept::Changed, + Kept::NotApplied, Kept::Recent, Kept::InUse, Kept::NotCompared, Kept::NotRemoved, ]; - /// What is said of those kept for this reason, as in "2 changed". + /// What is said of those kept for this reason, as in "2 not applied". fn word(self) -> &'static str { match self { - Kept::Changed => "changed", + Kept::NotApplied => "not applied", Kept::Recent => "recent", Kept::InUse => "in use", Kept::NotCompared => "not compared", @@ -251,14 +246,18 @@ fn state(repo: &git::Repo, dir: &Path, fork: &Found) -> io::Result<(State, Syste if repo.applied(&before, &after, None, dir)? { return Ok((State::Applied, touched)); } - let mut applied = 0; + let mut files = 0; for path in &changed { - if repo.applied(&before, &after, Some(path), dir)? { - applied += 1; + if !repo.applied(&before, &after, Some(path), dir)? { + files += 1; } } - let files = changed.len(); - Ok((State::Changed { files, applied }, touched)) + // Each file's changes may be there without the whole patch undoing. + let state = match files { + 0 => State::Applied, + files => State::NotApplied { files }, + }; + Ok((state, touched)) } /// When `path` in `fork` was last changed, or if it is gone, the directory diff --git a/cmd/fsfork/fsfork.1 b/cmd/fsfork/fsfork.1 index 46e9227..a83a8e0 100644 --- a/cmd/fsfork/fsfork.1 +++ b/cmd/fsfork/fsfork.1 @@ -125,17 +125,22 @@ as it would once applied there, even if .I dir changed after. .TP -.IB n " files changed" "\fR, \fPm applied" +.IB n " files not applied" +Something changed in it, and +.I dir +does not have the changes to .I n -files changed in it, of which -.IR dir , -if -.I m -is given, has the changes to -.IR m . +of the files: +.B fsdiff \-\-stat +shows them all. .TP -.B base left over, with no fork +.B base only The fork is gone, and its base is not. +.TP +.B unknown +It could not be compared with its base, as +.B fsfork +says on standard error. .PP Those left alone longest come first. Forks made elsewhere, with @@ -157,8 +162,8 @@ It keeps the others, and any the working directory is in. It says on standard output each it removed, as .BR "removed ../turso.1" , and then, on standard error, how many it kept, and why, as -.BR "fsfork: kept 2 changed, 3 recent" : -.B changed +.BR "fsfork: kept 2 not applied, 3 recent" : +.B not applied for those with changes .I dir does not have, diff --git a/cmd/fsfork/tests/fsfork.rs b/cmd/fsfork/tests/fsfork.rs index 19af2ca..2d95dd7 100644 --- a/cmd/fsfork/tests/fsfork.rs +++ b/cmd/fsfork/tests/fsfork.rs @@ -559,10 +559,10 @@ fn lists_the_forks_with_what_changed_in_each() { lines.sort(); let at = |name: &str| format!("{prefix}{name}"); let expected = [ - (at(".project.4.base"), "base left over, with no fork"), + (at(".project.4.base"), "base only"), (at("project.1"), "unchanged"), - (at("project.2"), "3 files changed"), - (at("project.3"), "2 files changed, 1 applied"), + (at("project.2"), "3 files not applied"), + (at("project.3"), "1 file not applied"), (at("project.applied"), "applied"), ]; let expected: Vec<(&str, &str)> = expected.iter().map(|(p, s)| (p.as_str(), *s)).collect(); @@ -591,7 +591,7 @@ fn a_fork_is_applied_if_the_directory_has_its_changes_even_after_more() { .to_string() }; write(&dir, "lines", &lines("2", "eight")); - assert_eq!(state(), "1 file changed"); + assert_eq!(state(), "1 file not applied"); write(&dir, "lines", &lines("two", "eight")); assert_eq!(state(), "applied"); } @@ -618,7 +618,7 @@ fn prunes_the_forks_done_with_and_keeps_the_others() { assert!(path.is_dir()); } assert_eq!(stdout(&out), ""); - assert_eq!(stderr(&out), "fsfork: kept 1 changed, 4 recent\n"); + assert_eq!(stderr(&out), "fsfork: kept 1 not applied, 4 recent\n"); let out = Command::new(env!("CARGO_BIN_EXE_fsfork")) .args(["--prune", "../project"]) @@ -638,7 +638,7 @@ fn prunes_the_forks_done_with_and_keeps_the_others() { "removed ../project.3", ], ); - assert_eq!(stderr(&out), "fsfork: kept 1 changed, 1 in use\n"); + assert_eq!(stderr(&out), "fsfork: kept 1 not applied, 1 in use\n"); assert!(!unchanged.exists() && !world.path(".project.1.base").exists()); assert!(!applied.exists() && !world.path(".project.3.base").exists()); assert!(!world.path(".project.4.base").exists()); From 932c05de87cc66958bbb969eb4a9d600d86a712d Mon Sep 17 00:00:00 2001 From: Pekka Enberg Date: Tue, 3 Nov 2026 13:42:33 +0200 Subject: [PATCH 8/8] fsfork -l: Say a fork has work only here, or is merged "5 files not applied" was patch talk, leaving the reader to work out what it means for the fork: that removing it loses the changes to those files, which only it has. Now it says so, "5 files only here", and a fork whose changes the directory has is "merged". fsfork --prune keeps forks "with work only here". --- README.md | 6 +++--- cmd/fsfork/forks.rs | 35 ++++++++++++++++++----------------- cmd/fsfork/fsfork.1 | 26 +++++++++++++------------- cmd/fsfork/fsfork.rs | 2 +- cmd/fsfork/tests/fsfork.rs | 22 ++++++++++++++-------- 5 files changed, 49 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 90cf88d..df014a4 100644 --- a/README.md +++ b/README.md @@ -51,13 +51,13 @@ tell which to remove: $ fsfork -l FORK UPDATED STATUS ../turso.1 4 days ago unchanged -../turso.3 1 day ago 9 files not applied +../turso.3 1 day ago 9 files only here ../.turso.2.base 2 hours ago base only -../turso.swebench 9 minutes ago applied +../turso.swebench 9 minutes ago merged ``` `fsfork --prune` removes those done with: the forks that are unchanged or -applied, with their bases, and the bases left over, once each has been left +merged, with their bases, and the bases left over, once each has been left alone for an hour. It says what it removed, and how many it kept, and why. Each command has a man page: [`fsfork.1`](cmd/fsfork/fsfork.1), diff --git a/cmd/fsfork/forks.rs b/cmd/fsfork/forks.rs index 0dbe0ad..f1d3020 100644 --- a/cmd/fsfork/forks.rs +++ b/cmd/fsfork/forks.rs @@ -24,10 +24,10 @@ enum State { /// Nothing changed in it. Unchanged, /// Something did, and the directory has it all now. - Applied, - /// Something did, and the directory does not have the changes to - /// `files` of the files. - NotApplied { files: usize }, + Merged, + /// Something did, and the changes to `files` of the files are only + /// in the fork: the directory does not have them. + OnlyHere { files: usize }, /// The fork is gone, and its base is not. LeftOver, /// It could not be compared with its base. @@ -38,9 +38,9 @@ impl fmt::Display for State { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { State::Unchanged => f.write_str("unchanged"), - State::Applied => f.write_str("applied"), - State::NotApplied { files: 1 } => f.write_str("1 file not applied"), - State::NotApplied { files } => write!(f, "{files} files not applied"), + State::Merged => f.write_str("merged"), + State::OnlyHere { files: 1 } => f.write_str("1 file only here"), + State::OnlyHere { files } => write!(f, "{files} files only here"), State::LeftOver => f.write_str("base only"), State::Unknown => f.write_str("unknown"), } @@ -72,7 +72,7 @@ pub fn list(dir: &Path) -> io::Result { /// How long a fork must be left alone for `prune` to remove it: one just /// made, with nothing changed in it yet, may have a command starting there, -/// and one just applied may have more to come. +/// and one just merged may have more to come. const LEFT_ALONE: Duration = Duration::from_secs(60 * 60); /// How long a fork must be left alone for `prune` to remove it: `LEFT_ALONE`, @@ -89,7 +89,7 @@ fn left_alone() -> Duration { LEFT_ALONE } -/// Removes the forks of `dir` that are unchanged or applied and were left +/// Removes the forks of `dir` that are unchanged or merged and were left /// alone long enough, and the bases left over from forks removed without /// them, saying on stdout each it removed, and on stderr how many it kept, /// and why; and returns whether all could be looked into and removed. @@ -102,7 +102,7 @@ pub fn prune(dir: &Path) -> io::Result { let mut out = io::stdout().lock(); for fork in &forks { let why = match fork.state { - State::NotApplied { .. } => Some(Kept::NotApplied), + State::OnlyHere { .. } => Some(Kept::OnlyHere), State::Unknown => Some(Kept::NotCompared), _ if now.duration_since(fork.touched).unwrap_or_default() < long_enough => { Some(Kept::Recent) @@ -142,7 +142,7 @@ pub fn prune(dir: &Path) -> io::Result { #[derive(Clone, Copy)] enum Kept { /// It has changes the directory does not. - NotApplied, + OnlyHere, /// It was left alone too little. Recent, /// The working directory is in it. @@ -156,17 +156,18 @@ enum Kept { impl Kept { /// Every reason, in the order they are said. const ALL: [Kept; 5] = [ - Kept::NotApplied, + Kept::OnlyHere, Kept::Recent, Kept::InUse, Kept::NotCompared, Kept::NotRemoved, ]; - /// What is said of those kept for this reason, as in "2 not applied". + /// What is said of those kept for this reason, as in "2 with work only + /// here". fn word(self) -> &'static str { match self { - Kept::NotApplied => "not applied", + Kept::OnlyHere => "with work only here", Kept::Recent => "recent", Kept::InUse => "in use", Kept::NotCompared => "not compared", @@ -244,7 +245,7 @@ fn state(repo: &git::Repo, dir: &Path, fork: &Found) -> io::Result<(State, Syste .filter_map(|path| modified(&fork.fork, path)) .fold(made, SystemTime::max); if repo.applied(&before, &after, None, dir)? { - return Ok((State::Applied, touched)); + return Ok((State::Merged, touched)); } let mut files = 0; for path in &changed { @@ -254,8 +255,8 @@ fn state(repo: &git::Repo, dir: &Path, fork: &Found) -> io::Result<(State, Syste } // Each file's changes may be there without the whole patch undoing. let state = match files { - 0 => State::Applied, - files => State::NotApplied { files }, + 0 => State::Merged, + files => State::OnlyHere { files }, }; Ok((state, touched)) } diff --git a/cmd/fsfork/fsfork.1 b/cmd/fsfork/fsfork.1 index a83a8e0..61027e8 100644 --- a/cmd/fsfork/fsfork.1 +++ b/cmd/fsfork/fsfork.1 @@ -114,10 +114,10 @@ Nothing changed in it, as .BR fsdiff (1) would say. .TP -.B applied +.B merged Something changed in it, and .I dir -has the changes: the patch +has the changes, so removing it loses nothing: the patch .BR fsdiff (1) shows would undo in .IR dir , @@ -125,14 +125,14 @@ as it would once applied there, even if .I dir changed after. .TP -.IB n " files not applied" -Something changed in it, and -.I dir -does not have the changes to +.IB n " files only here" +Something changed in it, and the changes to .I n -of the files: -.B fsdiff \-\-stat -shows them all. +of the files are only in the fork: +.I dir +does not have them, and removing the fork loses them. +.B fsdiff +shows them, to apply. .TP .B base only The fork is gone, and its base is not. @@ -154,16 +154,16 @@ it forks nothing, and removes the forks of that .B \-l would list as -.BR unchanged " or " applied , +.BR unchanged " or " merged , with their bases, and the bases left over, if each has been left alone for an hour: one just made may have a command starting in it, and one just -applied may have more to come. +merged may have more to come. It keeps the others, and any the working directory is in. It says on standard output each it removed, as .BR "removed ../turso.1" , and then, on standard error, how many it kept, and why, as -.BR "fsfork: kept 2 not applied, 3 recent" : -.B not applied +.BR "fsfork: kept 2 with work only here, 3 recent" : +.B with work only here for those with changes .I dir does not have, diff --git a/cmd/fsfork/fsfork.rs b/cmd/fsfork/fsfork.rs index 0796e10..80fc23c 100644 --- a/cmd/fsfork/fsfork.rs +++ b/cmd/fsfork/fsfork.rs @@ -31,7 +31,7 @@ struct Args { #[argh(switch, short = 'l')] list: bool, - /// remove the forks of the directory that are unchanged or applied, and + /// remove the forks of the directory that are unchanged or merged, and /// the bases left over from forks removed without them, rather than fork /// it #[argh(switch)] diff --git a/cmd/fsfork/tests/fsfork.rs b/cmd/fsfork/tests/fsfork.rs index 2d95dd7..2f23f2a 100644 --- a/cmd/fsfork/tests/fsfork.rs +++ b/cmd/fsfork/tests/fsfork.rs @@ -561,9 +561,9 @@ fn lists_the_forks_with_what_changed_in_each() { let expected = [ (at(".project.4.base"), "base only"), (at("project.1"), "unchanged"), - (at("project.2"), "3 files not applied"), - (at("project.3"), "1 file not applied"), - (at("project.applied"), "applied"), + (at("project.2"), "3 files only here"), + (at("project.3"), "1 file only here"), + (at("project.applied"), "merged"), ]; let expected: Vec<(&str, &str)> = expected.iter().map(|(p, s)| (p.as_str(), *s)).collect(); assert_eq!(lines, expected, "{listed}"); @@ -572,7 +572,7 @@ fn lists_the_forks_with_what_changed_in_each() { } #[test] -fn a_fork_is_applied_if_the_directory_has_its_changes_even_after_more() { +fn a_fork_is_merged_if_the_directory_has_its_changes_even_after_more() { let world = World::new(); let dir = world.project(); let lines = |second: &str, last: &str| format!("1\n{second}\n3\n4\n5\n6\n7\n{last}\n"); @@ -591,9 +591,9 @@ fn a_fork_is_applied_if_the_directory_has_its_changes_even_after_more() { .to_string() }; write(&dir, "lines", &lines("2", "eight")); - assert_eq!(state(), "1 file not applied"); + assert_eq!(state(), "1 file only here"); write(&dir, "lines", &lines("two", "eight")); - assert_eq!(state(), "applied"); + assert_eq!(state(), "merged"); } #[test] @@ -618,7 +618,10 @@ fn prunes_the_forks_done_with_and_keeps_the_others() { assert!(path.is_dir()); } assert_eq!(stdout(&out), ""); - assert_eq!(stderr(&out), "fsfork: kept 1 not applied, 4 recent\n"); + assert_eq!( + stderr(&out), + "fsfork: kept 1 with work only here, 4 recent\n" + ); let out = Command::new(env!("CARGO_BIN_EXE_fsfork")) .args(["--prune", "../project"]) @@ -638,7 +641,10 @@ fn prunes_the_forks_done_with_and_keeps_the_others() { "removed ../project.3", ], ); - assert_eq!(stderr(&out), "fsfork: kept 1 not applied, 1 in use\n"); + assert_eq!( + stderr(&out), + "fsfork: kept 1 with work only here, 1 in use\n" + ); assert!(!unchanged.exists() && !world.path(".project.1.base").exists()); assert!(!applied.exists() && !world.path(".project.3.base").exists()); assert!(!world.path(".project.4.base").exists());