diff --git a/README.md b/README.md index 99aabb6..df014a4 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,21 @@ 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 +FORK UPDATED STATUS +../turso.1 4 days ago unchanged +../turso.3 1 day ago 9 files only here +../.turso.2.base 2 hours ago base only +../turso.swebench 9 minutes ago merged +``` + +`fsfork --prune` removes those done with: the forks that are unchanged or +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), [`confine.1`](cmd/confine/confine.1), and [`fsdiff.1`](cmd/fsdiff/fsdiff.1) 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/cmd/fsfork/forks.rs b/cmd/fsfork/forks.rs new file mode 100644 index 0000000..f1d3020 --- /dev/null +++ b/cmd/fsfork/forks.rs @@ -0,0 +1,338 @@ +//! 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; and as `fsfork --prune` removes those done with. + +use std::{ + env, 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. + 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. + Unknown, +} + +impl fmt::Display for State { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + State::Unchanged => f.write_str("unchanged"), + 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"), + } + } +} + +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`, 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 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) +} + +/// 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 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`, +/// 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 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. +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 kept = [0; Kept::ALL.len()]; + let mut out = io::stdout().lock(); + for fork in &forks { + let why = match fork.state { + State::OnlyHere { .. } => Some(Kept::OnlyHere), + 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) + } + }, + }; + 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(", "))); + } + Ok(all) +} + +/// Why `prune` kept a fork. +#[derive(Clone, Copy)] +enum Kept { + /// It has changes the directory does not. + OnlyHere, + /// 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::OnlyHere, + Kept::Recent, + Kept::InUse, + Kept::NotCompared, + Kept::NotRemoved, + ]; + + /// What is said of those kept for this reason, as in "2 with work only + /// here". + fn word(self) -> &'static str { + match self { + Kept::OnlyHere => "with work only here", + 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 { + 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)> { + 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::Merged, touched)); + } + let mut files = 0; + for path in &changed { + if !repo.applied(&before, &after, Some(path), dir)? { + files += 1; + } + } + // Each file's changes may be there without the whole patch undoing. + let state = match files { + 0 => State::Merged, + files => State::OnlyHere { files }, + }; + 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()) +} + +/// 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, and +/// three spaces apart. +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 732f7c4..61027e8 100644 --- a/cmd/fsfork/fsfork.1 +++ b/cmd/fsfork/fsfork.1 @@ -9,6 +9,12 @@ fsfork \- fork a directory: make a copy-on-write clone of it .IR name ] .RI [ dir .RI [ fork ]] +.br +.B fsfork \-l +.RI [ dir ] +.br +.B fsfork \-\-prune +.RI [ dir ] .SH DESCRIPTION .B fsfork makes a copy-on-write clone of @@ -86,12 +92,90 @@ 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. +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 +.B unchanged +Nothing changed in it, as +.BR fsdiff (1) +would say. +.TP +.B merged +Something changed in it, and +.I dir +has the changes, so removing it loses nothing: 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 only here" +Something changed in it, and the changes to +.I n +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. +.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 +.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 " 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 +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 with work only here, 3 recent" : +.B with work only here +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 +would remove: it asks nothing. +.PP .B fsfork goes by .I .gitignore @@ -121,6 +205,16 @@ 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 \-\-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. @@ -132,6 +226,12 @@ 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; 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 @@ -172,11 +272,17 @@ and remove one: .PP .RS .nf -.B ls \-d turso.* +.B fsfork \-l turso .B rm \-rf turso.1 .turso.1.base .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 63bfe67..80fc23c 100644 --- a/cmd/fsfork/fsfork.rs +++ b/cmd/fsfork/fsfork.rs @@ -1,6 +1,10 @@ //! `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, and with `--prune`, removes those done +//! with. + +mod forks; use std::{ env, @@ -14,13 +18,25 @@ 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]\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. #[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, + + /// 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)] + prune: bool, + /// print where the fork is, rather than start a shell there #[argh(switch)] print: bool, @@ -46,6 +62,9 @@ fn main() -> ExitCode { Ok(args) => args, Err(code) => return code, }; + 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 // it reads from there as commands. @@ -72,6 +91,41 @@ fn main() -> ExitCode { } } +/// 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(format!("{option} cannot be given with --no-ignore")) + } else if args.name.is_some() { + Some(format!("{option} cannot be given with -n")) + } else if args.paths.len() > 1 { + Some("too many arguments".to_string()) + } 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); + let done = if args.list { + forks::list(dir) + } else { + forks::prune(dir) + }; + match done { + 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/tests/fsfork.rs b/cmd/fsfork/tests/fsfork.rs index 4f7f45c..2f23f2a 100644 --- a/cmd/fsfork/tests/fsfork.rs +++ b/cmd/fsfork/tests/fsfork.rs @@ -508,6 +508,185 @@ 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 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(); + (path, state) + }) + .collect(); + lines.sort(); + let at = |name: &str| format!("{prefix}{name}"); + let expected = [ + (at(".project.4.base"), "base only"), + (at("project.1"), "unchanged"), + (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}"); + assert!(listed.contains("just now"), "{listed}"); + } +} + +#[test] +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"); + 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 only here"); + write(&dir, "lines", &lines("two", "eight")); + assert_eq!(state(), "merged"); +} + +#[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_eq!(stdout(&out), ""); + 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"]) + .current_dir(&working) + .env("FSFORK_TEST_LEFT_ALONE", "0") + .output() + .unwrap(); + assert!(out.status.success(), "{}", stderr(&out)); + let listed = stdout(&out); + let mut removed: Vec<&str> = listed.lines().collect(); + removed.sort(); + assert_eq!( + removed, + [ + "removed ../.project.4.base", + "removed ../project.1", + "removed ../project.3", + ], + ); + 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()); + 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(); + let dir = world.project(); + let out = fsfork(&dir, &["-l"]); + assert!(out.status.success(), "{}", stderr(&out)); + assert_eq!(stdout(&out), "FORK UPDATED STATUS\n"); + assert_fails( + &fsfork(&world.dir, &["-l", "missing"]), + "missing: no such file", + ); +} + +#[test] +fn lists_and_prunes_but_forks_nothing_and_take_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"], + &["--prune", "--print"], + &["--prune", "-n", "x"], + &["--prune", ".", "../x"], + &["-l", "--prune"], + ] { + 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 +875,9 @@ 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 \ + fsfork --prune [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 748d01d..af4cd37 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; @@ -20,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; @@ -90,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/cmd/fsdiff/git.rs b/fsfork/git.rs similarity index 64% rename from cmd/fsdiff/git.rs rename to fsfork/git.rs index 4cc73d0..985dda7 100644 --- a/cmd/fsdiff/git.rs +++ b/fsfork/git.rs @@ -1,22 +1,24 @@ -//! 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, - os::unix::process::CommandExt, + env, + ffi::OsStr, + fs, io, + os::unix::{ffi::OsStrExt, process::CommandExt}, path::{Path, PathBuf}, 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 +32,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 +43,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, @@ -100,6 +102,62 @@ 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()) + } + + /// 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 { @@ -160,7 +218,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 {