1use std::path::{Path, PathBuf};
12use std::time::Duration;
13
14use crate::config::wtconfig::WtMeta;
15use crate::config::{self, Config, wtconfig};
16use crate::copy::{CopyOutcome, copy_ignored_files};
17use crate::cx::Env;
18use crate::error::{Error, Result};
19use crate::git::cli::GitCli;
20use crate::git::discover::Repo;
21use crate::git::submodule::seed::SeedReport;
22use crate::git::{branch_ref, default_branch, is_ancestor, ops, resolve_hex};
23use crate::hooks::{HookContext, HookRunner};
24use crate::model::Worktree;
25use crate::query::{self, Resolved};
26use crate::slug::slugify_with_fallback;
27use crate::template::{self, TemplateVars};
28use crate::worktree::{materialize, rows};
29
30const LOCK_TIMEOUT: Duration = Duration::from_secs(10);
33
34pub struct RepoLock {
48 _marker: gix_lock::Marker,
49}
50
51fn lock_dir(root: &Path) -> PathBuf {
55 let dot_git = root.join(".git");
56 if dot_git.is_dir() {
57 dot_git
58 } else {
59 root.to_path_buf()
60 }
61}
62
63fn ensure_schema_supported_now(root: &Path) -> Result<()> {
71 wtconfig::ensure_schema_supported(Repo::discover(root)?.gix())
72}
73
74pub(crate) fn acquire_repo_lock(root: &Path, timeout: Duration) -> Result<RepoLock> {
85 let resource = lock_dir(root).join("wt-mutation");
86 let marker = gix_lock::Marker::acquire_to_hold_resource(
87 &resource,
88 gix_lock::acquire::Fail::AfterDurationWithBackoff(timeout),
89 None,
90 )
91 .map_err(|e| Error::LockUnavailable {
92 path: format!("{}.lock", resource.display()),
93 reason: e.to_string(),
94 })?;
95 let lock = RepoLock { _marker: marker };
96 ensure_schema_supported_now(root)?;
97 Ok(lock)
98}
99
100#[cfg(feature = "cli")]
105pub(crate) fn lock_repo(root: &Path) -> Result<RepoLock> {
106 acquire_repo_lock(root, LOCK_TIMEOUT)
107}
108
109pub struct Workspace {
112 repo: Repo,
113 primary_root: PathBuf,
114 config: Config,
115 env: Env,
116}
117
118pub(crate) struct WorkspaceParts<'a> {
122 pub(crate) repo: &'a Repo,
124 pub(crate) config: &'a Config,
126 pub(crate) root: &'a Path,
128 pub(crate) env: &'a Env,
130}
131
132impl Workspace {
133 pub fn discover(dir: &Path, env: &Env, git: &dyn GitCli) -> Result<Workspace> {
137 let repo = Repo::discover(dir)?;
138 let workdir = repo.current_workdir().unwrap_or_else(|| repo.git_dir());
139 let common = git.run(
142 &workdir,
143 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
144 )?;
145 let common = PathBuf::from(common.trim());
146 let primary_root = if repo.is_bare() {
147 common
148 } else {
149 common.parent().map(Path::to_path_buf).unwrap_or(common)
150 };
151 let config = config::load(Some(&primary_root), env)?;
152 wtconfig::ensure_schema_supported(repo.gix())?;
155 Ok(Workspace {
156 repo,
157 primary_root,
158 config,
159 env: env.clone(),
160 })
161 }
162
163 pub fn lock(&self) -> Result<RepoLock> {
171 acquire_repo_lock(&self.primary_root, LOCK_TIMEOUT)
172 }
173
174 pub fn root(&self) -> &Path {
177 &self.primary_root
178 }
179
180 pub fn config(&self) -> &Config {
183 &self.config
184 }
185
186 pub fn is_bare(&self) -> bool {
188 self.repo.is_bare()
189 }
190
191 pub fn enumerate(&self, git: &dyn GitCli) -> Result<Vec<Worktree>> {
194 rows::enumerate_worktrees(&self.fresh_repo()?, git)
195 }
196
197 pub fn list(&self, git: &dyn GitCli) -> Result<Vec<Worktree>> {
201 rows::build_worktrees(&self.fresh_repo()?, git)
202 }
203
204 pub fn read_meta(&self, branch: &str) -> Result<WtMeta> {
206 Ok(wtconfig::read_meta(self.fresh_repo()?.gix(), branch))
207 }
208
209 pub fn write_meta(&self, git: &dyn GitCli, branch: &str, update: &MetaUpdate) -> Result<()> {
221 let _lock = self.lock()?;
222 apply_meta(git, &self.primary_root, branch, update)
223 }
224
225 pub fn clear_meta(&self, git: &dyn GitCli, branch: &str) -> Result<()> {
228 let _lock = self.lock()?;
229 wtconfig::clear_meta(git, &self.primary_root, branch)
230 }
231
232 pub fn create(
238 &self,
239 git: &dyn GitCli,
240 hooks: &dyn HookRunner,
241 options: &CreateOptions,
242 ) -> Result<CreatedWorktree> {
243 let repo = self.fresh_repo()?;
244 create_in(&self.parts(&repo), git, hooks, options)
245 }
246
247 pub fn remove(
252 &self,
253 git: &dyn GitCli,
254 hooks: &dyn HookRunner,
255 worktree: &Worktree,
256 options: &RemoveOptions,
257 ) -> Result<RemovedWorktree> {
258 let repo = self.fresh_repo()?;
259 remove_in(&self.parts(&repo), git, hooks, worktree, options)
260 }
261
262 fn fresh_repo(&self) -> Result<Repo> {
268 let dir = self
269 .repo
270 .current_workdir()
271 .unwrap_or_else(|| self.repo.git_dir());
272 Repo::discover(&dir)
273 }
274
275 fn parts<'a>(&'a self, repo: &'a Repo) -> WorkspaceParts<'a> {
277 WorkspaceParts {
278 repo,
279 config: &self.config,
280 root: &self.primary_root,
281 env: &self.env,
282 }
283 }
284
285 #[cfg_attr(not(feature = "cli"), allow(dead_code))]
287 pub(crate) fn into_session_parts(self) -> (Repo, PathBuf, Config) {
288 (self.repo, self.primary_root, self.config)
289 }
290}
291
292#[derive(Debug, Clone, Default, PartialEq, Eq)]
296pub struct MetaUpdate {
297 pub base_ref: Option<String>,
299 pub pr_number: Option<u64>,
301 pub pr_state: Option<String>,
303 pub pr_title: Option<String>,
305 pub pr_url: Option<String>,
307 pub issue_number: Option<u64>,
309 pub issue_title: Option<String>,
311 pub issue_url: Option<String>,
313 pub issue_brief: Option<String>,
315 pub created_by_wt: bool,
319}
320
321pub(crate) fn apply_meta(
324 git: &dyn GitCli,
325 root: &Path,
326 branch: &str,
327 update: &MetaUpdate,
328) -> Result<()> {
329 if let Some(base_ref) = &update.base_ref {
330 wtconfig::write_base_ref(git, root, branch, base_ref)?;
331 }
332 if let Some(number) = update.pr_number {
333 wtconfig::write_pr_number(git, root, branch, number)?;
334 }
335 if let Some(state) = &update.pr_state {
336 wtconfig::write_pr_state(git, root, branch, state)?;
337 }
338 if let Some(title) = &update.pr_title {
339 wtconfig::write_pr_title(git, root, branch, title)?;
340 }
341 if let Some(url) = &update.pr_url {
342 wtconfig::write_pr_url(git, root, branch, url)?;
343 }
344 if let Some(number) = update.issue_number {
345 wtconfig::write_issue_number(git, root, branch, number)?;
346 }
347 if let Some(title) = &update.issue_title {
348 wtconfig::write_issue_title(git, root, branch, title)?;
349 }
350 if let Some(url) = &update.issue_url {
351 wtconfig::write_issue_url(git, root, branch, url)?;
352 }
353 if let Some(brief) = &update.issue_brief {
354 wtconfig::write_issue_brief(git, root, branch, brief)?;
355 }
356 if update.created_by_wt {
357 wtconfig::mark_created_by_wt(git, root, branch)?;
358 }
359 Ok(())
360}
361
362#[derive(Debug, Clone, Default)]
364pub struct CreateOptions {
365 pub branch: String,
367 pub base: Option<String>,
371 pub track: Option<String>,
373 pub copy_from: Option<String>,
376 pub init_submodules: bool,
380 pub seed_submodules: bool,
386 pub reflink: bool,
391 pub no_hooks: bool,
393}
394
395#[derive(Debug, Clone, Copy, Default)]
399pub struct RemoveOptions {
400 pub force_remove: bool,
403 pub force_branch: bool,
405 pub keep_branch: bool,
407 pub no_hooks: bool,
409}
410
411#[derive(Debug, Clone, PartialEq, Eq)]
413pub enum HookOutcome {
414 Skipped,
417 Succeeded,
419 ExitedNonZero(i32),
421 Failed(String),
423}
424
425#[derive(Debug, Clone, PartialEq, Eq)]
427pub enum SubmodulesOutcome {
428 Skipped,
430 Initialized(usize),
432 Failed {
435 pending: usize,
437 error: String,
439 },
440}
441
442#[derive(Debug, Clone, Default, PartialEq, Eq)]
450#[non_exhaustive]
451pub struct SubmoduleSeeding {
452 pub seeded: Vec<String>,
454 pub skipped: Vec<String>,
456 pub failed: Vec<(String, String)>,
459}
460
461impl From<SeedReport> for SubmoduleSeeding {
462 fn from(report: SeedReport) -> Self {
463 Self {
464 seeded: report.seeded,
465 skipped: report.skipped,
466 failed: report.failed,
467 }
468 }
469}
470
471#[derive(Debug, Clone)]
473#[non_exhaustive]
474pub struct CreatedWorktree {
475 pub path: PathBuf,
477 pub branch: String,
479 pub base_ref: Option<String>,
482 pub reused: bool,
485 pub copy: CopyOutcome,
487 pub post_create: HookOutcome,
489 pub submodules: SubmodulesOutcome,
491 pub submodule_seeding: SubmoduleSeeding,
493 pub reflinked: bool,
497}
498
499#[derive(Debug, Clone)]
501#[non_exhaustive]
502pub struct RemovedWorktree {
503 pub branch_deleted: bool,
505 pub forced_past_guards: bool,
509 pub forced_for_submodules: bool,
515 pub pre_remove: HookOutcome,
519}
520
521pub(crate) fn resolve_base(repo: &Repo, config: &Config, explicit: Option<&str>) -> (String, bool) {
526 if let Some(explicit) = explicit {
527 return (explicit.to_string(), false);
528 }
529 if let Some(base) = &config.default_base {
530 return (base.clone(), false);
531 }
532 if let Some(branch) = default_branch(repo.gix()) {
533 return (branch, false);
534 }
535 ("HEAD".to_string(), true)
536}
537
538#[cfg(feature = "cli")]
545pub(crate) fn preview_target(
546 ws: &WorkspaceParts<'_>,
547 branch: &str,
548 base: Option<&str>,
549) -> Result<std::path::PathBuf> {
550 let (slug, _) = target_slug(ws, branch, base)?;
551 render_target(ws.config, ws.root, branch, &slug, ws.env)
552}
553
554fn target_slug(
561 ws: &WorkspaceParts<'_>,
562 branch: &str,
563 base: Option<&str>,
564) -> Result<(String, String)> {
565 let commit = match resolve_hex(ws.repo.gix(), &branch_ref(branch)) {
566 Some(oid) => oid,
567 None => {
568 let base_ref = resolve_base(ws.repo, ws.config, base).0;
569 resolve_hex(ws.repo.gix(), &base_ref)
570 .ok_or_else(|| Error::operation(format!("base ref {base_ref:?} not found")))?
571 }
572 };
573 let short_hash = commit.get(..7).unwrap_or(&commit).to_string();
574 let slug = slugify_with_fallback(branch, &short_hash);
575 Ok((slug, short_hash))
576}
577
578pub(crate) fn create_in(
580 ws: &WorkspaceParts<'_>,
581 git: &dyn GitCli,
582 hooks: &dyn HookRunner,
583 options: &CreateOptions,
584) -> Result<CreatedWorktree> {
585 wtconfig::ensure_schema_supported(ws.repo.gix())?;
590 let branch = options.branch.clone();
591 let worktrees = rows::enumerate_worktrees(ws.repo, git)?;
592 let branch_exists = resolve_hex(ws.repo.gix(), &branch_ref(&branch)).is_some();
593
594 let base_ref = if branch_exists {
595 None
596 } else {
597 Some(resolve_base(ws.repo, ws.config, options.base.as_deref()).0)
598 };
599 let (slug, short_hash) = target_slug(ws, &branch, options.base.as_deref())?;
603
604 if let Some(existing) = worktrees
607 .iter()
608 .find(|w| w.branch.as_deref() == Some(branch.as_str()))
609 {
610 let preview = render_target(ws.config, ws.root, &branch, &slug, ws.env)?;
611 if same_path(&existing.path, &preview) {
612 return Ok(CreatedWorktree {
613 path: existing.path.clone(),
614 branch,
615 base_ref: None,
616 reused: true,
617 copy: CopyOutcome::default(),
618 post_create: HookOutcome::Skipped,
619 submodules: SubmodulesOutcome::Skipped,
620 submodule_seeding: SubmoduleSeeding::default(),
621 reflinked: false,
622 });
623 }
624 return Err(Error::operation(format!(
625 "branch {branch:?} is already checked out at {}",
626 existing.path.display()
627 )));
628 }
629
630 let lock = acquire_repo_lock(ws.root, LOCK_TIMEOUT)?;
635 let target = resolve_target(
636 ws.config,
637 ws.root,
638 &branch,
639 &slug,
640 &short_hash,
641 ws.env,
642 ws.repo.is_bare(),
643 )?;
644 if let Some(parent) = target.parent() {
645 std::fs::create_dir_all(parent)?;
646 }
647
648 let reflink_plan = if options.reflink {
653 let source = copy_source(ws, &worktrees, options.copy_from.as_deref()).ok();
654 target
655 .parent()
656 .and_then(|parent| materialize::plan(source.as_deref(), parent))
657 } else {
658 None
659 };
660 let no_checkout = reflink_plan.is_some();
661
662 let target_str = target.to_string_lossy().into_owned();
664 if let Some(base) = &base_ref {
665 ops::worktree_add_branch(git, ws.root, &branch, &target_str, base, true, no_checkout)?;
668 } else {
669 ops::worktree_add(git, ws.root, &target_str, &branch, no_checkout)?;
670 }
671
672 let reflinked = match &reflink_plan {
676 Some(plan) => match materialize::apply(git, &target, plan) {
677 Ok(used_cow) => used_cow,
678 Err(e) => {
679 rollback_worktree(git, ws.root, &target, &branch, base_ref.is_some(), false);
680 return Err(e);
681 }
682 },
683 None => false,
684 };
685
686 let copy = match post_create_steps(ws, git, &worktrees, &branch, &base_ref, &target, options) {
688 Ok(outcome) => outcome,
689 Err(e) => {
690 let created = base_ref.is_some();
693 rollback_worktree(git, ws.root, &target, &branch, created, created);
694 return Err(e);
695 }
696 };
697 drop(lock);
698
699 let ctx = HookContext {
701 worktree_path: target.clone(),
702 branch: branch.clone(),
703 repo_root: ws.root.to_path_buf(),
704 base_ref: base_ref.clone(),
705 pr_number: None,
706 };
707 let post_create = match (options.no_hooks, ws.config.hooks_post_create.as_deref()) {
708 (true, _) | (false, None) => HookOutcome::Skipped,
709 (false, Some(command)) => match hooks.run(command, &ctx) {
710 Ok(0) => HookOutcome::Succeeded,
711 Ok(code) => HookOutcome::ExitedNonZero(code),
712 Err(e) => HookOutcome::Failed(e.to_string()),
713 },
714 };
715
716 let attached = match reflinked.then(|| common_git_dir(git, ws.root)) {
722 Some(Ok(common)) => materialize::attach_submodules(git, &target, &common),
723 _ => Vec::new(),
724 };
725 if !attached.is_empty() {
726 tracing::debug!(count = attached.len(), "attached copied submodules");
727 }
728
729 let attach_sync = if attached.is_empty() {
736 Ok(())
737 } else {
738 crate::git::submodule::sync(git, &target)
739 };
740
741 let (submodules, seed) = match attach_sync {
744 Err(e) => (
745 SubmodulesOutcome::Failed {
746 pending: attached.len(),
747 error: e.to_string(),
748 },
749 SeedReport::default(),
750 ),
751 Ok(()) if options.init_submodules => {
752 populate_submodules(git, &target, options.seed_submodules)?
753 }
754 Ok(()) => (SubmodulesOutcome::Skipped, SeedReport::default()),
755 };
756
757 Ok(CreatedWorktree {
758 path: target,
759 branch,
760 base_ref,
761 reused: false,
762 copy,
763 post_create,
764 submodules,
765 submodule_seeding: seed.into(),
766 reflinked,
767 })
768}
769
770fn common_git_dir(git: &dyn GitCli, root: &Path) -> Result<PathBuf> {
773 let out = git.run(
774 root,
775 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
776 )?;
777 Ok(PathBuf::from(out.trim()))
778}
779
780fn populate_submodules(
784 git: &dyn GitCli,
785 target: &Path,
786 seed_enabled: bool,
787) -> Result<(SubmodulesOutcome, SeedReport)> {
788 let pending = crate::git::submodule::uninitialized(git, target)?;
789 if pending.is_empty() {
790 return Ok((SubmodulesOutcome::Skipped, SeedReport::default()));
791 }
792 let (seed, result) = crate::git::submodule::populate(git, target, seed_enabled);
793 let outcome = match result {
794 Ok(()) => SubmodulesOutcome::Initialized(pending.len()),
795 Err(e) => SubmodulesOutcome::Failed {
796 pending: pending.len(),
797 error: e.to_string(),
798 },
799 };
800 Ok((outcome, seed))
801}
802
803fn post_create_steps(
806 ws: &WorkspaceParts<'_>,
807 git: &dyn GitCli,
808 worktrees: &[Worktree],
809 branch: &str,
810 base_ref: &Option<String>,
811 target: &Path,
812 options: &CreateOptions,
813) -> Result<CopyOutcome> {
814 if let Some(base) = base_ref {
815 apply_meta(
819 git,
820 ws.root,
821 branch,
822 &MetaUpdate {
823 base_ref: Some(base.clone()),
824 created_by_wt: true,
825 ..MetaUpdate::default()
826 },
827 )?;
828 }
829 if let Some(upstream) = &options.track {
832 ops::set_upstream(git, ws.root, branch, upstream)?;
833 }
834 let source = copy_source(ws, worktrees, options.copy_from.as_deref())?;
835 copy_ignored_files(git, &source, target, &ws.config.copy)
836}
837
838fn copy_source(
841 ws: &WorkspaceParts<'_>,
842 worktrees: &[Worktree],
843 copy_from: Option<&str>,
844) -> Result<PathBuf> {
845 if let Some(q) = copy_from {
846 return match query::resolve(worktrees, q) {
847 Resolved::One(index) => Ok(worktrees[index].path.clone()),
848 Resolved::Ambiguous(_) => {
849 Err(Error::operation(format!("--copy-from {q:?} is ambiguous")))
850 }
851 Resolved::NotFound => Err(Error::NotFound {
852 query: q.to_string(),
853 }),
854 };
855 }
856 Ok(ws
857 .repo
858 .current_workdir()
859 .unwrap_or_else(|| ws.root.to_path_buf()))
860}
861
862pub(crate) fn remove_in(
864 ws: &WorkspaceParts<'_>,
865 git: &dyn GitCli,
866 hooks: &dyn HookRunner,
867 worktree: &Worktree,
868 options: &RemoveOptions,
869) -> Result<RemovedWorktree> {
870 wtconfig::ensure_schema_supported(ws.repo.gix())?;
876 if worktree.is_main {
877 return Err(Error::operation("refusing to remove the primary worktree"));
878 }
879 let meta = worktree
880 .branch
881 .as_deref()
882 .map(|b| wtconfig::read_meta(ws.repo.gix(), b))
883 .unwrap_or_default();
884 let default = default_branch(ws.repo.gix());
885
886 if worktree.is_missing {
888 let _lock = acquire_repo_lock(ws.root, LOCK_TIMEOUT)?;
889 ops::worktree_prune(git, ws.root)?;
890 let branch_deleted = maybe_delete_branch(ws, git, worktree, &meta, options, &default);
891 clear_metadata(git, ws.root, worktree);
892 return Ok(RemovedWorktree {
893 branch_deleted,
894 forced_past_guards: false,
895 forced_for_submodules: false,
896 pre_remove: HookOutcome::Skipped,
897 });
898 }
899
900 let needs_submodule_force =
904 crate::git::submodule::any_initialized(git, &worktree.path).unwrap_or(false);
905
906 let untracked_blocks = ws.config.remove_untracked_blocks || needs_submodule_force;
913 let guard = rows::guard_status(worktree, untracked_blocks);
914 if guard.blocks() && !options.force_remove {
915 return Err(Error::RemoveGuarded {
916 dirty: guard.dirty,
917 unpushed: guard.unpushed,
918 });
919 }
920 let forced_past_guards = guard.blocks() && options.force_remove;
921 let forced_for_submodules = needs_submodule_force && !options.force_remove;
924
925 let ctx = HookContext {
928 worktree_path: worktree.path.clone(),
929 branch: worktree.branch.clone().unwrap_or_default(),
930 repo_root: ws.root.to_path_buf(),
931 base_ref: meta.base_ref.clone(),
932 pr_number: meta.pr_number,
933 };
934 let pre_remove = match (options.no_hooks, ws.config.hooks_pre_remove.as_deref()) {
935 (true, _) | (false, None) => HookOutcome::Skipped,
936 (false, Some(command)) => match hooks.run(command, &ctx) {
937 Ok(0) => HookOutcome::Succeeded,
938 Ok(code) if options.force_remove => HookOutcome::ExitedNonZero(code),
939 Ok(code) => {
940 return Err(Error::operation(format!(
941 "pre_remove hook exited with status {code}; aborting (use --force to override)"
942 )));
943 }
944 Err(e) if options.force_remove => HookOutcome::Failed(e.to_string()),
945 Err(e) => return Err(e),
946 },
947 };
948
949 let _lock = acquire_repo_lock(ws.root, LOCK_TIMEOUT)?;
952 let path = worktree.path.to_string_lossy().into_owned();
953
954 ops::worktree_remove(
957 git,
958 ws.root,
959 &path,
960 options.force_remove || needs_submodule_force,
961 )?;
962
963 let branch_deleted = maybe_delete_branch(ws, git, worktree, &meta, options, &default);
964 clear_metadata(git, ws.root, worktree);
965 Ok(RemovedWorktree {
966 branch_deleted,
967 forced_past_guards,
968 forced_for_submodules,
969 pre_remove,
970 })
971}
972
973fn maybe_delete_branch(
977 ws: &WorkspaceParts<'_>,
978 git: &dyn GitCli,
979 worktree: &Worktree,
980 meta: &WtMeta,
981 options: &RemoveOptions,
982 default: &Option<String>,
983) -> bool {
984 let Some(branch) = &worktree.branch else {
985 return false;
986 };
987 if options.keep_branch || !meta.created_by_wt {
988 return false;
989 }
990 let base = meta.base_ref.clone().or_else(|| default.clone());
991 let merged = base
992 .as_deref()
993 .is_some_and(|b| is_ancestor(ws.repo.gix(), &branch_ref(branch), b));
994 let should_delete = if merged {
995 ws.config.remove_delete_merged_branch
996 } else {
997 options.force_branch
998 };
999 if !should_delete {
1000 return false;
1001 }
1002 ops::delete_branch(git, ws.root, branch, true).is_ok()
1003}
1004
1005fn clear_metadata(git: &dyn GitCli, root: &Path, worktree: &Worktree) {
1007 if let Some(branch) = &worktree.branch {
1008 let _ = wtconfig::clear_meta(git, root, branch);
1009 }
1010}
1011
1012pub(crate) fn same_path(a: &Path, b: &Path) -> bool {
1015 let canon = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
1016 canon(a) == canon(b)
1017}
1018
1019pub(crate) fn git_dir_of(root: &Path, is_bare: bool) -> PathBuf {
1021 if is_bare {
1022 root.to_path_buf()
1023 } else {
1024 root.join(".git")
1025 }
1026}
1027
1028pub(crate) fn render_target(
1030 config: &Config,
1031 root: &Path,
1032 branch: &str,
1033 slug: &str,
1034 env: &Env,
1035) -> Result<PathBuf> {
1036 let vars = TemplateVars {
1037 repo_parent: root
1038 .parent()
1039 .map_or_else(|| root.to_path_buf(), Path::to_path_buf),
1040 repo: root
1041 .file_name()
1042 .map(|n| n.to_string_lossy().into_owned())
1043 .unwrap_or_default(),
1044 repo_root: root.to_path_buf(),
1045 branch: branch.to_string(),
1046 branch_slug: slug.to_string(),
1047 home: env
1048 .get("HOME")
1049 .map(PathBuf::from)
1050 .unwrap_or_else(|| PathBuf::from("~")),
1051 };
1052 template::render(&config.path_template, &vars)
1053}
1054
1055pub(crate) fn resolve_target(
1059 config: &Config,
1060 root: &Path,
1061 branch: &str,
1062 slug: &str,
1063 short_hash: &str,
1064 env: &Env,
1065 is_bare: bool,
1066) -> Result<PathBuf> {
1067 let target = render_target(config, root, branch, slug, env)?;
1068 template::ensure_outside_git(&target, &git_dir_of(root, is_bare))?;
1069 if !target.exists() {
1070 return Ok(target);
1071 }
1072 let alt = render_target(config, root, branch, &format!("{slug}-{short_hash}"), env)?;
1073 if alt.exists() {
1074 return Err(Error::operation(format!(
1075 "target path already exists: {}",
1076 target.display()
1077 )));
1078 }
1079 Ok(alt)
1080}
1081
1082pub(crate) fn run_best_effort(git: &dyn GitCli, root: &Path, args: &[&str], step: &str) {
1087 match git.run_raw(root, args) {
1088 Ok(out) if out.success => {}
1089 Ok(out) => {
1090 tracing::debug!(step, stderr = %out.stderr.trim(), "best-effort cleanup step failed");
1091 }
1092 Err(error) => {
1093 tracing::debug!(step, %error, "best-effort cleanup step could not run");
1094 }
1095 }
1096}
1097
1098pub(crate) fn rollback_worktree(
1105 git: &dyn GitCli,
1106 root: &Path,
1107 target: &Path,
1108 branch: &str,
1109 delete_branch: bool,
1110 clear_meta: bool,
1111) {
1112 let target_str = target.to_string_lossy();
1113 run_best_effort(
1114 git,
1115 root,
1116 &["worktree", "remove", "--force", &target_str],
1117 "rollback: worktree remove",
1118 );
1119 run_best_effort(
1120 git,
1121 root,
1122 &["worktree", "prune"],
1123 "rollback: worktree prune",
1124 );
1125 if delete_branch {
1126 run_best_effort(
1127 git,
1128 root,
1129 &["branch", "-D", branch],
1130 "rollback: branch delete",
1131 );
1132 }
1133 if clear_meta {
1134 let _ = wtconfig::clear_meta(git, root, branch);
1138 }
1139}
1140
1141#[cfg(test)]
1142mod tests {
1143 use super::*;
1144 use crate::git::cli::RealGit;
1145 use crate::hooks::RealHookRunner;
1146 use crate::testutil::{TestRepo, give_upstream};
1147 use std::collections::HashMap;
1148
1149 fn env() -> Env {
1150 Env::from_map(HashMap::new())
1151 }
1152
1153 fn workspace(repo: &TestRepo) -> Workspace {
1154 Workspace::discover(repo.root(), &env(), &RealGit).unwrap()
1155 }
1156
1157 fn create_opts(branch: &str) -> CreateOptions {
1158 CreateOptions {
1159 branch: branch.to_string(),
1160 no_hooks: true,
1161 ..Default::default()
1162 }
1163 }
1164
1165 #[test]
1166 fn discover_resolves_root_config_and_bareness() {
1167 let repo = TestRepo::init();
1168 let ws = workspace(&repo);
1169 assert!(!ws.is_bare());
1170 assert_eq!(
1171 std::fs::canonicalize(ws.root()).unwrap(),
1172 std::fs::canonicalize(repo.root()).unwrap()
1173 );
1174 assert_eq!(ws.config().pr_default_remote, "origin");
1175 }
1176
1177 #[test]
1178 fn discover_outside_a_repo_is_not_in_repo() {
1179 let dir = tempfile::tempdir().unwrap();
1180 assert!(matches!(
1181 Workspace::discover(dir.path(), &env(), &RealGit),
1182 Err(Error::NotInRepo)
1183 ));
1184 }
1185
1186 #[test]
1187 fn discover_from_linked_worktree_finds_primary_root() {
1188 let repo = TestRepo::init();
1189 repo.add_worktree("feature/x", "../wt-x");
1190 let linked = repo.root().parent().unwrap().join("wt-x");
1191 let ws = Workspace::discover(&linked, &env(), &RealGit).unwrap();
1192 assert_eq!(
1193 std::fs::canonicalize(ws.root()).unwrap(),
1194 std::fs::canonicalize(repo.root()).unwrap()
1195 );
1196 }
1197
1198 #[test]
1199 fn create_new_branch_records_metadata_and_copies_nothing() {
1200 let repo = TestRepo::init();
1201 let ws = workspace(&repo);
1202 let created = ws
1203 .create(&RealGit, &RealHookRunner, &create_opts("feature/login"))
1204 .unwrap();
1205 assert!(!created.reused);
1206 assert_eq!(created.branch, "feature/login");
1207 assert_eq!(created.base_ref.as_deref(), Some("main"));
1208 assert!(created.path.is_dir());
1209 assert!(
1210 created.path.ends_with("feature-login")
1211 || created.path.to_string_lossy().contains("feature-login")
1212 );
1213 assert_eq!(created.post_create, HookOutcome::Skipped);
1214 assert_eq!(created.submodules, SubmodulesOutcome::Skipped);
1215 assert!(created.copy.copied.is_empty());
1216 let meta = ws.read_meta("feature/login").unwrap();
1217 assert_eq!(meta.base_ref.as_deref(), Some("main"));
1218 assert!(meta.created_by_wt);
1219 }
1220
1221 #[test]
1222 fn create_existing_branch_does_not_mark_created() {
1223 let repo = TestRepo::init();
1224 repo.git(&["branch", "existing"]);
1225 let ws = workspace(&repo);
1226 let created = ws
1227 .create(&RealGit, &RealHookRunner, &create_opts("existing"))
1228 .unwrap();
1229 assert!(created.base_ref.is_none());
1230 assert!(!ws.read_meta("existing").unwrap().created_by_wt);
1231 }
1232
1233 #[test]
1234 fn create_is_idempotent_at_the_same_target() {
1235 let repo = TestRepo::init();
1236 let ws = workspace(&repo);
1237 let first = ws
1238 .create(&RealGit, &RealHookRunner, &create_opts("feature/x"))
1239 .unwrap();
1240 let second = ws
1241 .create(&RealGit, &RealHookRunner, &create_opts("feature/x"))
1242 .unwrap();
1243 assert!(!first.reused);
1244 assert!(second.reused);
1245 assert_eq!(second.path, first.path);
1246 assert_eq!(second.post_create, HookOutcome::Skipped);
1247 }
1248
1249 #[test]
1250 fn create_refuses_branch_checked_out_elsewhere() {
1251 let repo = TestRepo::init();
1252 repo.add_worktree("dup", "../manual-dup");
1253 let ws = workspace(&repo);
1254 let err = ws
1255 .create(&RealGit, &RealHookRunner, &create_opts("dup"))
1256 .unwrap_err();
1257 assert!(err.to_string().contains("already checked out"));
1258 }
1259
1260 #[cfg(feature = "cli")]
1263 #[test]
1264 fn preview_target_names_the_directory_create_actually_makes() {
1265 for branch in ["feat/7-add-login", "_"] {
1273 let repo = TestRepo::init();
1274 let ws = workspace(&repo);
1275 let fresh = Repo::discover(repo.root()).unwrap();
1276 let previewed = preview_target(&ws.parts(&fresh), branch, None).unwrap();
1277 let created = ws
1278 .create(&RealGit, &RealHookRunner, &create_opts(branch))
1279 .unwrap();
1280 assert_eq!(
1281 previewed, created.path,
1282 "preview and creation disagree for {branch:?}"
1283 );
1284 }
1285 }
1286
1287 #[test]
1288 fn a_slugless_branch_is_named_after_the_base_it_forks_from() {
1289 let repo = TestRepo::init();
1294 let ws = workspace(&repo);
1295 let base = Repo::discover(repo.root())
1296 .ok()
1297 .and_then(|r| resolve_hex(r.gix(), "main"))
1298 .expect("main resolves");
1299 let short = &base[..7];
1300
1301 let created = ws
1302 .create(&RealGit, &RealHookRunner, &create_opts("_"))
1303 .unwrap();
1304 let name = created
1305 .path
1306 .file_name()
1307 .map(|n| n.to_string_lossy().into_owned())
1308 .unwrap_or_default();
1309 assert!(
1310 name.ends_with(short),
1311 "{name} should end with the base short hash {short}"
1312 );
1313 }
1314
1315 #[test]
1316 fn create_with_explicit_base_records_it() {
1317 let repo = TestRepo::init();
1318 repo.git(&["branch", "base-branch"]);
1319 let ws = workspace(&repo);
1320 let mut opts = create_opts("derived");
1321 opts.base = Some("base-branch".into());
1322 let created = ws.create(&RealGit, &RealHookRunner, &opts).unwrap();
1323 assert_eq!(created.base_ref.as_deref(), Some("base-branch"));
1324 assert_eq!(
1325 ws.read_meta("derived").unwrap().base_ref.as_deref(),
1326 Some("base-branch")
1327 );
1328 }
1329
1330 #[test]
1331 fn create_with_unknown_base_errors() {
1332 let repo = TestRepo::init();
1333 let ws = workspace(&repo);
1334 let mut opts = create_opts("orphan");
1335 opts.base = Some("no-such-ref".into());
1336 let err = ws.create(&RealGit, &RealHookRunner, &opts).unwrap_err();
1337 assert!(err.to_string().contains("not found"));
1338 }
1339
1340 #[test]
1341 fn create_reports_hook_outcomes_without_failing() {
1342 let repo = TestRepo::init();
1343 repo.write(".wt.toml", "[hooks]\npost_create = \"exit 3\"\n");
1344 repo.commit_all("config");
1345 let ws = workspace(&repo);
1346 let mut opts = create_opts("hooked");
1347 opts.no_hooks = false;
1348 let created = ws.create(&RealGit, &RealHookRunner, &opts).unwrap();
1349 assert_eq!(created.post_create, HookOutcome::ExitedNonZero(3));
1350 assert!(created.path.is_dir());
1351 }
1352
1353 #[test]
1354 fn create_copies_ignored_files() {
1355 let repo = TestRepo::init();
1356 std::fs::write(repo.root().join(".wt.toml"), "copy = [\".env\"]\n").unwrap();
1357 repo.write(".env", "SECRET=1\n");
1358 let ws = workspace(&repo);
1359 let created = ws
1360 .create(&RealGit, &RealHookRunner, &create_opts("withenv"))
1361 .unwrap();
1362 assert_eq!(created.copy.copied.len(), 1);
1363 assert!(created.path.join(".env").exists());
1364 }
1365
1366 #[test]
1367 fn create_rolls_back_when_a_post_add_step_fails() {
1368 use crate::git::cli::{GitCli, GitOutput};
1369 struct FailConfig(RealGit);
1370 impl GitCli for FailConfig {
1371 fn run_raw(&self, repo: &Path, args: &[&str]) -> Result<GitOutput> {
1372 if args.first() == Some(&"config") && args.iter().any(|a| a.starts_with("wt.")) {
1373 return Ok(GitOutput {
1374 success: false,
1375 stdout: String::new(),
1376 stderr: "simulated failure".into(),
1377 });
1378 }
1379 self.0.run_raw(repo, args)
1380 }
1381 }
1382 let repo = TestRepo::init();
1383 let ws = workspace(&repo);
1384 let err = ws
1385 .create(
1386 &FailConfig(RealGit),
1387 &RealHookRunner,
1388 &create_opts("rollme"),
1389 )
1390 .unwrap_err();
1391 assert!(err.to_string().contains("simulated failure"));
1392 assert!(repo.git(&["branch", "--list", "rollme"]).trim().is_empty());
1393 assert!(!repo.git(&["worktree", "list"]).contains("rollme"));
1394 }
1395
1396 fn row_for(ws: &Workspace, branch: &str) -> Worktree {
1398 ws.list(&RealGit)
1399 .unwrap()
1400 .into_iter()
1401 .find(|w| w.branch.as_deref() == Some(branch))
1402 .unwrap()
1403 }
1404
1405 #[test]
1406 fn list_enumerate_and_meta_expose_worktrees() {
1407 let repo = TestRepo::init();
1408 let ws = workspace(&repo);
1409 ws.create(&RealGit, &RealHookRunner, &create_opts("feature/x"))
1410 .unwrap();
1411 let shallow = ws.enumerate(&RealGit).unwrap();
1412 assert_eq!(shallow.len(), 2);
1413 assert!(shallow.iter().all(|w| w.dirty.is_none()));
1415 let feat = row_for(&ws, "feature/x");
1416 assert_eq!(feat.dirty, Some(false));
1417 assert_eq!(feat.base_ref.as_deref(), Some("main"));
1418 }
1419
1420 #[test]
1421 fn write_meta_applies_only_the_set_fields() {
1422 let repo = TestRepo::init();
1423 let ws = workspace(&repo);
1424 ws.create(&RealGit, &RealHookRunner, &create_opts("feature/x"))
1425 .unwrap();
1426 ws.write_meta(
1427 &RealGit,
1428 "feature/x",
1429 &MetaUpdate {
1430 pr_number: Some(7),
1431 pr_state: Some("open".into()),
1432 pr_title: Some("Add x".into()),
1433 pr_url: Some("https://example.test/7".into()),
1434 ..MetaUpdate::default()
1435 },
1436 )
1437 .unwrap();
1438 let meta = ws.read_meta("feature/x").unwrap();
1439 assert_eq!(meta.pr_number, Some(7));
1440 assert_eq!(meta.pr_state.as_deref(), Some("open"));
1441 assert_eq!(meta.pr_title.as_deref(), Some("Add x"));
1442 assert_eq!(meta.pr_url.as_deref(), Some("https://example.test/7"));
1443 assert_eq!(meta.base_ref.as_deref(), Some("main"));
1445 assert!(meta.created_by_wt);
1446
1447 ws.write_meta(
1449 &RealGit,
1450 "feature/x",
1451 &MetaUpdate {
1452 pr_state: Some("merged".into()),
1453 ..MetaUpdate::default()
1454 },
1455 )
1456 .unwrap();
1457 let meta = ws.read_meta("feature/x").unwrap();
1458 assert_eq!(meta.pr_state.as_deref(), Some("merged"));
1459 assert_eq!(meta.pr_number, Some(7));
1460 assert_eq!(meta.pr_title.as_deref(), Some("Add x"));
1461 }
1462
1463 #[test]
1464 fn write_meta_marks_created_by_wt_but_never_unmarks() {
1465 let repo = TestRepo::init();
1466 let ws = workspace(&repo);
1467 repo.git(&["branch", "solo"]);
1468 ws.write_meta(&RealGit, "solo", &MetaUpdate::default())
1470 .unwrap();
1471 assert_eq!(ws.read_meta("solo").unwrap(), WtMeta::default());
1472
1473 ws.write_meta(
1474 &RealGit,
1475 "solo",
1476 &MetaUpdate {
1477 created_by_wt: true,
1478 ..MetaUpdate::default()
1479 },
1480 )
1481 .unwrap();
1482 assert!(ws.read_meta("solo").unwrap().created_by_wt);
1483 ws.write_meta(&RealGit, "solo", &MetaUpdate::default())
1485 .unwrap();
1486 assert!(ws.read_meta("solo").unwrap().created_by_wt);
1487 }
1488
1489 #[test]
1490 fn clear_meta_removes_the_section_and_tolerates_a_missing_one() {
1491 let repo = TestRepo::init();
1492 let ws = workspace(&repo);
1493 ws.create(&RealGit, &RealHookRunner, &create_opts("feature/x"))
1494 .unwrap();
1495 assert!(ws.read_meta("feature/x").unwrap().created_by_wt);
1496 ws.clear_meta(&RealGit, "feature/x").unwrap();
1497 assert_eq!(ws.read_meta("feature/x").unwrap(), WtMeta::default());
1498 ws.clear_meta(&RealGit, "never-recorded").unwrap();
1500 }
1501
1502 #[test]
1503 fn metadata_writes_take_the_repo_lock() {
1504 let repo = TestRepo::init();
1506 let ws = workspace(&repo);
1507 repo.git(&["branch", "locked"]);
1508 let held = ws.lock().unwrap();
1509 let err = ws
1510 .write_meta(
1511 &RealGit,
1512 "locked",
1513 &MetaUpdate {
1514 pr_number: Some(1),
1515 ..MetaUpdate::default()
1516 },
1517 )
1518 .unwrap_err();
1519 assert!(matches!(err, Error::LockUnavailable { .. }), "{err:?}");
1520 let err = ws.clear_meta(&RealGit, "locked").unwrap_err();
1521 assert!(matches!(err, Error::LockUnavailable { .. }), "{err:?}");
1522 drop(held);
1523 ws.clear_meta(&RealGit, "locked").unwrap();
1524 }
1525
1526 #[test]
1527 fn metadata_writes_refuse_a_future_schema() {
1528 let repo = TestRepo::init();
1529 let ws = workspace(&repo);
1530 repo.git(&["branch", "stamped"]);
1531 repo.git(&["config", "wt.schema", "3"]);
1532 let err = ws
1533 .write_meta(&RealGit, "stamped", &MetaUpdate::default())
1534 .unwrap_err();
1535 assert!(
1536 matches!(err, Error::SchemaTooNew { found: 3, .. }),
1537 "{err:?}"
1538 );
1539 let err = ws.clear_meta(&RealGit, "stamped").unwrap_err();
1540 assert!(
1541 matches!(err, Error::SchemaTooNew { found: 3, .. }),
1542 "{err:?}"
1543 );
1544 }
1545
1546 #[test]
1547 fn remove_blocked_by_guards_is_a_typed_error() {
1548 let repo = TestRepo::init();
1549 let ws = workspace(&repo);
1550 ws.create(&RealGit, &RealHookRunner, &create_opts("topic"))
1551 .unwrap();
1552 let row = row_for(&ws, "topic");
1554 let err = ws
1555 .remove(
1556 &RealGit,
1557 &RealHookRunner,
1558 &row,
1559 &RemoveOptions {
1560 no_hooks: true,
1561 ..Default::default()
1562 },
1563 )
1564 .unwrap_err();
1565 match err {
1566 Error::RemoveGuarded { dirty, unpushed } => {
1567 assert!(!dirty);
1568 assert!(unpushed);
1569 }
1570 other => panic!("expected RemoveGuarded, got {other:?}"),
1571 }
1572 }
1573
1574 #[test]
1575 fn create_seeds_submodules_without_reaching_a_remote() {
1576 let repo = TestRepo::init();
1582 repo.add_submodule("libs/sub");
1583 let ws = workspace(&repo);
1584 let created = ws
1585 .create(
1586 &RealGit,
1587 &RealHookRunner,
1588 &CreateOptions {
1589 branch: "topic".to_string(),
1590 init_submodules: true,
1591 seed_submodules: true,
1592 no_hooks: true,
1593 ..Default::default()
1594 },
1595 )
1596 .unwrap();
1597
1598 assert!(
1599 created.path.join("libs/sub/sub.txt").exists(),
1600 "submodule was not populated"
1601 );
1602 assert_eq!(
1603 created.submodule_seeding.seeded,
1604 vec!["libs/sub".to_string()]
1605 );
1606 assert!(created.submodule_seeding.failed.is_empty());
1607 assert!(matches!(
1608 created.submodules,
1609 SubmodulesOutcome::Initialized(1)
1610 ));
1611 }
1612
1613 #[test]
1614 fn reflink_materialization_matches_a_normal_checkout() {
1615 let Some(repo) = TestRepo::init_cow() else {
1619 return;
1620 };
1621 repo.add_submodule("libs/sub");
1622 repo.write("tracked.txt", "content\n");
1623 repo.write(".gitignore", "build.out\n");
1624 repo.commit_all("add a tracked file and an ignore rule");
1625 repo.write("build.out", "artifact\n");
1629 repo.write("scratch.txt", "unsaved\n");
1633 std::fs::create_dir_all(repo.root().join("wip")).unwrap();
1634 repo.write("wip/notes.md", "later\n");
1635 repo.git(&["config", "status.showUntrackedFiles", "no"]);
1638
1639 let ws = workspace(&repo);
1640 let created = ws
1641 .create(
1642 &RealGit,
1643 &RealHookRunner,
1644 &CreateOptions {
1645 branch: "topic".to_string(),
1646 init_submodules: true,
1647 seed_submodules: true,
1648 reflink: true,
1649 no_hooks: true,
1650 ..Default::default()
1651 },
1652 )
1653 .unwrap();
1654
1655 assert!(created.reflinked, "the CoW path did not run");
1656 assert_eq!(
1658 std::fs::read_to_string(created.path.join("tracked.txt")).unwrap(),
1659 "content\n"
1660 );
1661 let status = repo.git(&["-C", &created.path.to_string_lossy(), "status", "--short"]);
1662 assert!(
1663 status.trim().is_empty(),
1664 "worktree is not clean: {status:?}"
1665 );
1666 assert!(created.path.join("libs/sub/sub.txt").exists());
1668 let subs = repo.git(&[
1669 "-C",
1670 &created.path.to_string_lossy(),
1671 "submodule",
1672 "status",
1673 "--recursive",
1674 ]);
1675 assert!(
1676 subs.starts_with(' '),
1677 "submodule not in sync after a reflink create: {subs:?}"
1678 );
1679 let origin =
1684 |dir: &Path| repo.git(&["-C", &dir.to_string_lossy(), "config", "remote.origin.url"]);
1685 assert_eq!(
1686 origin(&created.path.join("libs/sub")),
1687 origin(&repo.root().join("libs/sub")),
1688 "the reflinked submodule kept the local mirror as its origin"
1689 );
1690 assert!(created.path.join("build.out").exists());
1692 assert!(
1693 !created.path.join("scratch.txt").exists(),
1694 "an untracked source file was cloned into the new worktree"
1695 );
1696 assert!(
1697 !created.path.join("wip/notes.md").exists(),
1698 "an untracked source directory was cloned into the new worktree"
1699 );
1700 }
1701
1702 #[test]
1703 fn reflink_declines_when_the_source_is_at_a_different_tree() {
1704 let repo = TestRepo::init();
1708 let base = repo.git(&["rev-parse", "HEAD"]).trim().to_string();
1709 repo.write("only-on-head.txt", "later\n");
1710 repo.commit_all("move the source ahead");
1711
1712 let ws = workspace(&repo);
1713 let created = ws
1714 .create(
1715 &RealGit,
1716 &RealHookRunner,
1717 &CreateOptions {
1718 branch: "topic".to_string(),
1719 base: Some(base),
1720 reflink: true,
1721 no_hooks: true,
1722 ..Default::default()
1723 },
1724 )
1725 .unwrap();
1726
1727 assert!(!created.reflinked, "cloned across differing trees");
1728 assert!(!created.path.join("only-on-head.txt").exists());
1730 let status = repo.git(&["-C", &created.path.to_string_lossy(), "status", "--short"]);
1731 assert!(
1732 status.trim().is_empty(),
1733 "worktree is not clean: {status:?}"
1734 );
1735 }
1736
1737 #[test]
1738 fn create_without_seeding_leaves_the_clone_to_git() {
1739 let repo = TestRepo::init();
1744 repo.add_submodule("libs/sub");
1745 let ws = workspace(&repo);
1746 let created = ws
1747 .create(
1748 &RealGit,
1749 &RealHookRunner,
1750 &CreateOptions {
1751 branch: "topic".to_string(),
1752 init_submodules: true,
1753 seed_submodules: false,
1754 no_hooks: true,
1755 ..Default::default()
1756 },
1757 )
1758 .unwrap();
1759
1760 assert!(created.submodule_seeding.seeded.is_empty());
1761 assert!(!created.path.join("libs/sub/sub.txt").exists());
1762 assert!(matches!(
1763 created.submodules,
1764 SubmodulesOutcome::Failed { .. }
1765 ));
1766 }
1767
1768 #[test]
1769 fn remove_succeeds_on_a_worktree_containing_submodules() {
1770 let repo = TestRepo::init();
1775 repo.add_submodule("libs/sub");
1776 let ws = workspace(&repo);
1777 let created = ws
1778 .create(&RealGit, &RealHookRunner, &create_opts("topic"))
1779 .unwrap();
1780 repo.git(&[
1785 "-C",
1786 &created.path.to_string_lossy(),
1787 "-c",
1788 "protocol.file.allow=always",
1789 "submodule",
1790 "update",
1791 "--init",
1792 ]);
1793 assert!(created.path.join("libs/sub/sub.txt").exists());
1794 give_upstream(&repo, "topic");
1797
1798 let row = row_for(&ws, "topic");
1799 let removed = ws
1800 .remove(
1801 &RealGit,
1802 &RealHookRunner,
1803 &row,
1804 &RemoveOptions {
1805 no_hooks: true,
1806 ..Default::default()
1807 },
1808 )
1809 .unwrap();
1810 assert!(!created.path.exists(), "worktree directory still present");
1811 assert!(
1812 removed.forced_for_submodules,
1813 "removal should record that git needed forcing for submodules"
1814 );
1815 assert!(
1816 !removed.forced_past_guards,
1817 "no wt guard was overridden, so this must not read as a forced removal"
1818 );
1819 }
1820
1821 #[test]
1822 fn remove_guards_untracked_files_when_submodules_force_git() {
1823 let repo = TestRepo::init();
1828 repo.add_submodule("libs/sub");
1829 let ws = workspace(&repo);
1830 let created = ws
1831 .create(&RealGit, &RealHookRunner, &create_opts("topic"))
1832 .unwrap();
1833 repo.git(&[
1834 "-C",
1835 &created.path.to_string_lossy(),
1836 "-c",
1837 "protocol.file.allow=always",
1838 "submodule",
1839 "update",
1840 "--init",
1841 ]);
1842 give_upstream(&repo, "topic");
1843 std::fs::write(created.path.join("scratch.txt"), "unsaved\n").unwrap();
1844
1845 let row = row_for(&ws, "topic");
1846 let err = ws
1847 .remove(
1848 &RealGit,
1849 &RealHookRunner,
1850 &row,
1851 &RemoveOptions {
1852 no_hooks: true,
1853 ..Default::default()
1854 },
1855 )
1856 .unwrap_err();
1857 assert!(matches!(err, Error::RemoveGuarded { dirty: true, .. }));
1858 assert!(created.path.join("scratch.txt").exists());
1859
1860 let row = row_for(&ws, "topic");
1862 let removed = ws
1863 .remove(
1864 &RealGit,
1865 &RealHookRunner,
1866 &row,
1867 &RemoveOptions {
1868 no_hooks: true,
1869 force_remove: true,
1870 ..Default::default()
1871 },
1872 )
1873 .unwrap();
1874 assert!(!created.path.exists());
1875 assert!(removed.forced_past_guards);
1876 }
1877
1878 #[test]
1879 fn remove_without_submodules_does_not_report_a_submodule_force() {
1880 let repo = TestRepo::init();
1881 let ws = workspace(&repo);
1882 ws.create(&RealGit, &RealHookRunner, &create_opts("topic"))
1883 .unwrap();
1884 give_upstream(&repo, "topic");
1885 let row = row_for(&ws, "topic");
1886 let removed = ws
1887 .remove(
1888 &RealGit,
1889 &RealHookRunner,
1890 &row,
1891 &RemoveOptions {
1892 no_hooks: true,
1893 ..Default::default()
1894 },
1895 )
1896 .unwrap();
1897 assert!(!removed.forced_for_submodules);
1898 assert!(!removed.forced_past_guards);
1899 }
1900
1901 #[test]
1902 fn remove_force_reports_forced_past_guards() {
1903 let repo = TestRepo::init();
1904 let ws = workspace(&repo);
1905 ws.create(&RealGit, &RealHookRunner, &create_opts("forced"))
1906 .unwrap();
1907 let row = row_for(&ws, "forced");
1908 let removed = ws
1909 .remove(
1910 &RealGit,
1911 &RealHookRunner,
1912 &row,
1913 &RemoveOptions {
1914 force_remove: true,
1915 force_branch: true,
1916 no_hooks: true,
1917 keep_branch: false,
1918 },
1919 )
1920 .unwrap();
1921 assert!(removed.forced_past_guards);
1922 assert!(!repo.git(&["worktree", "list"]).contains("forced"));
1923 assert!(removed.branch_deleted);
1925 assert_eq!(ws.read_meta("forced").unwrap(), WtMeta::default());
1927 }
1928
1929 #[test]
1930 fn remove_refuses_the_primary_worktree() {
1931 let repo = TestRepo::init();
1932 let ws = workspace(&repo);
1933 let main = row_for(&ws, "main");
1934 let err = ws
1935 .remove(&RealGit, &RealHookRunner, &main, &RemoveOptions::default())
1936 .unwrap_err();
1937 assert!(err.to_string().contains("primary"));
1938 }
1939
1940 #[test]
1941 fn remove_missing_worktree_prunes_without_guards() {
1942 let repo = TestRepo::init();
1943 let ws = workspace(&repo);
1944 let created = ws
1945 .create(&RealGit, &RealHookRunner, &create_opts("gone"))
1946 .unwrap();
1947 std::fs::remove_dir_all(&created.path).unwrap();
1948 let row = row_for(&ws, "gone");
1949 assert!(row.is_missing);
1950 let removed = ws
1951 .remove(
1952 &RealGit,
1953 &RealHookRunner,
1954 &row,
1955 &RemoveOptions {
1956 no_hooks: true,
1957 ..Default::default()
1958 },
1959 )
1960 .unwrap();
1961 assert_eq!(removed.pre_remove, HookOutcome::Skipped);
1962 assert!(!repo.git(&["worktree", "list"]).contains("gone"));
1963 }
1964
1965 #[test]
1966 fn remove_failing_pre_remove_hook_aborts_unless_forced() {
1967 let repo = TestRepo::init();
1968 repo.write(".wt.toml", "[hooks]\npre_remove = \"exit 5\"\n");
1969 repo.commit_all("config");
1970 let ws = workspace(&repo);
1971 ws.create(&RealGit, &RealHookRunner, &create_opts("hooked"))
1972 .unwrap();
1973 let head = repo.git(&["rev-parse", "HEAD"]).trim().to_string();
1975 repo.git(&["update-ref", "refs/remotes/origin/hooked", &head]);
1976 repo.git(&["config", "branch.hooked.remote", "origin"]);
1977 repo.git(&["config", "branch.hooked.merge", "refs/heads/hooked"]);
1978 let row = row_for(&ws, "hooked");
1979 let err = ws
1980 .remove(&RealGit, &RealHookRunner, &row, &RemoveOptions::default())
1981 .unwrap_err();
1982 assert!(
1983 err.to_string()
1984 .contains("pre_remove hook exited with status 5")
1985 );
1986 let removed = ws
1988 .remove(
1989 &RealGit,
1990 &RealHookRunner,
1991 &row,
1992 &RemoveOptions {
1993 force_remove: true,
1994 ..Default::default()
1995 },
1996 )
1997 .unwrap();
1998 assert_eq!(removed.pre_remove, HookOutcome::ExitedNonZero(5));
1999 assert!(!repo.git(&["worktree", "list"]).contains("hooked"));
2000 }
2001
2002 #[test]
2003 fn discover_refuses_a_future_schema() {
2004 let repo = TestRepo::init();
2005 repo.git(&["config", "wt.schema", "99"]);
2006 let err = Workspace::discover(repo.root(), &env(), &RealGit)
2007 .err()
2008 .expect("a future schema must refuse discovery");
2009 assert!(matches!(err, Error::SchemaTooNew { found: 99, .. }));
2010 }
2011
2012 #[test]
2013 fn mutations_refuse_a_schema_stamped_after_discovery() {
2014 let repo = TestRepo::init();
2017 let ws = workspace(&repo);
2018 repo.git(&["config", "wt.schema", "2"]);
2019 let err = ws
2020 .create(&RealGit, &RealHookRunner, &create_opts("late"))
2021 .unwrap_err();
2022 assert!(matches!(err, Error::SchemaTooNew { found: 2, .. }));
2023 }
2024
2025 #[test]
2026 fn lock_is_exclusive_and_released_on_drop() {
2027 let repo = TestRepo::init();
2028 let ws = workspace(&repo);
2029 let held = ws.lock().unwrap();
2030 let err = acquire_repo_lock(ws.root(), Duration::from_millis(50))
2032 .err()
2033 .expect("the held lock must exclude a second holder");
2034 match &err {
2035 Error::LockUnavailable { path, .. } => {
2036 assert!(path.ends_with("wt-mutation.lock"), "{path}");
2037 }
2038 other => panic!("expected LockUnavailable, got {other:?}"),
2039 }
2040 drop(held);
2042 acquire_repo_lock(ws.root(), Duration::from_millis(50)).unwrap();
2043 }
2044
2045 #[test]
2046 fn a_schema_refusal_does_not_strand_the_lock() {
2047 let repo = TestRepo::init();
2051 let ws = workspace(&repo);
2052 repo.git(&["config", "wt.schema", "2"]);
2053 let err = acquire_repo_lock(ws.root(), Duration::from_millis(50))
2054 .err()
2055 .expect("a future schema must refuse the acquisition");
2056 assert!(
2057 matches!(err, Error::SchemaTooNew { found: 2, .. }),
2058 "{err:?}"
2059 );
2060 assert!(!ws.root().join(".git/wt-mutation.lock").exists());
2061
2062 repo.git(&["config", "--unset", "wt.schema"]);
2063 acquire_repo_lock(ws.root(), Duration::from_millis(50)).unwrap();
2064 }
2065
2066 #[test]
2067 fn the_lock_gate_reads_a_bare_repository_too() {
2068 let repo = TestRepo::init_bare();
2073 acquire_repo_lock(repo.root(), Duration::from_millis(50)).unwrap();
2074
2075 repo.git(&["config", "wt.schema", "2"]);
2076 let err = acquire_repo_lock(repo.root(), Duration::from_millis(50))
2077 .err()
2078 .expect("a bare repository is gated like any other");
2079 assert!(
2080 matches!(err, Error::SchemaTooNew { found: 2, .. }),
2081 "{err:?}"
2082 );
2083 }
2084
2085 #[test]
2086 fn a_schema_bump_landing_during_the_lock_wait_is_refused() {
2087 let repo = TestRepo::init();
2094 let ws = workspace(&repo);
2095 repo.git(&["branch", "stamped"]);
2096 let held = ws.lock().unwrap();
2097
2098 let (discovered, wait) = std::sync::mpsc::channel();
2099 let root = repo.root().to_path_buf();
2100 let writer = std::thread::spawn(move || {
2101 let ws = Workspace::discover(&root, &env(), &RealGit)?;
2102 discovered.send(()).expect("the test thread outlives this");
2103 ws.write_meta(
2104 &RealGit,
2105 "stamped",
2106 &MetaUpdate {
2107 pr_number: Some(1),
2108 ..MetaUpdate::default()
2109 },
2110 )
2111 });
2112
2113 wait.recv().expect("the writer discovers before it blocks");
2114 repo.git(&["config", "wt.schema", "2"]);
2115 drop(held);
2116
2117 let err = writer
2118 .join()
2119 .expect("the writer must not panic")
2120 .expect_err("the bumped schema must refuse the blocked write");
2121 assert!(
2122 matches!(err, Error::SchemaTooNew { found: 2, .. }),
2123 "{err:?}"
2124 );
2125 repo.git(&["config", "--unset", "wt.schema"]);
2127 assert_eq!(ws.read_meta("stamped").unwrap(), WtMeta::default());
2128 }
2129
2130 #[test]
2131 fn create_releases_the_lock_before_the_post_create_hook() {
2132 let repo = TestRepo::init();
2135 repo.write(
2136 ".wt.toml",
2137 "[hooks]\npost_create = \"test ! -e \\\"$WT_REPO_ROOT/.git/wt-mutation.lock\\\"\"\n",
2138 );
2139 repo.commit_all("config");
2140 let ws = workspace(&repo);
2141 let mut opts = create_opts("hookfree");
2142 opts.no_hooks = false;
2143 let created = ws.create(&RealGit, &RealHookRunner, &opts).unwrap();
2144 assert_eq!(created.post_create, HookOutcome::Succeeded);
2145 }
2146
2147 #[test]
2148 fn concurrent_creates_on_one_branch_do_not_corrupt_metadata() {
2149 let repo = TestRepo::init();
2153 let root = repo.root().to_path_buf();
2154 let spawn = |root: PathBuf| {
2155 std::thread::spawn(move || {
2156 let ws = Workspace::discover(&root, &env(), &RealGit)?;
2157 ws.create(&RealGit, &RealHookRunner, &create_opts("feat/race"))
2158 })
2159 };
2160 let a = spawn(root.clone());
2161 let b = spawn(root);
2162 let results = [a.join().unwrap(), b.join().unwrap()];
2163 let ok = results.iter().filter(|r| r.is_ok()).count();
2164 let created = results
2167 .iter()
2168 .filter(|r| r.as_ref().is_ok_and(|c| !c.reused))
2169 .count();
2170 assert!(ok >= 1, "at least one racer must win: {results:?}");
2171 assert_eq!(created, 1, "exactly one racer creates: {results:?}");
2172
2173 let ws = workspace(&repo);
2174 let rows = ws.list(&RealGit).unwrap();
2175 let race_rows: Vec<_> = rows
2176 .iter()
2177 .filter(|w| w.branch.as_deref() == Some("feat/race"))
2178 .collect();
2179 assert_eq!(race_rows.len(), 1);
2180 let meta = ws.read_meta("feat/race").unwrap();
2181 assert_eq!(meta.base_ref.as_deref(), Some("main"));
2182 assert!(meta.created_by_wt);
2183 }
2184
2185 #[test]
2186 fn resolve_base_falls_back_to_head_only_without_default() {
2187 let repo = TestRepo::init();
2188 let ws = workspace(&repo);
2189 let r = Repo::discover(repo.root()).unwrap();
2190 assert_eq!(
2191 resolve_base(&r, ws.config(), Some("explicit")),
2192 ("explicit".into(), false)
2193 );
2194 assert_eq!(resolve_base(&r, ws.config(), None), ("main".into(), false));
2196 let mut config = ws.config().clone();
2198 config.default_base = Some("trunk".into());
2199 assert_eq!(resolve_base(&r, &config, None), ("trunk".into(), false));
2200 }
2201}