1use std::path::{Path, PathBuf};
4
5use console::style;
6
7use crate::constants::{
8 default_worktree_path, format_config_key, CONFIG_KEY_BASE_BRANCH, CONFIG_KEY_BASE_PATH,
9 CONFIG_KEY_INTENDED_BRANCH,
10};
11use crate::error::{CwError, Result};
12use crate::git;
13use crate::shared_files;
14
15use super::ai_tools::LaunchOptions;
16use crate::cli::EmitFormat;
17use crate::messages;
18
19pub fn create_worktree(
21 branch_name: &str,
22 base_branch: Option<&str>,
23 path: Option<&str>,
24 initial_prompt: Option<&str>,
25 launch_opts: &LaunchOptions<'_>,
26 emit: EmitFormat,
27) -> Result<PathBuf> {
28 let repo = git::get_repo_root(None)?;
29
30 if !git::is_valid_branch_name(branch_name, Some(&repo)) {
32 let error_msg = git::get_branch_name_error(branch_name);
33 return Err(CwError::InvalidBranch(messages::invalid_branch_name(
34 &error_msg,
35 )));
36 }
37
38 macro_rules! say {
41 ($($arg:tt)*) => {
42 if emit == EmitFormat::Json {
43 eprintln!($($arg)*);
44 } else {
45 println!($($arg)*);
46 }
47 };
48 }
49
50 let existing = git::find_worktree_by_branch(&repo, branch_name)?.or(
52 git::find_worktree_by_branch(&repo, &format!("refs/heads/{}", branch_name))?,
53 );
54
55 if let Some(existing_path) = existing {
56 say!(
57 "\n{}\nBranch '{}' already has a worktree at:\n {}\n",
58 style("! Worktree already exists").yellow().bold(),
59 style(branch_name).cyan(),
60 style(existing_path.display()).blue(),
61 );
62
63 if git::is_non_interactive() {
64 return Err(CwError::InvalidBranch(format!(
65 "Worktree for branch '{}' already exists at {}.\n\
66 Use 'gw resume {}' to continue work.",
67 branch_name,
68 existing_path.display(),
69 branch_name,
70 )));
71 }
72
73 say!(
75 "Use '{}' to resume work in this worktree.\n",
76 style(format!("gw resume {}", branch_name)).cyan()
77 );
78 return Ok(existing_path);
79 }
80
81 let mut branch_already_exists = false;
83 let mut is_remote_only = false;
84
85 if git::branch_exists(branch_name, Some(&repo)) {
86 say!(
87 "\n{}\nBranch '{}' already exists locally but has no worktree.\n",
88 style("! Branch already exists").yellow().bold(),
89 style(branch_name).cyan(),
90 );
91 branch_already_exists = true;
92 } else if git::remote_branch_exists(branch_name, Some(&repo), "origin") {
93 say!(
94 "\n{}\nBranch '{}' exists on remote but not locally.\n",
95 style("! Remote branch found").yellow().bold(),
96 style(branch_name).cyan(),
97 );
98 branch_already_exists = true;
99 is_remote_only = true;
100 }
101
102 let base = if let Some(b) = base_branch {
104 b.to_string()
105 } else {
106 git::detect_default_branch(Some(&repo))
107 };
108
109 if (!is_remote_only || base_branch.is_some()) && !git::branch_exists(&base, Some(&repo)) {
111 return Err(CwError::InvalidBranch(messages::branch_not_found(&base)));
112 }
113
114 let worktree_path = if let Some(p) = path {
116 PathBuf::from(p)
117 .canonicalize()
118 .unwrap_or_else(|_| PathBuf::from(p))
119 } else {
120 default_worktree_path(&repo, branch_name)
121 };
122
123 say!("\n{}", style("Creating new worktree:").cyan().bold());
124 say!(" Base branch: {}", style(&base).green());
125 say!(" New branch: {}", style(branch_name).green());
126 say!(" Path: {}\n", style(worktree_path.display()).blue());
127
128 if let Some(parent) = worktree_path.parent() {
130 let _ = std::fs::create_dir_all(parent);
131 }
132
133 let _ = git::git_command(&["fetch", "--all", "--prune"], Some(&repo), false, false);
135
136 let wt_str = worktree_path.to_string_lossy().to_string();
138 if is_remote_only {
139 git::git_command(
140 &[
141 "worktree",
142 "add",
143 "-b",
144 branch_name,
145 &wt_str,
146 &format!("origin/{}", branch_name),
147 ],
148 Some(&repo),
149 true,
150 false,
151 )?;
152 } else if branch_already_exists {
153 git::git_command(
154 &["worktree", "add", &wt_str, branch_name],
155 Some(&repo),
156 true,
157 false,
158 )?;
159 } else {
160 git::git_command(
161 &["worktree", "add", "-b", branch_name, &wt_str, &base],
162 Some(&repo),
163 true,
164 false,
165 )?;
166 }
167
168 let bb_key = format_config_key(CONFIG_KEY_BASE_BRANCH, branch_name);
170 let bp_key = format_config_key(CONFIG_KEY_BASE_PATH, branch_name);
171 let ib_key = format_config_key(CONFIG_KEY_INTENDED_BRANCH, branch_name);
172 git::set_config(&bb_key, &base, Some(&repo))?;
173 git::set_config(&bp_key, &repo.to_string_lossy(), Some(&repo))?;
174 git::set_config(&ib_key, branch_name, Some(&repo))?;
175
176 say!(
177 "{} Worktree created successfully\n",
178 style("*").green().bold()
179 );
180
181 shared_files::share_files(&repo, &worktree_path);
183
184 crate::hooks::run_event("post_new", &worktree_path)?;
190
191 if emit == EmitFormat::Json {
194 println!(
195 "{}",
196 serde_json::to_string(&serde_json::json!({
197 "worktree_path": worktree_path.display().to_string(),
198 "branch": branch_name,
199 "base": base,
200 }))
201 .map_err(|e| CwError::Other(format!("json serialization failed: {e}")))?
202 );
203 return Ok(worktree_path);
204 }
205
206 let _ = super::ai_tools::spawn_in_worktree(&worktree_path, initial_prompt, launch_opts);
212
213 Ok(worktree_path)
214}
215
216#[derive(Debug)]
222pub enum DeletionOutcome {
223 Deleted {
224 branch: Option<String>,
225 path: PathBuf,
226 },
227 Skipped {
228 reason: String,
229 },
230 Failed {
231 error: CwError,
232 },
233}
234
235#[derive(Debug, Clone, Copy)]
237pub struct RmFlags {
238 pub keep_branch: bool,
239 pub delete_remote: bool,
240 pub git_force: bool,
242 pub allow_busy: bool,
244}
245
246pub(crate) fn delete_one(
253 worktree_path: &Path,
254 branch_name: Option<&str>,
255 main_repo: &Path,
256 flags: RmFlags,
257) -> DeletionOutcome {
258 let wt_resolved = git::canonicalize_or(worktree_path);
260 let main_resolved = git::canonicalize_or(main_repo);
261 if wt_resolved == main_resolved {
262 return DeletionOutcome::Failed {
263 error: CwError::Git(messages::cannot_delete_main_worktree()),
264 };
265 }
266
267 if let Ok(cwd) = std::env::current_dir() {
269 let cwd_canon = cwd.canonicalize().unwrap_or(cwd);
270 let wt_canon = worktree_path
271 .canonicalize()
272 .unwrap_or_else(|_| worktree_path.to_path_buf());
273 if cwd_canon.starts_with(&wt_canon) {
274 let _ = std::env::set_current_dir(main_repo);
275 }
276 }
277
278 if let Err(e) = crate::hooks::run_event("pre_rm", worktree_path) {
283 eprintln!(
284 "{} pre_rm hook failed (continuing anyway): {}",
285 style("!").yellow().bold(),
286 e
287 );
288 }
289
290 println!(
292 "{}",
293 style(messages::removing_worktree(worktree_path)).yellow()
294 );
295 if let Err(e) = git::remove_worktree_safe(worktree_path, main_repo, flags.git_force) {
296 return DeletionOutcome::Failed { error: e };
297 }
298 println!("{} Worktree removed\n", style("*").green().bold());
299
300 if let Some(branch) = branch_name {
302 if !flags.keep_branch {
303 println!(
304 "{}",
305 style(messages::deleting_local_branch(branch)).yellow()
306 );
307 let _ = git::git_command(&["branch", "-D", branch], Some(main_repo), false, false);
308
309 let bb_key = format_config_key(CONFIG_KEY_BASE_BRANCH, branch);
310 let bp_key = format_config_key(CONFIG_KEY_BASE_PATH, branch);
311 let ib_key = format_config_key(CONFIG_KEY_INTENDED_BRANCH, branch);
312 git::unset_config(&bb_key, Some(main_repo));
313 git::unset_config(&bp_key, Some(main_repo));
314 git::unset_config(&ib_key, Some(main_repo));
315
316 println!(
317 "{} Local branch and metadata removed\n",
318 style("*").green().bold()
319 );
320
321 if flags.delete_remote {
322 println!(
323 "{}",
324 style(messages::deleting_remote_branch(branch)).yellow()
325 );
326 match git::git_command(
327 &["push", "origin", &format!(":{}", branch)],
328 Some(main_repo),
329 false,
330 true,
331 ) {
332 Ok(r) if r.returncode == 0 => {
333 println!("{} Remote branch deleted\n", style("*").green().bold());
334 }
335 _ => {
336 println!("{} Remote branch deletion failed\n", style("!").yellow());
337 }
338 }
339 }
340 }
341 }
342
343 DeletionOutcome::Deleted {
344 branch: branch_name.map(str::to_string),
345 path: worktree_path.to_path_buf(),
346 }
347}
348
349pub fn delete_worktree(
364 target: Option<&str>,
365 keep_branch: bool,
366 delete_remote: bool,
367 force: bool,
368 allow_busy: bool,
369) -> Result<()> {
370 let main_repo = git::get_main_repo_root(None)?;
371 let (worktree_path, branch_name) = resolve_delete_target(target, &main_repo)?;
372
373 let wt_resolved = git::canonicalize_or(&worktree_path);
376 let main_resolved = git::canonicalize_or(&main_repo);
377 if wt_resolved == main_resolved {
378 return Err(CwError::Git(messages::cannot_delete_main_worktree()));
379 }
380
381 if let Ok(cwd) = std::env::current_dir() {
386 let cwd_canon = cwd.canonicalize().unwrap_or(cwd);
387 let wt_canon = worktree_path
388 .canonicalize()
389 .unwrap_or_else(|_| worktree_path.clone());
390 if cwd_canon.starts_with(&wt_canon) {
391 let _ = std::env::set_current_dir(&main_repo);
392 }
393 }
394
395 let (hard, soft) = crate::operations::busy::detect_busy_tiered(&worktree_path);
396 if (!hard.is_empty() || !soft.is_empty()) && !allow_busy {
397 let branch_display = branch_name.clone().unwrap_or_else(|| {
398 worktree_path
399 .file_name()
400 .map(|n| n.to_string_lossy().to_string())
401 .unwrap_or_else(|| worktree_path.to_string_lossy().to_string())
402 });
403 let msg = crate::operations::busy_messages::render_refusal(&branch_display, &hard, &soft);
404 eprint!("{}", msg);
405 return Err(CwError::Other(format!(
406 "worktree '{}' is in use; re-run with --force to override",
407 branch_display
408 )));
409 }
410
411 let flags = RmFlags {
412 keep_branch,
413 delete_remote,
414 git_force: force,
415 allow_busy: true, };
417
418 match delete_one(&worktree_path, branch_name.as_deref(), &main_repo, flags) {
419 DeletionOutcome::Deleted { .. } => Ok(()),
420 DeletionOutcome::Skipped { reason } => Err(CwError::Other(reason)),
421 DeletionOutcome::Failed { error } => Err(error),
422 }
423}
424
425fn resolve_delete_target(
430 target: Option<&str>,
431 main_repo: &Path,
432) -> Result<(PathBuf, Option<String>)> {
433 let target = target.map(|t| t.to_string()).unwrap_or_else(|| {
434 std::env::current_dir()
435 .unwrap_or_default()
436 .to_string_lossy()
437 .to_string()
438 });
439
440 let strict = super::helpers::resolve_target_strict(main_repo, &target)?;
441 Ok((strict.path, strict.branch))
442}