diff --git a/src/worktree/mod.rs b/src/worktree/mod.rs index cad1de6..ec02b17 100644 --- a/src/worktree/mod.rs +++ b/src/worktree/mod.rs @@ -1,13 +1,13 @@ //! Multi-repo worktree management building blocks. //! -//! Provides types, store operations, git operations, helpers, and hooks +//! Provides types, meta's records of the sets it created, git operations, helpers, and hooks //! for worktree management. Command handlers live in `meta_git_cli::commands::worktree`. pub mod git_ops; pub mod helpers; pub mod hooks; +pub mod record; pub mod safety; -pub mod store; pub mod types; // Re-export commonly-used types diff --git a/src/worktree/record.rs b/src/worktree/record.rs new file mode 100644 index 0000000..738e710 --- /dev/null +++ b/src/worktree/record.rs @@ -0,0 +1,248 @@ +//! What meta records about a worktree set it created. +//! +//! There is no global list. Each linked worktree meta creates gets a record +//! in git's own admin directory for that worktree +//! (`/worktrees//meta-worktree.json`). Git ignores the +//! file and deletes it with the worktree (`git worktree remove` or `prune`). +//! Only something that can write the repository's git directory can make +//! one, so a record is meta's proof that it made the set the record names. + +use anyhow::{Context, Result}; +use meta_core::display::escape_path; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +/// The record's file name inside a worktree's admin directory. +pub const RECORD_FILE: &str = "meta-worktree.json"; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SetRecord { + /// The set directory, resolved when it was created. + pub set: PathBuf, + /// The meta directory the set was created from. + pub project: PathBuf, + pub created_at: String, + #[serde(default)] + pub ephemeral: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ttl_seconds: Option, + #[serde(default, skip_serializing_if = "HashMap::is_empty")] + pub custom: HashMap, +} + +impl SetRecord { + /// The set's name: its directory's name. + pub fn name(&self) -> String { + self.set + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default() + } + + /// Seconds until the TTL expires: `None` without a TTL, negative once + /// expired. A malformed `created_at` warns and never expires. + pub fn ttl_remaining(&self, now_epoch: i64) -> Option { + self.ttl_seconds.map(|ttl| { + let created = match chrono::DateTime::parse_from_rfc3339(&self.created_at) { + Ok(dt) => dt.timestamp(), + Err(e) => { + log::warn!( + "Malformed created_at '{}' in the record of '{}': {}", + meta_core::display::escape(&self.created_at), + escape_path(&self.set), + e + ); + return i64::MAX; + } + }; + let ttl = i64::try_from(ttl).unwrap_or(i64::MAX); + created.saturating_add(ttl).saturating_sub(now_epoch) + }) + } +} + +/// The record in a worktree's admin directory, if it has one. +pub fn read(admin: &Path) -> Result> { + let path = admin.join(RECORD_FILE); + let content = match std::fs::read_to_string(&path) { + Ok(content) => content, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e).with_context(|| format!("Cannot read {}", escape_path(&path))), + }; + serde_json::from_str(&content) + .map(Some) + .with_context(|| format!("Cannot parse {}", escape_path(&path))) +} + +/// Record `record` in a worktree's admin directory, atomically (a temp file +/// renamed into place). The directory is git's: it must exist, and it +/// carries the repository's permissions, not those of meta's data dir. +pub fn write(admin: &Path, record: &SetRecord) -> Result<()> { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let path = admin.join(RECORD_FILE); + let tmp = admin.join(format!( + "{RECORD_FILE}.tmp.{}.{}", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + )); + let json = serde_json::to_string_pretty(record)?; + let written = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp) + .and_then(|mut file| std::io::Write::write_all(&mut file, json.as_bytes())) + .and_then(|()| std::fs::rename(&tmp, &path)); + if written.is_err() { + let _ = std::fs::remove_file(&tmp); + } + written.with_context(|| format!("Cannot write {}", escape_path(&path))) +} + +/// Delete the record in a worktree's admin directory, if any. +pub fn delete(admin: &Path) -> Result<()> { + let path = admin.join(RECORD_FILE); + match std::fs::remove_file(&path) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => { + Err(e).with_context(|| format!("Cannot delete {}", escape_path(&path))) + } + _ => Ok(()), + } +} + +/// Whether the checkout of the worktree whose admin directory is `admin` +/// is gone (git calls such a worktree prunable). Anything that can't be +/// read counts as still there. +pub fn checkout_gone(admin: &Path) -> bool { + let Ok(gitdir) = std::fs::read_to_string(admin.join("gitdir")) else { + return false; + }; + matches!( + admin.join(gitdir.trim()).symlink_metadata(), + Err(e) if e.kind() == std::io::ErrorKind::NotFound + ) +} + +/// Meta's record of creating the set at `set`, from the first of its +/// worktrees `checkouts` with a trusted record naming it (see +/// [`super::safety::member_record`]). Worktrees whose record can't be used +/// are passed over: the removal check blocks on them. +pub fn find>( + set: &Path, + checkouts: impl IntoIterator, +) -> Option { + let set = set.canonicalize().ok()?; + checkouts.into_iter().find_map(|checkout| { + super::safety::member_record(checkout.as_ref()) + .ok() + .flatten() + .map(|(_, record)| record) + .filter(|record| record.set == set) + }) +} + +/// Every record in the worktree admin directories of the repository whose +/// git directory is `git_dir`, by admin directory. A record, or a +/// directory, that can't be read is there as its error: a set it would +/// have shown must not be taken as absent. +pub fn in_repo(git_dir: &Path) -> Vec<(PathBuf, Result)> { + let worktrees = git_dir.join("worktrees"); + let entries = match std::fs::read_dir(&worktrees) { + Ok(entries) => entries, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Vec::new(), + Err(e) => { + let e = + anyhow::Error::from(e).context(format!("Cannot read {}", escape_path(&worktrees))); + return vec![(worktrees, Err(e))]; + } + }; + entries + .filter_map(|entry| match entry { + Ok(entry) => { + let admin = entry.path(); + read(&admin).transpose().map(|record| (admin, record)) + } + Err(e) => Some(( + worktrees.clone(), + Err(anyhow::Error::from(e) + .context(format!("Cannot read {}", escape_path(&worktrees)))), + )), + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn record(created_at: &str, ttl_seconds: Option) -> SetRecord { + SetRecord { + set: PathBuf::from("/p/.worktrees/test-wt"), + project: PathBuf::from("/p"), + created_at: created_at.to_string(), + ephemeral: false, + ttl_seconds, + custom: HashMap::new(), + } + } + + #[test] + fn name_is_the_set_directory_name() { + assert_eq!(record("", None).name(), "test-wt"); + } + + #[test] + fn ttl_remaining() { + // 2025-01-01T00:00:00Z is epoch 1735689600 + let created = 1_735_689_600i64; + let r = record("2025-01-01T00:00:00Z", Some(3600)); + assert_eq!(r.ttl_remaining(created + 1800), Some(1800)); + assert_eq!(r.ttl_remaining(created + 3600), Some(0)); + assert_eq!(r.ttl_remaining(created + 7200), Some(-3600)); + assert_eq!(record("2025-01-01T00:00:00Z", None).ttl_remaining(0), None); + let huge = record("2025-01-01T00:00:00Z", Some(u64::MAX)); + assert_eq!( + huge.ttl_remaining(1_800_000_000), + Some(i64::MAX - 1_800_000_000) + ); + let malformed = record("not-a-date", Some(3600)); + assert_eq!(malformed.ttl_remaining(1_700_000_000), Some(i64::MAX)); + } + + #[test] + fn write_read_delete_round_trip() { + let temp = tempfile::tempdir().unwrap(); + let admin = temp.path().join("worktrees/wt"); + std::fs::create_dir_all(&admin).unwrap(); + assert_eq!(read(&admin).unwrap(), None); + + let mut r = record("2025-01-01T00:00:00Z", Some(60)); + r.custom.insert("k".into(), "v".into()); + write(&admin, &r).unwrap(); + assert_eq!(read(&admin).unwrap(), Some(r.clone())); + let found = in_repo(temp.path()); + assert_eq!(found.len(), 1); + assert_eq!(found[0].0, admin); + assert_eq!(found[0].1.as_ref().unwrap(), &r); + + delete(&admin).unwrap(); + delete(&admin).unwrap(); + assert_eq!(read(&admin).unwrap(), None); + assert!(in_repo(temp.path()).is_empty()); + } + + #[test] + fn write_needs_the_admin_dir_to_exist() { + let temp = tempfile::tempdir().unwrap(); + let admin = temp.path().join("gone"); + assert!(write(&admin, &record("", None)).is_err()); + assert!(!admin.exists()); + } + + #[test] + fn a_malformed_record_is_an_error() { + let temp = tempfile::tempdir().unwrap(); + std::fs::write(temp.path().join(RECORD_FILE), "not json").unwrap(); + assert!(read(temp.path()).is_err()); + } +} diff --git a/src/worktree/safety.rs b/src/worktree/safety.rs index 0f1c577..876f44c 100644 --- a/src/worktree/safety.rs +++ b/src/worktree/safety.rs @@ -8,13 +8,16 @@ use meta_core::display::{escape, escape_path}; use std::path::{Path, PathBuf}; use super::git_ops::{git_command, remove_worktree_repos}; +use super::record::{self, SetRecord}; -/// A linked worktree checkout inside a set, and the git directory of the -/// repository it belongs to (where `git worktree remove` runs). +/// A linked worktree checkout inside a set, the git directory of the +/// repository it belongs to (where `git worktree remove` runs), and meta's +/// record of creating it, if it has one. #[derive(Debug, Clone, PartialEq)] pub struct Member { pub path: PathBuf, pub repo_git_dir: PathBuf, + pub record: Option, } /// What deleting a worktree set would destroy. @@ -22,13 +25,18 @@ pub struct Member { pub struct RemovalCheck { /// Every linked worktree in the set, nested and hidden ones included. pub members: Vec, - /// Repositories that aren't linked worktrees, and checkouts git can't - /// inspect. No flag overrides these. + /// Repositories that aren't linked worktrees, checkouts git can't + /// inspect, and worktrees meta recorded for another set. No flag + /// overrides these. pub blockers: Vec, /// Work that deleting the set would lose. `--force` may discard it. pub unsaved: Vec, /// Files outside every repository (part of `unsaved`). pub loose: Vec, + /// Records that can't be used (part of `blockers`). They block removal + /// as a proof of ownership; a create rolling back the set it just + /// claimed needs no such proof. + pub unusable_records: Vec, /// Each checkout's complete git status, stranded commit ids, and the size /// and modification time of every file `unsaved` lists, so a re-check /// sees changes the abbreviated lines would hide, rewrites included. @@ -39,6 +47,13 @@ impl RemovalCheck { pub fn is_clear(&self) -> bool { self.blockers.is_empty() && self.unsaved.is_empty() } + + /// Meta's record of creating the set, if a worktree in it has one. A + /// record naming another set is a blocker, so without blockers every + /// record found names this set. + pub fn record(&self) -> Option<&SetRecord> { + self.members.iter().find_map(|m| m.record.as_ref()) + } } /// Inspect a worktree set before deleting it. @@ -48,7 +63,9 @@ impl RemovalCheck { /// worktree of its repository) and on checkouts git cannot inspect. Reports /// as unsaved: uncommitted or untracked changes, commits that no branch, tag /// or remote ref holds, and files that no repository holds. Ignored files count as disposable, as -/// they do for `git worktree remove`. +/// they do for `git worktree remove`. Blocks on a worktree whose record +/// (see [`record`]) names another set, such as a set nested in this one, or +/// whose record can't be read. pub fn check_worktree_removal(wt_dir: &Path) -> Result { let mut check = RemovalCheck::default(); if wt_dir.symlink_metadata().is_ok_and(|m| m.is_symlink()) { @@ -58,12 +75,12 @@ pub fn check_worktree_removal(wt_dir: &Path) -> Result { )); return Ok(check); } + let set = wt_dir + .canonicalize() + .with_context(|| format!("Cannot resolve {}", escape_path(wt_dir)))?; let root_owned = match git_entry(wt_dir)? { - GitEntry::Worktree(repo_git_dir) => { - check.members.push(Member { - path: wt_dir.to_path_buf(), - repo_git_dir, - }); + GitEntry::Worktree(dirs) => { + add_member(&mut check, &set, wt_dir, dirs); true } GitEntry::Repository(why) => { @@ -75,12 +92,26 @@ pub fn check_worktree_removal(wt_dir: &Path) -> Result { GitEntry::None => false, }; let mut loose = Vec::new(); - scan(wt_dir, root_owned, &mut loose, &mut check)?; + scan(&set, wt_dir, root_owned, &mut loose, &mut check)?; // A stable order, so two checks of an unchanged set compare equal. check.members.sort_by(|a, b| a.path.cmp(&b.path)); check.blockers.sort(); loose.sort(); + // Another set's records are blockers already + let mut records = check + .members + .iter() + .filter_map(|m| m.record.as_ref().filter(|r| r.set == set)); + if let Some(first) = records.next() { + if records.any(|r| r != first) { + check.blockers.push(format!( + "{}: its worktrees hold different records of meta creating it", + escape_path(wt_dir) + )); + } + } + let paths: Vec = check.members.iter().map(|m| m.path.clone()).collect(); for member in &paths { let label = relative_label(wt_dir, member); @@ -127,9 +158,10 @@ fn file_fingerprint(path: &Path) -> String { /// Delete a set that [`check_worktree_removal`] inspected, and nothing else. /// /// Checks the set again first and refuses if anything changed since `check` -/// (prune checks many sets before deleting any). Then unregisters the checked -/// worktrees (stopping at the first failure), deletes the files outside every -/// repository only if `force`, and removes the directories left empty. +/// (prune checks many sets before deleting any). Then deletes the files +/// outside every repository only if `force`, unregisters the checked +/// worktrees (stopping at the first failure), and removes the directories +/// left empty. /// Anything outside the checked worktrees that is still there is reported /// and left in place. meta doesn't lock out other processes, so a write into /// the set during the deletion itself can still be lost. @@ -145,12 +177,14 @@ pub fn delete_checked_set( escape_path(wt_dir) ); } - remove_worktree_repos(&check.members, force, verbose)?; + // Loose files first: git deletes each worktree's record with it, so a + // set that fails here is still meta's to remove on a retry. if force { for path in &check.loose { remove_entry(path).with_context(|| format!("Cannot delete {}", escape_path(path)))?; } } + remove_worktree_repos(&check.members, force, verbose)?; remove_empty_dirs(wt_dir)?; if wt_dir.symlink_metadata().is_ok() { let left: Vec = std::fs::read_dir(wt_dir) @@ -195,9 +229,94 @@ fn remove_empty_dirs(dir: &Path) -> Result<()> { Ok(()) } +/// Add the linked worktree at `path`, with its admin directory and its +/// repository's git directory, to the members of the set resolved to `set`. +fn add_member( + check: &mut RemovalCheck, + set: &Path, + path: &Path, + (admin, repo_git_dir): (PathBuf, PathBuf), +) { + let record = match trusted_record(&admin, &repo_git_dir) { + Ok(record) => record, + Err(e) => { + let why = format!( + "{}: meta's record of it can't be used ({e:#})", + escape_path(path) + ); + check.unusable_records.push(why.clone()); + check.blockers.push(why); + None + } + }; + if let Some(other) = record.as_ref().filter(|r| r.set != set) { + check + .blockers + .push(if other.set.symlink_metadata().is_ok() { + format!( + "{}: meta created it for another worktree set, {}; remove that one first", + escape_path(path), + escape_path(&other.set) + ) + } else { + format!( + "{}: meta created it for a worktree set at {}, which is gone; was the set moved?", + escape_path(path), + escape_path(&other.set) + ) + }); + } + // git refuses to remove a locked worktree, which would stop a removal + // halfway + if admin.join("locked").symlink_metadata().is_ok() { + check.blockers.push(format!( + "{}: git has it locked; run 'git worktree unlock' on it first", + escape_path(path) + )); + } + check.members.push(Member { + path: path.to_path_buf(), + repo_git_dir, + record, + }); +} + +/// Meta's record of the linked worktree checked out at `checkout`, with its +/// admin directory: `None` if it isn't a linked worktree or has no record, +/// an error if it has a record that can't be trusted. +pub fn member_record(checkout: &Path) -> Result> { + let Ok((admin, repo_git_dir)) = linked_worktree_dirs(checkout) else { + return Ok(None); + }; + Ok(trusted_record(&admin, &repo_git_dir)?.map(|record| (admin, record))) +} + +/// The record in `admin`, the admin directory of a worktree of the +/// repository whose git directory is `repo_git_dir`. Git keeps every +/// worktree's admin directory in its repository's `worktrees` directory; a +/// record anywhere else is no proof of anything, and an error. +fn trusted_record(admin: &Path, repo_git_dir: &Path) -> Result> { + let Some(record) = record::read(admin)? else { + return Ok(None); + }; + let registered = || -> Option { + Some( + admin.canonicalize().ok()?.parent()? + == repo_git_dir.join("worktrees").canonicalize().ok()?, + ) + }; + anyhow::ensure!( + registered() == Some(true), + "its git metadata {} is not where git keeps a worktree's", + escape_path(admin) + ); + Ok(Some(record)) +} + enum GitEntry { - /// A linked worktree, with its repository's git directory. - Worktree(PathBuf), + /// A linked worktree, with its admin directory and its repository's git + /// directory. + Worktree((PathBuf, PathBuf)), /// A repository of its own, or a checkout meta can't attribute to one. Repository(String), None, @@ -206,8 +325,8 @@ enum GitEntry { fn git_entry(dir: &Path) -> Result { let git = dir.join(".git"); match git.symlink_metadata() { - Ok(meta) if meta.is_file() => Ok(match linked_worktree_git_dir(dir) { - Ok(repo_git_dir) => GitEntry::Worktree(repo_git_dir), + Ok(meta) if meta.is_file() => Ok(match linked_worktree_dirs(dir) { + Ok(dirs) => GitEntry::Worktree(dirs), Err(e) => GitEntry::Repository(format!("not a linked worktree ({e:#})")), }), Ok(_) => Ok(GitEntry::Repository( @@ -227,11 +346,17 @@ fn git_entry(dir: &Path) -> Result { } } -/// Follow a checkout's `.git` file to its repository's git directory, -/// requiring the linked-worktree layout: an admin directory with a -/// `commondir` and a `gitdir` that points back at this checkout. A -/// `--separate-git-dir` checkout or a submodule fails this. -fn linked_worktree_git_dir(checkout: &Path) -> Result { +/// The admin directory of the linked worktree checked out at `checkout`, in +/// its repository's git directory (see [`linked_worktree_dirs`]). +pub fn linked_worktree_admin_dir(checkout: &Path) -> Result { + linked_worktree_dirs(checkout).map(|(admin, _)| admin) +} + +/// Follow a checkout's `.git` file to its admin directory and its +/// repository's git directory, requiring the linked-worktree layout: an +/// admin directory with a `commondir` and a `gitdir` that points back at +/// this checkout. A `--separate-git-dir` checkout or a submodule fails this. +fn linked_worktree_dirs(checkout: &Path) -> Result<(PathBuf, PathBuf)> { let git_file = checkout.join(".git"); let content = std::fs::read_to_string(&git_file).context("cannot read .git")?; let admin = content @@ -267,12 +392,19 @@ fn linked_worktree_git_dir(checkout: &Path) -> Result { 'git worktree repair' in its repository)", escape_path(&admin) ); - Ok(admin.join(common.trim())) + let common = admin.join(common.trim()); + Ok((admin, common)) } /// Walk the set without following links. `owned` means a repository above /// `dir` accounts for its files. -fn scan(dir: &Path, owned: bool, loose: &mut Vec, check: &mut RemovalCheck) -> Result<()> { +fn scan( + set: &Path, + dir: &Path, + owned: bool, + loose: &mut Vec, + check: &mut RemovalCheck, +) -> Result<()> { let entries = std::fs::read_dir(dir).with_context(|| format!("Cannot read {}", escape_path(dir)))?; for entry in entries { @@ -294,14 +426,11 @@ fn scan(dir: &Path, owned: bool, loose: &mut Vec, check: &mut RemovalCh GitEntry::Repository(why) => check .blockers .push(format!("{}: {why}", escape_path(&path))), - GitEntry::Worktree(repo_git_dir) => { - check.members.push(Member { - path: path.clone(), - repo_git_dir, - }); - scan(&path, true, loose, check)?; + GitEntry::Worktree(dirs) => { + add_member(check, set, &path, dirs); + scan(set, &path, true, loose, check)?; } - GitEntry::None => scan(&path, owned, loose, check)?, + GitEntry::None => scan(set, &path, owned, loose, check)?, } } Ok(()) @@ -582,6 +711,145 @@ mod tests { ); } + fn set_record(set: &Path) -> SetRecord { + SetRecord { + set: set.canonicalize().unwrap(), + project: set.to_path_buf(), + created_at: "2026-01-01T00:00:00Z".to_string(), + ephemeral: false, + ttl_seconds: None, + custom: Default::default(), + } + } + + fn mark(checkout: &Path, record: &SetRecord) { + record::write(&linked_worktree_admin_dir(checkout).unwrap(), record).unwrap(); + } + + #[test] + fn records_name_their_set_and_block_any_other() { + let tmp = tempfile::tempdir().unwrap(); + let set = tmp.path().join("set"); + repo_with_worktree(tmp.path(), "root", &set); + repo_with_worktree(tmp.path(), "leaf", &set.join("leaf")); + // A worktree git made by hand carries no record + let check = check_worktree_removal(&set).unwrap(); + assert!(check.is_clear() && check.record().is_none(), "{check:?}"); + + let record = set_record(&set); + mark(&set, &record); + let check = check_worktree_removal(&set).unwrap(); + assert!(check.is_clear(), "{check:?}"); + assert_eq!(check.record(), Some(&record)); + + // A set nested in this one is another set's + let inner = set.join("inner"); + repo_with_worktree(tmp.path(), "inner", &inner); + mark(&inner, &set_record(&inner)); + let check = check_worktree_removal(&set).unwrap(); + assert_eq!(check.blockers.len(), 1, "{check:?}"); + assert!( + check.blockers[0].contains("another worktree set"), + "{check:?}" + ); + // and the inner set is clear on its own + assert!(check_worktree_removal(&inner).unwrap().is_clear()); + } + + #[test] + fn records_that_differ_or_sit_outside_git_layout_block() { + let tmp = tempfile::tempdir().unwrap(); + let set = tmp.path().join("set"); + repo_with_worktree(tmp.path(), "root", &set); + repo_with_worktree(tmp.path(), "leaf", &set.join("leaf")); + let record = set_record(&set); + mark(&set, &record); + let mut later = record.clone(); + later.ttl_seconds = Some(0); + mark(&set.join("leaf"), &later); + let check = check_worktree_removal(&set).unwrap(); + assert!( + check + .blockers + .iter() + .any(|b| b.contains("different records")), + "{check:?}" + ); + + // A checkout pointing at a copied admin directory with a record in + // it: the backlink holds, but git doesn't keep it there + let fake = tmp.path().join("fake"); + repo_with_worktree(tmp.path(), "real", &fake.join("real")); + let admin = linked_worktree_admin_dir(&fake.join("real")).unwrap(); + let copy = fake.join("admin"); + std::fs::create_dir(©).unwrap(); + for file in ["HEAD", "commondir", "gitdir"] { + std::fs::copy(admin.join(file), copy.join(file)).unwrap(); + } + let common = std::fs::read_to_string(admin.join("commondir")).unwrap(); + std::fs::write( + copy.join("commondir"), + admin.join(common.trim()).to_str().unwrap(), + ) + .unwrap(); + std::fs::write( + fake.join("real/.git"), + format!("gitdir: {}", copy.display()), + ) + .unwrap(); + mark(&fake.join("real"), &set_record(&fake)); + let check = check_worktree_removal(&fake).unwrap(); + assert!(check.record().is_none(), "{check:?}"); + assert!( + check + .blockers + .iter() + .any(|b| b.contains("not where git keeps")), + "{check:?}" + ); + // nor does `add` find it to copy into the worktrees it adds + assert!(member_record(&fake.join("real")).is_err()); + assert_eq!(record::find(&fake, [fake.join("real")]), None); + } + + #[cfg(unix)] + #[test] + fn a_record_is_trusted_when_the_worktrees_dir_is_a_link() { + let tmp = tempfile::tempdir().unwrap(); + let source = tmp.path().join("root"); + std::fs::create_dir_all(&source).unwrap(); + git(&source, &["init", "-q"]); + git(&source, &["commit", "-q", "--allow-empty", "-m", "init"]); + std::fs::create_dir(source.join(".git/real-worktrees")).unwrap(); + std::os::unix::fs::symlink("real-worktrees", source.join(".git/worktrees")).unwrap(); + let set = tmp.path().join("set"); + git( + &source, + &["worktree", "add", "-q", "-b", "s", set.to_str().unwrap()], + ); + let record = set_record(&set); + mark(&set, &record); + let check = check_worktree_removal(&set).unwrap(); + assert!(check.is_clear(), "{check:?}"); + assert_eq!(check.record(), Some(&record)); + } + + #[test] + fn a_locked_worktree_blocks() { + let tmp = tempfile::tempdir().unwrap(); + let set = tmp.path().join("set"); + repo_with_worktree(tmp.path(), "root", &set); + git( + &tmp.path().join("root"), + &["worktree", "lock", set.to_str().unwrap()], + ); + let check = check_worktree_removal(&set).unwrap(); + assert!( + check.blockers.iter().any(|b| b.contains("locked")), + "{check:?}" + ); + } + #[test] fn reports_dirty_nested_repo_loose_files_and_primary_checkouts() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/worktree/store.rs b/src/worktree/store.rs deleted file mode 100644 index 7033231..0000000 --- a/src/worktree/store.rs +++ /dev/null @@ -1,604 +0,0 @@ -//! Centralized worktree store operations. -//! -//! Manages `~/.meta/worktree.json` — the persistent record of all worktrees. - -use anyhow::Result; -use meta_core::display::escape_path; -use std::path::{Path, PathBuf}; - -use super::types::{StoreRepoEntry, WorktreeStoreData, WorktreeStoreEntry}; - -/// Derive the store key from a worktree path. -/// -/// Attempts to canonicalize the path to resolve symlinks and normalize -/// path components. This prevents collisions when the same physical -/// directory is referenced via different paths (symlinks, relative paths, etc.). -/// -/// If canonicalization fails (e.g., path doesn't exist yet), falls back -/// to using the path as-is to maintain backward compatibility. -fn store_key(worktree_path: &Path) -> String { - match worktree_path.canonicalize() { - Ok(canonical) => canonical.to_string_lossy().into_owned(), - Err(e) => { - log::debug!( - "Failed to canonicalize path '{}': {}. Using original path.", - escape_path(worktree_path), - e - ); - worktree_path.to_string_lossy().into_owned() - } - } -} - -fn store_path() -> Result { - meta_core::data_dir::data_file("worktree") -} - -fn store_lock_path(data_path: &Path) -> PathBuf { - data_path.with_extension("lock") -} - -/// Return (data_path, lock_path) for the worktree store. -fn store_paths() -> Result<(PathBuf, PathBuf)> { - let data_path = store_path()?; - let lock_path = store_lock_path(&data_path); - Ok((data_path, lock_path)) -} - -/// Whether the store file does not exist, so there is nothing to remove. -/// Any other error (an unreadable data dir, say) is left to the update, -/// which reports it, instead of being taken as an empty store. -fn store_missing(data_path: &Path) -> bool { - matches!( - std::fs::symlink_metadata(data_path), - Err(e) if e.kind() == std::io::ErrorKind::NotFound - ) -} - -/// Add a worktree entry to the centralized store. -pub fn store_add(worktree_path: &Path, entry: WorktreeStoreEntry) -> Result<()> { - meta_core::data_dir::ensure_meta_dir()?; - let (data_path, lock_path) = store_paths()?; - let key = store_key(worktree_path); - - meta_core::store::update::(&data_path, &lock_path, |store| { - store.worktrees.insert(key, entry); - }) -} - -/// Get all entries from the store. -pub fn store_list() -> Result { - meta_core::store::read(&store_path()?) -} - -/// Get the store key and entry for an existing worktree path, if meta -/// recorded creating it. Keep the key: once the path is deleted it can no -/// longer be resolved to the same key. -pub fn store_get(worktree_path: &Path) -> Result> { - let key = store_key(worktree_path); - Ok(store_list()? - .worktrees - .remove(&key) - .map(|entry| (key, entry))) -} - -/// Recorded worktree sets inside `worktree_path`, not counting itself. -/// Deleting `worktree_path` would delete those sets too. -pub fn store_sets_inside(worktree_path: &Path) -> Result> { - let key = store_key(worktree_path); - let root = Path::new(&key); - Ok(store_list()? - .worktrees - .into_keys() - .filter(|k| Path::new(k) != root && Path::new(k).starts_with(root)) - .collect()) -} - -/// Add repos to an existing worktree entry in the store. -pub fn store_extend_repos(worktree_path: &Path, repos: Vec) -> Result<()> { - let (data_path, lock_path) = store_paths()?; - let key = store_key(worktree_path); - - meta_core::store::update::(&data_path, &lock_path, move |store| { - if let Some(entry) = store.worktrees.get_mut(&key) { - entry.repos.extend(repos); - } - }) -} - -/// Remove multiple worktree entries from the store in a single lock cycle. -/// Each `(key, created_at)` pair removes the entry only if it is still the -/// one that was read, so a worktree recreated at the same path keeps its record. -pub fn store_remove_batch(entries: &[(String, String)]) -> Result<()> { - let (data_path, lock_path) = store_paths()?; - if store_missing(&data_path) { - return Ok(()); - } - - meta_core::store::update::(&data_path, &lock_path, |store| { - for (key, created_at) in entries { - if store - .worktrees - .get(key) - .is_some_and(|e| e.created_at == *created_at) - { - store.worktrees.remove(key); - } - } - }) -} - -/// Compute TTL remaining seconds for a store entry. -/// Returns `None` if no TTL is set. Negative means expired. -/// On malformed `created_at`, warns and treats as not expired. -pub fn entry_ttl_remaining(entry: &WorktreeStoreEntry, now_epoch: i64) -> Option { - entry.ttl_seconds.map(|ttl| { - let created = match chrono::DateTime::parse_from_rfc3339(&entry.created_at) { - Ok(dt) => dt.timestamp(), - Err(e) => { - log::warn!( - "Malformed created_at '{}' in store entry '{}': {}", - meta_core::display::escape(&entry.created_at), - meta_core::display::escape(&entry.name), - e - ); - return i64::MAX; - } - }; - let ttl = i64::try_from(ttl).unwrap_or(i64::MAX); - created.saturating_add(ttl).saturating_sub(now_epoch) - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::collections::HashMap; - - fn make_entry(created_at: &str, ttl_seconds: Option) -> WorktreeStoreEntry { - WorktreeStoreEntry { - name: "test-wt".to_string(), - project: "/tmp/project".to_string(), - created_at: created_at.to_string(), - ephemeral: ttl_seconds.is_some(), - ttl_seconds, - repos: vec![], - custom: HashMap::new(), - } - } - - // ── store_key ─────────────────────────────────────────── - - #[test] - fn store_key_returns_path_string() { - let path = std::path::Path::new("/home/user/.worktrees/feat-1"); - // Note: For non-existent paths, store_key falls back to original path - assert_eq!(store_key(path), "/home/user/.worktrees/feat-1"); - } - - #[test] - fn store_key_canonicalizes_existing_paths() { - // Create a temp directory to test canonicalization - let temp_dir = tempfile::tempdir().unwrap(); - let temp_path = temp_dir.path(); - - // Canonicalize the temp dir to get the absolute, resolved path - let canonical = temp_path.canonicalize().unwrap(); - - // store_key should return the canonical path - assert_eq!( - store_key(temp_path), - canonical.to_string_lossy().to_string() - ); - } - - #[test] - #[cfg(unix)] - fn store_key_resolves_symlinks() { - use std::os::unix::fs::symlink; - - let temp_dir = tempfile::tempdir().unwrap(); - let real_dir = temp_dir.path().join("real"); - let symlink_path = temp_dir.path().join("link"); - - std::fs::create_dir(&real_dir).unwrap(); - symlink(&real_dir, &symlink_path).unwrap(); - - // Both paths should resolve to the same canonical key - let key_real = store_key(&real_dir); - let key_symlink = store_key(&symlink_path); - - assert_eq!( - key_real, key_symlink, - "Symlink and real path should produce the same store key" - ); - } - - #[test] - fn store_key_handles_nonexistent_paths() { - // For non-existent paths, should fall back to original path - let path = std::path::Path::new("/nonexistent/path/to/worktree"); - assert_eq!(store_key(path), "/nonexistent/path/to/worktree"); - } - - #[test] - fn store_key_normalizes_relative_components() { - let temp_dir = tempfile::tempdir().unwrap(); - let real_path = temp_dir.path(); - - // Create a subdirectory so the path exists - let subdir = real_path.join("subdir"); - std::fs::create_dir(&subdir).unwrap(); - - // Create a path with .. components that resolves back to real_path - let path_with_dots = subdir.join("..").join("."); - - // Both should resolve to the same canonical path - let key_clean = store_key(real_path); - let key_with_dots = store_key(&path_with_dots); - - assert_eq!( - key_clean, key_with_dots, - "Paths with . and .. should normalize to same key" - ); - } - - // ── entry_ttl_remaining ───────────────────────────────── - - #[test] - fn ttl_remaining_none_when_no_ttl() { - let entry = make_entry("2025-01-01T00:00:00Z", None); - assert!(entry_ttl_remaining(&entry, 1_700_000_000).is_none()); - } - - #[test] - fn ttl_remaining_positive_when_not_expired() { - // created_at = 2025-01-01T00:00:00Z = epoch 1735689600 - // ttl = 3600s (1 hour) - // now = 1735689600 + 1800 (30 min later) - // remaining = 1735689600 + 3600 - (1735689600 + 1800) = 1800 - let entry = make_entry("2025-01-01T00:00:00Z", Some(3600)); - let created_epoch = 1_735_689_600i64; - let remaining = entry_ttl_remaining(&entry, created_epoch + 1800).unwrap(); - assert_eq!(remaining, 1800); - } - - #[test] - fn ttl_remaining_negative_when_expired() { - // created + ttl < now → negative - let entry = make_entry("2025-01-01T00:00:00Z", Some(3600)); - let created_epoch = 1_735_689_600i64; - let remaining = entry_ttl_remaining(&entry, created_epoch + 7200).unwrap(); - assert_eq!(remaining, -3600); - } - - #[test] - fn ttl_remaining_zero_at_exact_expiry() { - let entry = make_entry("2025-01-01T00:00:00Z", Some(3600)); - let created_epoch = 1_735_689_600i64; - let remaining = entry_ttl_remaining(&entry, created_epoch + 3600).unwrap(); - assert_eq!(remaining, 0); - } - - #[test] - fn ttl_remaining_huge_ttl_never_expires() { - let entry = make_entry("2025-01-01T00:00:00Z", Some(u64::MAX)); - let remaining = entry_ttl_remaining(&entry, 1_800_000_000).unwrap(); - assert_eq!(remaining, i64::MAX - 1_800_000_000); - } - - #[test] - fn ttl_remaining_malformed_date_returns_max() { - let entry = make_entry("not-a-date", Some(3600)); - let remaining = entry_ttl_remaining(&entry, 1_700_000_000).unwrap(); - assert_eq!(remaining, i64::MAX); - } - - // ── Concurrent store access (file locking) ───────────── - // Note: These tests use #[serial] because META_DATA_DIR is process-global. - // Each test isolates its store via a unique temp directory. - - #[test] - #[serial_test::serial] - fn store_add_and_remove_sequential() { - let temp_dir = tempfile::tempdir().unwrap(); - // Isolate store to temp dir - let store_dir = temp_dir.path().join("meta-store"); - std::fs::create_dir_all(&store_dir).unwrap(); - std::env::set_var("META_DATA_DIR", &store_dir); - - let wt_path = temp_dir.path().join("test-wt"); - std::fs::create_dir(&wt_path).unwrap(); - - // Add entry - let entry = make_entry("2025-01-01T00:00:00Z", None); - store_add(&wt_path, entry.clone()).unwrap(); - - // Verify it was added - let data = store_list().unwrap(); - let key = store_key(&wt_path); - assert!(data.worktrees.contains_key(&key)); - - // Remove entry - store_remove_batch(&[(key.clone(), "2025-01-01T00:00:00Z".to_string())]).unwrap(); - - // Verify it was removed - let data = store_list().unwrap(); - assert!(!data.worktrees.contains_key(&key)); - - std::env::remove_var("META_DATA_DIR"); - } - - #[test] - #[serial_test::serial] - fn store_remove_batch_removes_multiple() { - let temp_dir = tempfile::tempdir().unwrap(); - // Isolate store to temp dir - let store_dir = temp_dir.path().join("meta-store"); - std::fs::create_dir_all(&store_dir).unwrap(); - std::env::set_var("META_DATA_DIR", &store_dir); - - let wt1 = temp_dir.path().join("wt1"); - let wt2 = temp_dir.path().join("wt2"); - let wt3 = temp_dir.path().join("wt3"); - - std::fs::create_dir(&wt1).unwrap(); - std::fs::create_dir(&wt2).unwrap(); - std::fs::create_dir(&wt3).unwrap(); - - // Add three entries - store_add(&wt1, make_entry("2025-01-01T00:00:00Z", None)).unwrap(); - store_add(&wt2, make_entry("2025-01-01T00:00:00Z", None)).unwrap(); - store_add(&wt3, make_entry("2025-01-01T00:00:00Z", None)).unwrap(); - - // Remove two in batch - let keys_to_remove = vec![ - (store_key(&wt1), "2025-01-01T00:00:00Z".to_string()), - (store_key(&wt2), "2025-01-01T00:00:00Z".to_string()), - ]; - store_remove_batch(&keys_to_remove).unwrap(); - - // An entry recreated since it was read keeps its record - store_add(&wt3, make_entry("2026-01-01T00:00:00Z", None)).unwrap(); - store_remove_batch(&[(store_key(&wt3), "2025-01-01T00:00:00Z".to_string())]).unwrap(); - - // Verify only wt3 remains - let data = store_list().unwrap(); - assert!(!data.worktrees.contains_key(&store_key(&wt1))); - assert!(!data.worktrees.contains_key(&store_key(&wt2))); - assert!(data.worktrees.contains_key(&store_key(&wt3))); - - // Cleanup - store_remove_batch(&[(store_key(&wt3), "2026-01-01T00:00:00Z".to_string())]).unwrap(); - std::env::remove_var("META_DATA_DIR"); - } - - #[test] - #[serial_test::serial] - fn store_extend_repos_adds_to_existing_entry() { - let temp_dir = tempfile::tempdir().unwrap(); - // Isolate store to temp dir - let store_dir = temp_dir.path().join("meta-store"); - std::fs::create_dir_all(&store_dir).unwrap(); - std::env::set_var("META_DATA_DIR", &store_dir); - - let wt_path = temp_dir.path().join("extend-wt"); - std::fs::create_dir(&wt_path).unwrap(); - - // Canonicalize the path immediately after creating it to ensure consistency - let wt_path = wt_path.canonicalize().unwrap(); - - // Add entry with one repo - let mut entry = make_entry("2025-01-01T00:00:00Z", None); - entry.repos = vec![StoreRepoEntry { - alias: "repo1".to_string(), - branch: "main".to_string(), - created_branch: false, - }]; - store_add(&wt_path, entry).unwrap(); - - // Extend with another repo - let new_repos = vec![StoreRepoEntry { - alias: "repo2".to_string(), - branch: "main".to_string(), - created_branch: false, - }]; - store_extend_repos(&wt_path, new_repos).unwrap(); - - // Verify both repos are present - let data = store_list().unwrap(); - let key = store_key(&wt_path); - let stored_entry = data.worktrees.get(&key).unwrap(); - assert_eq!(stored_entry.repos.len(), 2); - assert!(stored_entry.repos.iter().any(|r| r.alias == "repo1")); - assert!(stored_entry.repos.iter().any(|r| r.alias == "repo2")); - - // Cleanup - store_remove_batch(&[(store_key(&wt_path), "2025-01-01T00:00:00Z".to_string())]).unwrap(); - std::env::remove_var("META_DATA_DIR"); - } - - #[test] - #[serial_test::serial] - fn store_operations_handle_nonexistent_store_gracefully() { - let temp_dir = tempfile::tempdir().unwrap(); - // Isolate store to temp dir - but don't create worktree.json - let store_dir = temp_dir.path().join("meta-store"); - std::fs::create_dir_all(&store_dir).unwrap(); - std::env::set_var("META_DATA_DIR", &store_dir); - - // List should return empty, not error (store file doesn't exist yet) - let data = store_list().unwrap(); - assert!(data.worktrees.is_empty()); - - // Remove on non-existent worktree should succeed - let wt_path = temp_dir.path().join("nonexistent-wt"); - assert!( - store_remove_batch(&[(store_key(&wt_path), "2025-01-01T00:00:00Z".to_string())]) - .is_ok() - ); - - std::env::remove_var("META_DATA_DIR"); - } - - #[test] - #[serial_test::serial] - fn concurrent_store_adds_do_not_conflict() { - use std::sync::Arc; - use std::thread; - - let temp_dir = Arc::new(tempfile::tempdir().unwrap()); - // Isolate store to temp dir to avoid conflicts with parallel nextest processes - let store_dir = temp_dir.path().join("meta-store"); - std::fs::create_dir_all(&store_dir).unwrap(); - std::env::set_var("META_DATA_DIR", &store_dir); - - // Spawn multiple threads that add worktrees concurrently - let handles: Vec<_> = (0..5) - .map(|i| { - let temp_dir = Arc::clone(&temp_dir); - thread::spawn(move || { - let wt_path = temp_dir.path().join(format!("concurrent-add-{i}")); - std::fs::create_dir(&wt_path).unwrap(); - let mut entry = make_entry("2025-01-01T00:00:00Z", None); - entry.name = format!("concurrent-add-{i}"); - store_add(&wt_path, entry).unwrap(); - wt_path - }) - }) - .collect(); - - // Wait for all threads - let paths: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect(); - - // Verify all 5 entries were added (check each specific one exists) - let data = store_list().unwrap(); - for path in &paths { - let key = store_key(path); - assert!( - data.worktrees.contains_key(&key), - "Concurrent add failed: {key} not found in store" - ); - } - - // Cleanup - batch remove for efficiency - let keys: Vec = paths.iter().map(|p| store_key(p)).collect(); - let entries: Vec<_> = keys - .iter() - .map(|k| (k.clone(), "2025-01-01T00:00:00Z".to_string())) - .collect(); - store_remove_batch(&entries).unwrap(); - - // Verify cleanup worked - let data_after = store_list().unwrap(); - for key in &keys { - assert!( - !data_after.worktrees.contains_key(key), - "Cleanup failed: {key} still in store" - ); - } - std::env::remove_var("META_DATA_DIR"); - } - - #[test] - #[serial_test::serial] - fn concurrent_batch_removes_handle_overlapping_keys() { - use std::sync::Arc; - use std::thread; - - let temp_dir = Arc::new(tempfile::tempdir().unwrap()); - // Isolate store to temp dir to avoid conflicts with parallel nextest processes - let store_dir = temp_dir.path().join("meta-store"); - std::fs::create_dir_all(&store_dir).unwrap(); - std::env::set_var("META_DATA_DIR", &store_dir); - - // Add 10 worktrees - let paths: Vec<_> = (0..10) - .map(|i| { - let wt_path = temp_dir.path().join(format!("batch-rm-{i}")); - std::fs::create_dir(&wt_path).unwrap(); - let mut entry = make_entry("2025-01-01T00:00:00Z", None); - entry.name = format!("batch-rm-{i}"); - store_add(&wt_path, entry).unwrap(); - wt_path - }) - .collect(); - - let keys_before: Vec = paths.iter().map(|p| store_key(p)).collect(); - - // Spawn threads that remove overlapping batches - let handles: Vec<_> = (0..3) - .map(|batch_id| { - let paths = paths.clone(); - thread::spawn(move || { - // Each thread removes a different subset - let start = batch_id * 3; - let end = std::cmp::min(start + 4, paths.len()); - let keys: Vec = - paths[start..end].iter().map(|p| store_key(p)).collect(); - let entries: Vec<_> = keys - .into_iter() - .map(|k| (k, "2025-01-01T00:00:00Z".to_string())) - .collect(); - store_remove_batch(&entries).unwrap(); - }) - }) - .collect(); - - // Wait for all threads - for handle in handles { - handle.join().unwrap(); - } - - // All entries should be removed (with possible duplicates in batches) - let data = store_list().unwrap(); - for key in &keys_before { - assert!( - !data.worktrees.contains_key(key), - "Key {key} should be removed" - ); - } - std::env::remove_var("META_DATA_DIR"); - } - - #[test] - #[serial_test::serial] - fn store_handles_corrupted_data_file() { - // Isolate store to temp dir to avoid conflicts with parallel nextest processes - let temp_dir = tempfile::tempdir().unwrap(); - let store_dir = temp_dir.path().join("meta-store"); - std::fs::create_dir_all(&store_dir).unwrap(); - std::env::set_var("META_DATA_DIR", &store_dir); - - let store = store_path().unwrap(); - - // Clean up by ensuring a fresh empty store - meta_core::data_dir::ensure_meta_dir().unwrap(); - std::fs::write(&store, b"{\"worktrees\":{}}").unwrap(); - - // Write invalid JSON - meta_core::data_dir::ensure_meta_dir().unwrap(); - std::fs::write(&store, b"not valid json").unwrap(); - - // store_list should handle corruption gracefully - // (either returns error or returns default empty store) - let result = store_list(); - - // Accept either behavior: error or default empty store - match result { - Ok(data) => { - // If it returns a default, it should be empty - assert!( - data.worktrees.is_empty(), - "Corrupted store should return empty data" - ); - } - Err(_) => { - // Error is also acceptable - } - } - - std::env::remove_var("META_DATA_DIR"); - // temp_dir cleanup is automatic on drop - } -} diff --git a/src/worktree/types.rs b/src/worktree/types.rs index 93908d0..02df6f7 100644 --- a/src/worktree/types.rs +++ b/src/worktree/types.rs @@ -1,6 +1,6 @@ //! Types for worktree management. -use serde::{Deserialize, Serialize}; +use serde::Serialize; use std::collections::HashMap; use std::path::PathBuf; @@ -39,16 +39,6 @@ impl std::str::FromStr for RepoSpec { } } -impl From<&CreateRepoEntry> for StoreRepoEntry { - fn from(r: &CreateRepoEntry) -> Self { - StoreRepoEntry { - alias: r.alias.clone(), - branch: r.branch.clone(), - created_branch: r.created_branch, - } - } -} - // ==================== Internal Types ==================== /// Resolved worktree context for operations that need meta_dir, worktree_root, and worktree path. @@ -58,36 +48,6 @@ pub struct WorktreeContext { pub wt_dir: PathBuf, } -// ==================== Centralized Store Types ==================== - -/// Top-level store structure at `~/.meta/worktree.json`. -#[derive(Debug, Default, Serialize, Deserialize)] -pub struct WorktreeStoreData { - pub worktrees: HashMap, -} - -/// Individual worktree entry in the centralized store. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct WorktreeStoreEntry { - pub name: String, - pub project: String, - pub created_at: String, - pub ephemeral: bool, - #[serde(skip_serializing_if = "Option::is_none")] - pub ttl_seconds: Option, - pub repos: Vec, - #[serde(default, skip_serializing_if = "HashMap::is_empty")] - pub custom: HashMap, -} - -/// Repo entry within a store entry. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct StoreRepoEntry { - pub alias: String, - pub branch: String, - pub created_branch: bool, -} - // ==================== JSON Output Structures ==================== #[derive(Debug, Serialize)] @@ -293,32 +253,4 @@ mod tests { let spec: RepoSpec = input.parse().unwrap(); assert_eq!(spec.to_string(), input); } - - // ── StoreRepoEntry From ──────────────── - - #[test] - fn store_entry_from_create_entry() { - let create = CreateRepoEntry { - alias: "lib".to_string(), - path: "/tmp/lib".to_string(), - branch: "main".to_string(), - created_branch: true, - }; - let store: StoreRepoEntry = StoreRepoEntry::from(&create); - assert_eq!(store.alias, "lib"); - assert_eq!(store.branch, "main"); - assert!(store.created_branch); - } - - #[test] - fn store_entry_from_create_entry_no_created_branch() { - let create = CreateRepoEntry { - alias: "app".to_string(), - path: "/tmp/app".to_string(), - branch: "develop".to_string(), - created_branch: false, - }; - let store: StoreRepoEntry = StoreRepoEntry::from(&create); - assert!(!store.created_branch); - } }